-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathlint.py
executable file
·1536 lines (1348 loc) · 65.2 KB
/
lint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Linting policy for nf-core pipeline projects.
Tests Nextflow-based pipelines to check that they adhere to
the nf-core community guidelines.
"""
from rich.console import Console
from rich.markdown import Markdown
from rich.table import Table
import datetime
import fnmatch
import git
import io
import json
import logging
import os
import re
import requests
import rich
import rich.progress
import subprocess
import textwrap
import click
import requests
import yaml
import nf_core.utils
import nf_core.schema
log = logging.getLogger(__name__)
# Set up local caching for requests to speed up remote queries
nf_core.utils.setup_requests_cachedir()
# Don't pick up debug logs from the requests package
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
def run_linting(pipeline_dir, release_mode=False, show_passed=False, md_fn=None, json_fn=None):
"""Runs all nf-core linting checks on a given Nextflow pipeline project
in either `release` mode or `normal` mode (default). Returns an object
of type :class:`PipelineLint` after finished.
Args:
pipeline_dir (str): The path to the Nextflow pipeline root directory
release_mode (bool): Set this to `True`, if the linting should be run in the `release` mode.
See :class:`PipelineLint` for more information.
Returns:
An object of type :class:`PipelineLint` that contains all the linting results.
"""
# Create the lint object
lint_obj = PipelineLint(pipeline_dir)
# Run the linting tests
try:
lint_obj.lint_pipeline(release_mode)
except AssertionError as e:
log.critical("Critical error: {}".format(e))
log.info("Stopping tests...")
return lint_obj
# Print the results
lint_obj.print_results(show_passed)
# Save results to Markdown file
if md_fn is not None:
log.info("Writing lint results to {}".format(md_fn))
markdown = lint_obj.get_results_md()
with open(md_fn, "w") as fh:
fh.write(markdown)
# Save results to JSON file
if json_fn is not None:
lint_obj.save_json_results(json_fn)
# Try to post comment to a GitHub PR
lint_obj.github_comment()
# Exit code
if len(lint_obj.failed) > 0:
if release_mode:
log.info("Reminder: Lint tests were run in --release mode.")
return lint_obj
class PipelineLint(object):
"""Object to hold linting information and results.
All objects attributes are set, after the :func:`PipelineLint.lint_pipeline` function was called.
Args:
path (str): The path to the nf-core pipeline directory.
Attributes:
conda_config (dict): The parsed conda configuration file content (`environment.yml`).
conda_package_info (dict): The conda package(s) information, based on the API requests to Anaconda cloud.
config (dict): The Nextflow pipeline configuration file content.
dockerfile (list): A list of lines (str) from the parsed Dockerfile.
failed (list): A list of tuples of the form: `(<error no>, <reason>)`
files (list): A list of files found during the linting process.
minNextflowVersion (str): The minimum required Nextflow version to run the pipeline.
passed (list): A list of tuples of the form: `(<passed no>, <reason>)`
path (str): Path to the pipeline directory.
pipeline_name (str): The pipeline name, without the `nf-core` tag, for example `hlatyping`.
release_mode (bool): `True`, if you the to linting was run in release mode, `False` else.
warned (list): A list of tuples of the form: `(<warned no>, <reason>)`
**Attribute specifications**
Some of the more complex attributes of a PipelineLint object.
* `conda_config`::
# Example
{
'name': 'nf-core-hlatyping',
'channels': ['bioconda', 'conda-forge'],
'dependencies': ['optitype=1.3.2', 'yara=0.9.6']
}
* `conda_package_info`::
# See https://api.anaconda.org/package/bioconda/bioconda-utils as an example.
{
<package>: <API JSON repsonse object>
}
* `config`: Produced by calling Nextflow with :code:`nextflow config -flat <workflow dir>`. Here is an example from
the `nf-core/hlatyping <https://github.com/nf-core/hlatyping>`_ pipeline::
process.container = 'nfcore/hlatyping:1.1.1'
params.help = false
params.outdir = './results'
params.bam = false
params.single_end = false
params.seqtype = 'dna'
params.solver = 'glpk'
params.igenomes_base = './iGenomes'
params.clusterOptions = false
...
"""
def __init__(self, path):
""" Initialise linting object """
self.release_mode = False
self.version = nf_core.__version__
self.path = path
self.git_sha = None
self.files = []
self.config = {}
self.pipeline_name = None
self.minNextflowVersion = None
self.dockerfile = []
self.conda_config = {}
self.conda_package_info = {}
self.schema_obj = None
self.passed = []
self.warned = []
self.failed = []
try:
repo = git.Repo(self.path)
self.git_sha = repo.head.object.hexsha
except:
pass
# Overwrite if we have the last commit from the PR - otherwise we get a merge commit hash
if os.environ.get("GITHUB_PR_COMMIT", "") != "":
self.git_sha = os.environ["GITHUB_PR_COMMIT"]
def lint_pipeline(self, release_mode=False):
"""Main linting function.
Takes the pipeline directory as the primary input and iterates through
the different linting checks in order. Collects any warnings or errors
and returns summary at completion. Raises an exception if there is a
critical error that makes the rest of the tests pointless (eg. no
pipeline script). Results from this function are printed by the main script.
Args:
release_mode (boolean): Activates the release mode, which checks for
consistent version tags of containers. Default is `False`.
Returns:
dict: Summary of test result messages structured as follows::
{
'pass': [
( test-id (int), message (string) ),
( test-id (int), message (string) )
],
'warn': [(id, msg)],
'fail': [(id, msg)],
}
Raises:
If a critical problem is found, an ``AssertionError`` is raised.
"""
log.info("Testing pipeline: [magenta]{}".format(self.path))
if self.release_mode:
log.info("Including --release mode tests")
check_functions = [
"check_files_exist",
"check_licence",
"check_docker",
"check_nextflow_config",
"check_actions_branch_protection",
"check_actions_ci",
"check_actions_lint",
"check_actions_awstest",
"check_actions_awsfulltest",
"check_readme",
"check_conda_env_yaml",
"check_conda_dockerfile",
"check_pipeline_todos",
"check_pipeline_name",
"check_cookiecutter_strings",
"check_schema_lint",
"check_schema_params",
]
if release_mode:
self.release_mode = True
check_functions.extend(["check_version_consistency"])
progress = rich.progress.Progress(
"[bold blue]{task.description}",
rich.progress.BarColumn(bar_width=None),
"[magenta]{task.completed} of {task.total}[reset] » [bold yellow]{task.fields[func_name]}",
transient=True,
)
with progress:
lint_progress = progress.add_task(
"Running lint checks", total=len(check_functions), func_name=check_functions[0]
)
for fun_name in check_functions:
progress.update(lint_progress, advance=1, func_name=fun_name)
log.debug("Running lint test: {}".format(fun_name))
getattr(self, fun_name)()
if len(self.failed) > 0:
log.error("Found test failures in `{}`, halting lint run.".format(fun_name))
break
def check_files_exist(self):
"""Checks a given pipeline directory for required files.
Iterates through the pipeline's directory content and checkmarks files
for presence.
Files that **must** be present::
'nextflow.config',
'nextflow_schema.json',
['LICENSE', 'LICENSE.md', 'LICENCE', 'LICENCE.md'], # NB: British / American spelling
'README.md',
'CHANGELOG.md',
'docs/README.md',
'docs/output.md',
'docs/usage.md',
'.github/workflows/branch.yml',
'.github/workflows/ci.yml',
'.github/workflows/linting.yml'
Files that *should* be present::
'main.nf',
'environment.yml',
'Dockerfile',
'conf/base.config',
'.github/workflows/awstest.yml',
'.github/workflows/awsfulltest.yml'
Files that *must not* be present::
'Singularity',
'parameters.settings.json',
'bin/markdown_to_html.r'
Files that *should not* be present::
'.travis.yml'
Raises:
An AssertionError if neither `nextflow.config` or `main.nf` found.
"""
# NB: Should all be files, not directories
# List of lists. Passes if any of the files in the sublist are found.
files_fail = [
["nextflow.config"],
["nextflow_schema.json"],
["LICENSE", "LICENSE.md", "LICENCE", "LICENCE.md"], # NB: British / American spelling
["README.md"],
["CHANGELOG.md"],
[os.path.join("docs", "README.md")],
[os.path.join("docs", "output.md")],
[os.path.join("docs", "usage.md")],
[os.path.join(".github", "workflows", "branch.yml")],
[os.path.join(".github", "workflows", "ci.yml")],
[os.path.join(".github", "workflows", "linting.yml")],
]
files_warn = [
["main.nf"],
["environment.yml"],
["Dockerfile"],
[os.path.join("conf", "base.config")],
[os.path.join(".github", "workflows", "awstest.yml")],
[os.path.join(".github", "workflows", "awsfulltest.yml")],
]
# List of strings. Dails / warns if any of the strings exist.
files_fail_ifexists = ["Singularity", "parameters.settings.json", os.path.join("bin", "markdown_to_html.r")]
files_warn_ifexists = [".travis.yml"]
def pf(file_path):
return os.path.join(self.path, file_path)
# First - critical files. Check that this is actually a Nextflow pipeline
if not os.path.isfile(pf("nextflow.config")) and not os.path.isfile(pf("main.nf")):
self.failed.append((1, "File not found: nextflow.config or main.nf"))
raise AssertionError("Neither nextflow.config or main.nf found! Is this a Nextflow pipeline?")
# Files that cause an error if they don't exist
for files in files_fail:
if any([os.path.isfile(pf(f)) for f in files]):
self.passed.append((1, "File found: {}".format(self._wrap_quotes(files))))
self.files.extend(files)
else:
self.failed.append((1, "File not found: {}".format(self._wrap_quotes(files))))
# Files that cause a warning if they don't exist
for files in files_warn:
if any([os.path.isfile(pf(f)) for f in files]):
self.passed.append((1, "File found: {}".format(self._wrap_quotes(files))))
self.files.extend(files)
else:
self.warned.append((1, "File not found: {}".format(self._wrap_quotes(files))))
# Files that cause an error if they exist
for file in files_fail_ifexists:
if os.path.isfile(pf(file)):
self.failed.append((1, "File must be removed: {}".format(self._wrap_quotes(file))))
else:
self.passed.append((1, "File not found check: {}".format(self._wrap_quotes(file))))
# Files that cause a warning if they exist
for file in files_warn_ifexists:
if os.path.isfile(pf(file)):
self.warned.append((1, "File should be removed: {}".format(self._wrap_quotes(file))))
else:
self.passed.append((1, "File not found check: {}".format(self._wrap_quotes(file))))
# Load and parse files for later
if "environment.yml" in self.files:
with open(os.path.join(self.path, "environment.yml"), "r") as fh:
self.conda_config = yaml.safe_load(fh)
def check_docker(self):
"""Checks that Dockerfile contains the string ``FROM``."""
if "Dockerfile" not in self.files:
return
fn = os.path.join(self.path, "Dockerfile")
content = ""
with open(fn, "r") as fh:
content = fh.read()
# Implicitly also checks if empty.
if "FROM " in content:
self.passed.append((2, "Dockerfile check passed"))
self.dockerfile = [line.strip() for line in content.splitlines()]
return
self.failed.append((2, "Dockerfile check failed"))
def check_licence(self):
"""Checks licence file is MIT.
Currently the checkpoints are:
* licence file must be long enough (4 or more lines)
* licence contains the string *without restriction*
* licence doesn't have any placeholder variables
"""
for l in ["LICENSE", "LICENSE.md", "LICENCE", "LICENCE.md"]:
fn = os.path.join(self.path, l)
if os.path.isfile(fn):
content = ""
with open(fn, "r") as fh:
content = fh.read()
# needs at least copyright, permission, notice and "as-is" lines
nl = content.count("\n")
if nl < 4:
self.failed.append((3, "Number of lines too small for a valid MIT license file: {}".format(fn)))
return
# determine whether this is indeed an MIT
# license. Most variations actually don't contain the
# string MIT Searching for 'without restriction'
# instead (a crutch).
if not "without restriction" in content:
self.failed.append((3, "Licence file did not look like MIT: {}".format(fn)))
return
# check for placeholders present in
# - https://choosealicense.com/licenses/mit/
# - https://opensource.org/licenses/MIT
# - https://en.wikipedia.org/wiki/MIT_License
placeholders = {"[year]", "[fullname]", "<YEAR>", "<COPYRIGHT HOLDER>", "<year>", "<copyright holders>"}
if any([ph in content for ph in placeholders]):
self.failed.append((3, "Licence file contains placeholders: {}".format(fn)))
return
self.passed.append((3, "Licence check passed"))
return
self.failed.append((3, "Couldn't find MIT licence file"))
def check_nextflow_config(self):
"""Checks a given pipeline for required config variables.
At least one string in each list must be present for fail and warn.
Any config in config_fail_ifdefined results in a failure.
Uses ``nextflow config -flat`` to parse pipeline ``nextflow.config``
and print all config variables.
NB: Does NOT parse contents of main.nf / nextflow script
"""
# Fail tests if these are missing
config_fail = [
["manifest.name"],
["manifest.nextflowVersion"],
["manifest.description"],
["manifest.version"],
["manifest.homePage"],
["timeline.enabled"],
["trace.enabled"],
["report.enabled"],
["dag.enabled"],
["process.cpus"],
["process.memory"],
["process.time"],
["params.outdir"],
["params.input"],
]
# Throw a warning if these are missing
config_warn = [
["manifest.mainScript"],
["timeline.file"],
["trace.file"],
["report.file"],
["dag.file"],
["process.container"],
]
# Old depreciated vars - fail if present
config_fail_ifdefined = [
"params.version",
"params.nf_required_version",
"params.container",
"params.singleEnd",
"params.igenomesIgnore",
]
# Get the nextflow config for this pipeline
self.config = nf_core.utils.fetch_wf_config(self.path)
for cfs in config_fail:
for cf in cfs:
if cf in self.config.keys():
self.passed.append((4, "Config variable found: {}".format(self._wrap_quotes(cf))))
break
else:
self.failed.append((4, "Config variable not found: {}".format(self._wrap_quotes(cfs))))
for cfs in config_warn:
for cf in cfs:
if cf in self.config.keys():
self.passed.append((4, "Config variable found: {}".format(self._wrap_quotes(cf))))
break
else:
self.warned.append((4, "Config variable not found: {}".format(self._wrap_quotes(cfs))))
for cf in config_fail_ifdefined:
if cf not in self.config.keys():
self.passed.append((4, "Config variable (correctly) not found: {}".format(self._wrap_quotes(cf))))
else:
self.failed.append((4, "Config variable (incorrectly) found: {}".format(self._wrap_quotes(cf))))
# Check and warn if the process configuration is done with deprecated syntax
process_with_deprecated_syntax = list(
set(
[
re.search(r"^(process\.\$.*?)\.+.*$", ck).group(1)
for ck in self.config.keys()
if re.match(r"^(process\.\$.*?)\.+.*$", ck)
]
)
)
for pd in process_with_deprecated_syntax:
self.warned.append((4, "Process configuration is done with deprecated_syntax: {}".format(pd)))
# Check the variables that should be set to 'true'
for k in ["timeline.enabled", "report.enabled", "trace.enabled", "dag.enabled"]:
if self.config.get(k) == "true":
self.passed.append((4, "Config `{}` had correct value: `{}`".format(k, self.config.get(k))))
else:
self.failed.append((4, "Config `{}` did not have correct value: `{}`".format(k, self.config.get(k))))
# Check that the pipeline name starts with nf-core
try:
assert self.config.get("manifest.name", "").strip("'\"").startswith("nf-core/")
except (AssertionError, IndexError):
self.failed.append(
(
4,
"Config `manifest.name` did not begin with `nf-core/`:\n {}".format(
self.config.get("manifest.name", "").strip("'\"")
),
)
)
else:
self.passed.append((4, "Config `manifest.name` began with `nf-core/`"))
self.pipeline_name = self.config.get("manifest.name", "").strip("'").replace("nf-core/", "")
# Check that the homePage is set to the GitHub URL
try:
assert self.config.get("manifest.homePage", "").strip("'\"").startswith("https://github.com/nf-core/")
except (AssertionError, IndexError):
self.failed.append(
(
4,
"Config variable `manifest.homePage` did not begin with https://github.com/nf-core/:\n {}".format(
self.config.get("manifest.homePage", "").strip("'\"")
),
)
)
else:
self.passed.append((4, "Config variable `manifest.homePage` began with https://github.com/nf-core/"))
# Check that the DAG filename ends in `.svg`
if "dag.file" in self.config:
if self.config["dag.file"].strip("'\"").endswith(".svg"):
self.passed.append((4, "Config `dag.file` ended with `.svg`"))
else:
self.failed.append((4, "Config `dag.file` did not end with `.svg`"))
# Check that the minimum nextflowVersion is set properly
if "manifest.nextflowVersion" in self.config:
if self.config.get("manifest.nextflowVersion", "").strip("\"'").lstrip("!").startswith(">="):
self.passed.append((4, "Config variable `manifest.nextflowVersion` started with >= or !>="))
# Save self.minNextflowVersion for convenience
nextflowVersionMatch = re.search(r"[0-9\.]+(-edge)?", self.config.get("manifest.nextflowVersion", ""))
if nextflowVersionMatch:
self.minNextflowVersion = nextflowVersionMatch.group(0)
else:
self.minNextflowVersion = None
else:
self.failed.append(
(
4,
"Config `manifest.nextflowVersion` did not start with `>=` or `!>=` : `{}`".format(
self.config.get("manifest.nextflowVersion", "")
).strip("\"'"),
)
)
# Check that the process.container name is pulling the version tag or :dev
if self.config.get("process.container"):
container_name = "{}:{}".format(
self.config.get("manifest.name").replace("nf-core", "nfcore").strip("'"),
self.config.get("manifest.version", "").strip("'"),
)
if "dev" in self.config.get("manifest.version", "") or not self.config.get("manifest.version"):
container_name = "{}:dev".format(
self.config.get("manifest.name").replace("nf-core", "nfcore").strip("'")
)
try:
assert self.config.get("process.container", "").strip("'") == container_name
except AssertionError:
if self.release_mode:
self.failed.append(
(
4,
"Config `process.container` looks wrong. Should be `{}` but is `{}`".format(
container_name, self.config.get("process.container", "").strip("'")
),
)
)
else:
self.warned.append(
(
4,
"Config `process.container` looks wrong. Should be `{}` but is `{}`".format(
container_name, self.config.get("process.container", "").strip("'")
),
)
)
else:
self.passed.append((4, "Config `process.container` looks correct: `{}`".format(container_name)))
# Check that the pipeline version contains `dev`
if not self.release_mode and "manifest.version" in self.config:
if self.config["manifest.version"].strip(" '\"").endswith("dev"):
self.passed.append(
(4, "Config `manifest.version` ends in `dev`: `{}`".format(self.config["manifest.version"]))
)
else:
self.warned.append(
(
4,
"Config `manifest.version` should end in `dev`: `{}`".format(self.config["manifest.version"]),
)
)
elif "manifest.version" in self.config:
if "dev" in self.config["manifest.version"]:
self.failed.append(
(
4,
"Config `manifest.version` should not contain `dev` for a release: `{}`".format(
self.config["manifest.version"]
),
)
)
else:
self.passed.append(
(
4,
"Config `manifest.version` does not contain `dev` for release: `{}`".format(
self.config["manifest.version"]
),
)
)
def check_actions_branch_protection(self):
"""Checks that the GitHub Actions branch protection workflow is valid.
Makes sure PRs can only come from nf-core dev or 'patch' of a fork.
"""
fn = os.path.join(self.path, ".github", "workflows", "branch.yml")
if os.path.isfile(fn):
with open(fn, "r") as fh:
branchwf = yaml.safe_load(fh)
# Check that the action is turned on for PRs to master
try:
# Yaml 'on' parses as True - super weird
assert "master" in branchwf[True]["pull_request"]["branches"]
except (AssertionError, KeyError):
self.failed.append(
(5, "GitHub Actions 'branch' workflow should be triggered for PRs to master: `{}`".format(fn))
)
else:
self.passed.append(
(5, "GitHub Actions 'branch' workflow is triggered for PRs to master: `{}`".format(fn))
)
# Check that PRs are only ok if coming from an nf-core `dev` branch or a fork `patch` branch
steps = branchwf.get("jobs", {}).get("test", {}).get("steps", [])
for step in steps:
has_name = step.get("name", "").strip() == "Check PRs"
has_if = step.get("if", "").strip() == "github.repository == 'nf-core/{}'".format(
self.pipeline_name.lower()
)
# Don't use .format() as the squiggly brackets get ridiculous
has_run = step.get(
"run", ""
).strip() == '{ [[ ${{github.event.pull_request.head.repo.full_name}} == nf-core/PIPELINENAME ]] && [[ $GITHUB_HEAD_REF = "dev" ]]; } || [[ $GITHUB_HEAD_REF == "patch" ]]'.replace(
"PIPELINENAME", self.pipeline_name.lower()
)
if has_name and has_if and has_run:
self.passed.append(
(
5,
"GitHub Actions 'branch' workflow looks good: `{}`".format(fn),
)
)
break
else:
self.failed.append(
(
5,
"Couldn't find GitHub Actions 'branch' check for PRs to master: `{}`".format(fn),
)
)
def check_actions_ci(self):
"""Checks that the GitHub Actions CI workflow is valid
Makes sure tests run with the required nextflow version.
"""
fn = os.path.join(self.path, ".github", "workflows", "ci.yml")
if os.path.isfile(fn):
with open(fn, "r") as fh:
ciwf = yaml.safe_load(fh)
# Check that the action is turned on for the correct events
try:
expected = {"push": {"branches": ["dev"]}, "pull_request": None, "release": {"types": ["published"]}}
# NB: YAML dict key 'on' is evaluated to a Python dict key True
assert ciwf[True] == expected
except (AssertionError, KeyError, TypeError):
self.failed.append(
(
5,
"GitHub Actions CI is not triggered on expected events: `{}`".format(fn),
)
)
else:
self.passed.append((5, "GitHub Actions CI is triggered on expected events: `{}`".format(fn)))
# Check that we're pulling the right docker image and tagging it properly
if self.config.get("process.container", ""):
docker_notag = re.sub(r":(?:[\.\d]+|dev)$", "", self.config.get("process.container", "").strip("\"'"))
docker_withtag = self.config.get("process.container", "").strip("\"'")
# docker build
docker_build_cmd = "docker build --no-cache . -t {}".format(docker_withtag)
try:
steps = ciwf["jobs"]["test"]["steps"]
assert any([docker_build_cmd in step["run"] for step in steps if "run" in step.keys()])
except (AssertionError, KeyError, TypeError):
self.failed.append(
(
5,
"CI is not building the correct docker image. Should be: `{}`".format(docker_build_cmd),
)
)
else:
self.passed.append((5, "CI is building the correct docker image: `{}`".format(docker_build_cmd)))
# docker pull
docker_pull_cmd = "docker pull {}:dev".format(docker_notag)
try:
steps = ciwf["jobs"]["test"]["steps"]
assert any([docker_pull_cmd in step["run"] for step in steps if "run" in step.keys()])
except (AssertionError, KeyError, TypeError):
self.failed.append(
(5, "CI is not pulling the correct docker image. Should be: `{}`".format(docker_pull_cmd))
)
else:
self.passed.append((5, "CI is pulling the correct docker image: {}".format(docker_pull_cmd)))
# docker tag
docker_tag_cmd = "docker tag {}:dev {}".format(docker_notag, docker_withtag)
try:
steps = ciwf["jobs"]["test"]["steps"]
assert any([docker_tag_cmd in step["run"] for step in steps if "run" in step.keys()])
except (AssertionError, KeyError, TypeError):
self.failed.append(
(5, "CI is not tagging docker image correctly. Should be: `{}`".format(docker_tag_cmd))
)
else:
self.passed.append((5, "CI is tagging docker image correctly: {}".format(docker_tag_cmd)))
# Check that we are testing the minimum nextflow version
try:
matrix = ciwf["jobs"]["test"]["strategy"]["matrix"]["nxf_ver"]
assert any([self.minNextflowVersion in matrix])
except (KeyError, TypeError):
self.failed.append((5, "Continuous integration does not check minimum NF version: `{}`".format(fn)))
except AssertionError:
self.failed.append((5, "Minimum NF version different in CI and pipelines manifest: `{}`".format(fn)))
else:
self.passed.append((5, "Continuous integration checks minimum NF version: `{}`".format(fn)))
def check_actions_lint(self):
"""Checks that the GitHub Actions lint workflow is valid
Makes sure ``nf-core lint`` and ``markdownlint`` runs.
"""
fn = os.path.join(self.path, ".github", "workflows", "linting.yml")
if os.path.isfile(fn):
with open(fn, "r") as fh:
lintwf = yaml.safe_load(fh)
# Check that the action is turned on for push and pull requests
try:
assert "push" in lintwf[True]
assert "pull_request" in lintwf[True]
except (AssertionError, KeyError, TypeError):
self.failed.append(
(5, "GitHub Actions linting workflow must be triggered on PR and push: `{}`".format(fn))
)
else:
self.passed.append((5, "GitHub Actions linting workflow is triggered on PR and push: `{}`".format(fn)))
# Check that the Markdown linting runs
Markdownlint_cmd = "markdownlint ${GITHUB_WORKSPACE} -c ${GITHUB_WORKSPACE}/.github/markdownlint.yml"
try:
steps = lintwf["jobs"]["Markdown"]["steps"]
assert any([Markdownlint_cmd in step["run"] for step in steps if "run" in step.keys()])
except (AssertionError, KeyError, TypeError):
self.failed.append((5, "Continuous integration must run Markdown lint Tests: `{}`".format(fn)))
else:
self.passed.append((5, "Continuous integration runs Markdown lint Tests: `{}`".format(fn)))
# Check that the nf-core linting runs
nfcore_lint_cmd = "nf-core -l lint_log.txt lint ${GITHUB_WORKSPACE}"
try:
steps = lintwf["jobs"]["nf-core"]["steps"]
assert any([nfcore_lint_cmd in step["run"] for step in steps if "run" in step.keys()])
except (AssertionError, KeyError, TypeError):
self.failed.append((5, "Continuous integration must run nf-core lint Tests: `{}`".format(fn)))
else:
self.passed.append((5, "Continuous integration runs nf-core lint Tests: `{}`".format(fn)))
def check_actions_awstest(self):
"""Checks the GitHub Actions awstest is valid.
Makes sure it is triggered only on ``push`` to ``master``.
"""
fn = os.path.join(self.path, ".github", "workflows", "awstest.yml")
if os.path.isfile(fn):
with open(fn, "r") as fh:
wf = yaml.safe_load(fh)
# Check that the action is only turned on for workflow_dispatch
try:
assert "workflow_dispatch" in wf[True]
assert "push" not in wf[True]
assert "pull_request" not in wf[True]
except (AssertionError, KeyError, TypeError):
self.failed.append(
(
5,
"GitHub Actions AWS test should be triggered on workflow_dispatch and not on push or PRs: `{}`".format(
fn
),
)
)
else:
self.passed.append((5, "GitHub Actions AWS test is triggered on workflow_dispatch: `{}`".format(fn)))
def check_actions_awsfulltest(self):
"""Checks the GitHub Actions awsfulltest is valid.
Makes sure it is triggered only on ``release`` and workflow_dispatch.
"""
fn = os.path.join(self.path, ".github", "workflows", "awsfulltest.yml")
if os.path.isfile(fn):
with open(fn, "r") as fh:
wf = yaml.safe_load(fh)
aws_profile = "-profile test "
# Check that the action is only turned on for published releases
try:
assert "release" in wf[True]
assert "published" in wf[True]["release"]["types"]
assert "workflow_dispatch" in wf[True]
assert "push" not in wf[True]
assert "pull_request" not in wf[True]
except (AssertionError, KeyError, TypeError):
self.failed.append(
(
5,
"GitHub Actions AWS full test should be triggered only on published release and workflow_dispatch: `{}`".format(
fn
),
)
)
else:
self.passed.append(
(
5,
"GitHub Actions AWS full test is triggered only on published release and workflow_dispatch: `{}`".format(
fn
),
)
)
# Warn if `-profile test` is still unchanged
try:
steps = wf["jobs"]["run-awstest"]["steps"]
assert any([aws_profile in step["run"] for step in steps if "run" in step.keys()])
except (AssertionError, KeyError, TypeError):
self.passed.append((5, "GitHub Actions AWS full test should test full datasets: `{}`".format(fn)))
else:
self.warned.append((5, "GitHub Actions AWS full test should test full datasets: `{}`".format(fn)))
def check_readme(self):
"""Checks the repository README file for errors.
Currently just checks the badges at the top of the README.
"""
with open(os.path.join(self.path, "README.md"), "r") as fh:
content = fh.read()
# Check that there is a readme badge showing the minimum required version of Nextflow
# and that it has the correct version
nf_badge_re = r"\[!\[Nextflow\]\(https://img\.shields\.io/badge/nextflow-%E2%89%A5([\d\.]+)-brightgreen\.svg\)\]\(https://www\.nextflow\.io/\)"
match = re.search(nf_badge_re, content)
if match:
nf_badge_version = match.group(1).strip("'\"")
try:
assert nf_badge_version == self.minNextflowVersion
except (AssertionError, KeyError):
self.failed.append(
(
6,
"README Nextflow minimum version badge does not match config. Badge: `{}`, Config: `{}`".format(
nf_badge_version, self.minNextflowVersion
),
)
)
else:
self.passed.append(
(
6,
"README Nextflow minimum version badge matched config. Badge: `{}`, Config: `{}`".format(
nf_badge_version, self.minNextflowVersion
),
)
)
else:
self.warned.append((6, "README did not have a Nextflow minimum version badge."))
# Check that we have a bioconda badge if we have a bioconda environment file
if "environment.yml" in self.files:
bioconda_badge = "[![install with bioconda](https://img.shields.io/badge/install%20with-bioconda-brightgreen.svg)](https://bioconda.github.io/)"
if bioconda_badge in content:
self.passed.append((6, "README had a bioconda badge"))
else:
self.warned.append((6, "Found a bioconda environment.yml file but no badge in the README"))
def check_version_consistency(self):
"""Checks container tags versions.
Runs on ``process.container`` (if set) and ``$GITHUB_REF`` (if a GitHub Actions release).
Checks that:
* the container has a tag
* the version numbers are numeric
* the version numbers are the same as one-another
"""
versions = {}
# Get the version definitions
# Get version from nextflow.config
versions["manifest.version"] = self.config.get("manifest.version", "").strip(" '\"")
# Get version from the docker slug
if self.config.get("process.container", "") and not ":" in self.config.get("process.container", ""):
self.failed.append(
(
7,
"Docker slug seems not to have "
"a version tag: {}".format(self.config.get("process.container", "")),
)
)
return
# Get config container slugs, (if set; one container per workflow)
if self.config.get("process.container", ""):
versions["process.container"] = self.config.get("process.container", "").strip(" '\"").split(":")[-1]
if self.config.get("process.container", ""):
versions["process.container"] = self.config.get("process.container", "").strip(" '\"").split(":")[-1]
# Get version from the GITHUB_REF env var if this is a release
if (
os.environ.get("GITHUB_REF", "").startswith("refs/tags/")
and os.environ.get("GITHUB_REPOSITORY", "") != "nf-core/tools"
):
versions["GITHUB_REF"] = os.path.basename(os.environ["GITHUB_REF"].strip(" '\""))
# Check if they are all numeric
for v_type, version in versions.items():
if not version.replace(".", "").isdigit():
self.failed.append((7, "{} was not numeric: {}!".format(v_type, version)))
return
# Check if they are consistent
if len(set(versions.values())) != 1:
self.failed.append(
(
7,
"The versioning is not consistent between container, release tag "
"and config. Found {}".format(", ".join(["{} = {}".format(k, v) for k, v in versions.items()])),
)
)
return
self.passed.append((7, "Version tags are numeric and consistent between container, release tag and config."))
def check_conda_env_yaml(self):
"""Checks that the conda environment file is valid.
Checks that:
* a name is given and is consistent with the pipeline name
* check that dependency versions are pinned
* dependency versions are the latest available
"""
if "environment.yml" not in self.files:
return
# Check that the environment name matches the pipeline name
pipeline_version = self.config.get("manifest.version", "").strip(" '\"")
expected_env_name = "nf-core-{}-{}".format(self.pipeline_name.lower(), pipeline_version)
if self.conda_config["name"] != expected_env_name:
self.failed.append(