-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.py
More file actions
1859 lines (1565 loc) · 69 KB
/
cli.py
File metadata and controls
1859 lines (1565 loc) · 69 KB
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
"""CLI for strict-syntax-health."""
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
import httpx
import plotly.graph_objects as go
import rich_click as click
from rich.console import Console
from rich.table import Table
# API URLs
PIPELINES_URL = "https://nf-co.re/pipelines.json"
MODULES_REPO_URL = "https://github.com/nf-core/modules.git"
# Directory paths
PIPELINES_DIR = Path("pipelines")
MODULES_DIR = Path("modules")
LINT_RESULTS_DIR = Path("lint_results")
# Pipelines.json now lives inside pipelines/
PIPELINES_JSON_PATH = PIPELINES_DIR / "pipelines.json"
# README path
README_PATH = Path("README.md")
# Lint results subdirectories (named to avoid gitignore patterns matching "pipelines/" and "modules/")
PIPELINES_LINT_RESULTS_DIR = LINT_RESULTS_DIR / "pipeline-results"
MODULES_LINT_RESULTS_DIR = LINT_RESULTS_DIR / "module-results"
SUBWORKFLOWS_LINT_RESULTS_DIR = LINT_RESULTS_DIR / "subworkflow-results"
PRINTS_HELP_RESULTS_DIR = LINT_RESULTS_DIR / "prints-help-results"
console = Console()
# ============================================================================
# Git commit hash utilities for caching
# ============================================================================
def get_remote_commit_hash(repo_url: str, branch: str = "HEAD") -> str | None:
"""Get the latest commit hash from a remote repository without cloning.
Uses `git ls-remote` which only queries the remote server - no download needed.
This is the key optimization for skipping unchanged repos.
Args:
repo_url: The URL of the git repository
branch: The branch/ref to check (default: HEAD). Use "refs/heads/dev" for dev branch.
Returns:
The commit hash string, or None if the query fails.
"""
try:
result = subprocess.run(
["git", "ls-remote", repo_url, branch],
capture_output=True,
text=True,
check=True,
timeout=30,
)
if result.stdout:
return result.stdout.split()[0]
return None
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
return None
def get_local_commit_hash(repo_path: Path) -> str:
"""Get the current HEAD commit hash of a cloned repository.
Args:
repo_path: Path to the cloned git repository.
Returns:
The commit hash string.
"""
result = subprocess.run(
["git", "-C", str(repo_path), "rev-parse", "HEAD"],
capture_output=True,
text=True,
check=True,
)
return result.stdout.strip()
# ============================================================================
# Result sorting and utilities
# ============================================================================
def _sort_results(results: list[dict]) -> list[dict]:
"""Sort results by parse_error first, then errors (descending), then warnings (descending)."""
return sorted(results, key=lambda x: (not x.get("parse_error", False), -x["errors"], -x["warnings"]))
def update_pipelines_json() -> None:
"""Download the latest pipelines.json from nf-co.re."""
console.print(f"Downloading {PIPELINES_URL}...")
PIPELINES_JSON_PATH.parent.mkdir(parents=True, exist_ok=True)
response = httpx.get(PIPELINES_URL, timeout=60)
response.raise_for_status()
PIPELINES_JSON_PATH.write_bytes(response.content)
console.print(f"Updated {PIPELINES_JSON_PATH}")
def load_pipelines() -> list[dict]:
"""Load pipelines from the local pipelines.json file."""
if not PIPELINES_JSON_PATH.exists():
console.print(f"[red]{PIPELINES_JSON_PATH} not found. Run with --update-pipelines first.[/red]")
sys.exit(1)
console.print(f"Loading pipelines from {PIPELINES_JSON_PATH}...")
data = json.loads(PIPELINES_JSON_PATH.read_text())
pipelines = []
for pipeline in data.get("remote_workflows", []):
if pipeline.get("archived", False):
continue
pipelines.append(
{
"name": pipeline["name"],
"full_name": pipeline["full_name"],
"html_url": f"https://github.com/{pipeline['full_name']}",
}
)
console.print(f"Found {len(pipelines)} active pipelines")
return pipelines
def check_modules_repo_unchanged(
no_cache: bool = False, check_modules: bool = True, check_subworkflows: bool = True
) -> tuple[bool, str | None]:
"""Check if the nf-core/modules repo is unchanged from cache (without cloning).
Args:
no_cache: If True, always return False (treat as changed)
check_modules: Whether to check the modules cache
check_subworkflows: Whether to check the subworkflows cache
Returns:
Tuple of (is_unchanged, remote_commit_hash)
- is_unchanged: True if repo hasn't changed and we can use cached results
- remote_commit_hash: The remote commit hash (for updating cache later)
"""
if no_cache:
return False, None
# Get remote commit hash WITHOUT cloning
remote_commit = get_remote_commit_hash(MODULES_REPO_URL, "refs/heads/master")
if remote_commit is None:
return False, None
# Check caches for the types being linted
cache_matches = True
if check_modules:
modules_cache = load_results_dict_for_type("modules")
modules_repo_commit = modules_cache.get("_repo_commit")
if modules_repo_commit != remote_commit:
cache_matches = False
if check_subworkflows:
subworkflows_cache = load_results_dict_for_type("subworkflows")
subworkflows_repo_commit = subworkflows_cache.get("_repo_commit")
if subworkflows_repo_commit != remote_commit:
cache_matches = False
return cache_matches, remote_commit
def clone_modules_repo() -> str:
"""Clone or update the nf-core/modules repository.
Returns:
The current commit hash of the cloned/updated repository.
"""
if MODULES_DIR.exists():
console.print("Updating nf-core/modules repository...")
subprocess.run(
["git", "-C", str(MODULES_DIR), "fetch", "--quiet", "origin", "master"],
check=True,
capture_output=True,
)
subprocess.run(
["git", "-C", str(MODULES_DIR), "checkout", "--quiet", "master"],
check=True,
capture_output=True,
)
subprocess.run(
["git", "-C", str(MODULES_DIR), "pull", "--quiet"],
check=True,
capture_output=True,
)
else:
console.print("Cloning nf-core/modules repository...")
subprocess.run(
["git", "clone", "--quiet", "--depth", "1", MODULES_REPO_URL, str(MODULES_DIR)],
check=True,
capture_output=True,
)
commit_hash = get_local_commit_hash(MODULES_DIR)
console.print(f"nf-core/modules repository ready at {MODULES_DIR} ({commit_hash[:8]})")
return commit_hash
def discover_modules() -> list[dict]:
"""Discover all modules in the nf-core/modules repository."""
modules_path = MODULES_DIR / "modules" / "nf-core"
if not modules_path.exists():
console.print(f"[red]Modules path not found: {modules_path}[/red]")
return []
modules = []
# Walk through tool directories
for tool_dir in sorted(modules_path.iterdir()):
if not tool_dir.is_dir() or tool_dir.name.startswith("."):
continue
# Walk through subcommand directories
for subcommand_dir in sorted(tool_dir.iterdir()):
if not subcommand_dir.is_dir() or subcommand_dir.name.startswith("."):
continue
main_nf = subcommand_dir / "main.nf"
if main_nf.exists():
# Module name is tool_subcommand (e.g., bwa_mem)
name = f"{tool_dir.name}_{subcommand_dir.name}"
modules.append(
{
"name": name,
"path": subcommand_dir,
"html_url": (
f"https://github.com/nf-core/modules/tree/master/modules/nf-core/"
f"{tool_dir.name}/{subcommand_dir.name}"
),
}
)
console.print(f"Found {len(modules)} modules")
return modules
def discover_subworkflows() -> list[dict]:
"""Discover all subworkflows in the nf-core/modules repository."""
subworkflows_path = MODULES_DIR / "subworkflows" / "nf-core"
if not subworkflows_path.exists():
console.print(f"[red]Subworkflows path not found: {subworkflows_path}[/red]")
return []
subworkflows = []
for subworkflow_dir in sorted(subworkflows_path.iterdir()):
if not subworkflow_dir.is_dir() or subworkflow_dir.name.startswith("."):
continue
main_nf = subworkflow_dir / "main.nf"
if main_nf.exists():
subworkflows.append(
{
"name": subworkflow_dir.name,
"path": subworkflow_dir,
"html_url": (
f"https://github.com/nf-core/modules/tree/master/subworkflows/nf-core/{subworkflow_dir.name}"
),
}
)
console.print(f"Found {len(subworkflows)} subworkflows")
return subworkflows
def clone_pipeline(pipeline: dict) -> Path:
"""Clone a pipeline repository, preferring the 'dev' branch."""
repo_path = PIPELINES_DIR / pipeline["name"]
if repo_path.exists():
console.print(f" Pipeline already cloned: {pipeline['name']}")
# Try to checkout dev branch, fall back to default if it doesn't exist
try:
subprocess.run(
["git", "-C", str(repo_path), "fetch", "--quiet", "origin", "dev"],
check=True,
capture_output=True,
)
subprocess.run(
["git", "-C", str(repo_path), "checkout", "--quiet", "dev"],
check=True,
capture_output=True,
)
except subprocess.CalledProcessError:
# dev branch doesn't exist, stay on current branch
pass
# Pull latest changes
subprocess.run(
["git", "-C", str(repo_path), "pull", "--quiet"],
check=True,
capture_output=True,
)
else:
console.print(f" Cloning {pipeline['full_name']}...")
PIPELINES_DIR.mkdir(parents=True, exist_ok=True)
# Try to clone dev branch first
try:
subprocess.run(
["git", "clone", "--quiet", "--depth", "1", "--branch", "dev", pipeline["html_url"], str(repo_path)],
check=True,
capture_output=True,
)
except subprocess.CalledProcessError:
# dev branch doesn't exist, clone default branch
subprocess.run(
["git", "clone", "--quiet", "--depth", "1", pipeline["html_url"], str(repo_path)],
check=True,
capture_output=True,
)
return repo_path
def get_nextflow_version() -> str:
"""Get the current nextflow version."""
result = subprocess.run(
["nextflow", "-version"],
capture_output=True,
text=True,
)
# Parse version from output like "nextflow version 24.10.0.5928"
for line in result.stdout.split("\n"):
if "version" in line.lower():
parts = line.split()
for i, part in enumerate(parts):
if part.lower() == "version" and i + 1 < len(parts):
return parts[i + 1]
return "unknown"
def lint_component(repo_path: Path, target_path: Path | None = None) -> dict:
"""Run nextflow lint on a component (JSON output for parsing).
Args:
repo_path: The repository root path (used as cwd)
target_path: Optional specific path to lint (relative to repo_path or absolute)
"""
if target_path:
# Make path relative to repo_path if it's absolute or inside repo_path
try:
relative_path = target_path.relative_to(repo_path)
except ValueError:
relative_path = target_path
cmd = ["nextflow", "lint", str(relative_path), "-o", "json"]
else:
cmd = ["nextflow", "lint", ".", "-o", "json"]
result = subprocess.run(
cmd,
cwd=repo_path,
capture_output=True,
text=True,
)
# nextflow lint returns non-zero exit code if there are errors
# but we still want to parse the output
try:
lint_result = json.loads(result.stdout)
lint_result["parse_error"] = False
return lint_result
except json.JSONDecodeError:
name = target_path.name if target_path else repo_path.name
console.print(f"[red]Failed to parse lint output for {name}[/red]")
console.print(f"stdout: {result.stdout}")
console.print(f"stderr: {result.stderr}")
return {"summary": {"errors": 0}, "errors": [], "warnings": [], "parse_error": True}
def lint_directory_bulk(repo_path: Path, target_path: Path) -> dict:
"""Run nextflow lint on a directory containing multiple components (JSON output).
This runs lint once on the entire directory and returns all results,
which is much faster than running lint on each component individually.
Args:
repo_path: The repository root path (used as cwd)
target_path: The directory to lint (e.g., modules/nf-core or subworkflows/nf-core)
"""
try:
relative_path = target_path.relative_to(repo_path)
except ValueError:
relative_path = target_path
cmd = ["nextflow", "lint", str(relative_path), "-o", "json"]
result = subprocess.run(
cmd,
cwd=repo_path,
capture_output=True,
text=True,
)
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
console.print(f"[red]Failed to parse bulk lint output for {target_path}[/red]")
console.print(f"stdout: {result.stdout[:500]}...")
console.print(f"stderr: {result.stderr}")
return {"errors": [], "warnings": []}
def _extract_component_name_from_path(filepath: str, component_type: str) -> str | None:
"""Extract component name from a file path.
Args:
filepath: Path like 'modules/nf-core/bwa/mem/main.nf' or 'subworkflows/nf-core/foo/main.nf'
component_type: Either 'modules' or 'subworkflows'
Returns:
Component name like 'bwa_mem' for modules or 'foo' for subworkflows, or None if not matched
"""
parts = Path(filepath).parts
# Find the nf-core part and extract the component name
try:
nf_core_idx = parts.index("nf-core")
except ValueError:
return None
if component_type == "modules":
# modules/nf-core/tool/subcommand/main.nf -> tool_subcommand
if len(parts) > nf_core_idx + 2:
return f"{parts[nf_core_idx + 1]}_{parts[nf_core_idx + 2]}"
else:
# subworkflows/nf-core/name/main.nf -> name
if len(parts) > nf_core_idx + 1:
return parts[nf_core_idx + 1]
return None
def _group_lint_results_by_component(
lint_result: dict,
component_type: str,
) -> dict[str, dict]:
"""Group lint errors and warnings by component name.
Args:
lint_result: The JSON output from nextflow lint
component_type: Either 'modules' or 'subworkflows'
Returns:
Dict mapping component name to {"errors": [...], "warnings": [...]}
"""
grouped: dict[str, dict] = {}
for error in lint_result.get("errors", []):
filename = error.get("filename", "")
name = _extract_component_name_from_path(filename, component_type)
if name:
if name not in grouped:
grouped[name] = {"errors": [], "warnings": []}
grouped[name]["errors"].append(error)
for warning in lint_result.get("warnings", []):
filename = warning.get("filename", "")
name = _extract_component_name_from_path(filename, component_type)
if name:
if name not in grouped:
grouped[name] = {"errors": [], "warnings": []}
grouped[name]["warnings"].append(warning)
return grouped
def _get_code_snippet(repo_path: Path, filename: str, line_num: int, column: int) -> str | None:
"""Read a code snippet from a file for display in markdown.
Args:
repo_path: Base repository path
filename: Relative path to the file
line_num: Line number (1-indexed)
column: Column number (1-indexed)
Returns:
Formatted code snippet with caret marker, or None if file not found
"""
try:
file_path = repo_path / filename
if not file_path.exists():
return None
source_lines = file_path.read_text().splitlines()
if line_num < 1 or line_num > len(source_lines):
return None
source_line = source_lines[line_num - 1]
# Create caret marker line pointing to the column
# Account for the column being 1-indexed
caret_line = " " * (column - 1) + "^" * max(1, min(10, len(source_line) - column + 1))
return f" ```nextflow\n {source_line}\n {caret_line}\n ```"
except Exception:
return None
def _generate_markdown_from_issues(
errors: list[dict],
warnings: list[dict],
nextflow_version: str,
repo_path: Path | None = None,
) -> str:
"""Generate markdown output matching nextflow lint markdown format.
Args:
errors: List of error dicts with filename, startLine, startColumn, message
warnings: List of warning dicts with same structure
nextflow_version: Nextflow version string
repo_path: Optional repository path for reading source code snippets
Returns:
Markdown string matching nextflow lint output format
"""
now = datetime.now(timezone.utc).isoformat()
error_count = len(errors)
warning_count = len(warnings)
lines = [
"# Nextflow lint results",
"",
f"- Generated: {now}",
f"- Nextflow version: {nextflow_version}",
]
if error_count == 0 and warning_count == 0:
lines.append("- Summary: No issues found")
return "\n".join(lines)
summary_parts = []
if error_count > 0:
summary_parts.append(f"{error_count} error{'s' if error_count != 1 else ''}")
if warning_count > 0:
summary_parts.append(f"{warning_count} warning{'s' if warning_count != 1 else ''}")
lines.append(f"- Summary: {', '.join(summary_parts)}")
if errors:
lines.extend(["", "## :x: Errors", ""])
for error in errors:
filename = error.get("filename", "unknown")
line_num = error.get("startLine", 0)
col = error.get("startColumn", 0)
message = error.get("message", "")
lines.append(f"- Error: `{filename}:{line_num}:{col}`: {message}")
lines.append("")
if repo_path:
snippet = _get_code_snippet(repo_path, filename, line_num, col)
if snippet:
lines.append(snippet)
lines.append("")
if warnings:
lines.extend(["", "## :warning: Warnings", ""])
for warning in warnings:
filename = warning.get("filename", "unknown")
line_num = warning.get("startLine", 0)
col = warning.get("startColumn", 0)
message = warning.get("message", "")
lines.append(f"- Warning: `{filename}:{line_num}:{col}`: {message}")
lines.append("")
if repo_path:
snippet = _get_code_snippet(repo_path, filename, line_num, col)
if snippet:
lines.append(snippet)
lines.append("")
return "\n".join(lines)
def lint_pipeline(repo_path: Path) -> dict:
"""Run nextflow lint on a pipeline (JSON output for parsing)."""
return lint_component(repo_path)
def test_prints_help(repo_path: Path, name: str) -> bool:
"""Test if a pipeline can print help using the v2 syntax parser.
Runs: NXF_SYNTAX_PARSER=v2 nextflow run . --help
Args:
repo_path: Path to the cloned pipeline repository.
name: Pipeline name (used for saving output file).
Returns:
True if the command succeeds (exit code 0), False otherwise.
"""
PRINTS_HELP_RESULTS_DIR.mkdir(parents=True, exist_ok=True)
output_file = PRINTS_HELP_RESULTS_DIR / f"{name}_help.txt"
try:
env = {**os.environ, "NXF_SYNTAX_PARSER": "v2"}
# Use stderr=STDOUT to interleave stdout and stderr as they would appear in a terminal
result = subprocess.run(
["nextflow", "run", ".", "--help"],
cwd=repo_path,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=120,
env=env,
)
# Save combined output to file
output_content = f"$ NXF_SYNTAX_PARSER=v2 nextflow run . --help\n\n{result.stdout}"
output_file.write_text(output_content)
return result.returncode == 0
except subprocess.TimeoutExpired:
console.print("[dim] --help test timed out[/dim]")
output_file.write_text("$ NXF_SYNTAX_PARSER=v2 nextflow run . --help\n\nError: Timeout after 120s\n")
return False
except Exception as e:
console.print(f"[dim] --help test failed: {e}[/dim]")
output_file.write_text(f"$ NXF_SYNTAX_PARSER=v2 nextflow run . --help\n\nError: {e}\n")
return False
def lint_component_markdown(repo_path: Path, name: str, output_dir: Path, target_path: Path | None = None) -> None:
"""Run nextflow lint on a component and save markdown output to file."""
output_dir.mkdir(parents=True, exist_ok=True)
output_file = output_dir / f"{name}_lint.md"
# Build command - if target_path specified, lint that specific path
if target_path:
# Make path relative to repo_path if it's absolute or inside repo_path
try:
relative_path = target_path.relative_to(repo_path)
except ValueError:
relative_path = target_path
cmd = ["nextflow", "lint", str(relative_path), "-o", "markdown"]
else:
cmd = ["nextflow", "lint", ".", "-o", "markdown"]
result = subprocess.run(
cmd,
cwd=repo_path,
capture_output=True,
text=True,
)
# Combine stdout and stderr for full output
output = result.stdout
if result.stderr:
output += "\n" + result.stderr
output_file.write_text(output)
console.print(f" Saved lint output to {output_file}")
def run_pipeline_lint(pipelines: list[dict], no_cache: bool = False) -> list[dict]:
"""Clone and lint all pipelines, using commit cache to skip unchanged repos.
Args:
pipelines: List of pipeline dicts with name, full_name, html_url
no_cache: If True, ignore cache and re-lint everything
"""
commits_cache = load_results_dict_for_type("pipelines")
results = []
skipped_count = 0
linted_count = 0
for pipeline in pipelines:
name = pipeline["name"]
cached = commits_cache.get(name)
# BEFORE cloning: check if we can skip by comparing remote commit hash
if not no_cache and cached:
# Try dev branch first, then HEAD (default branch)
remote_commit = get_remote_commit_hash(pipeline["html_url"], "refs/heads/dev")
if remote_commit is None:
remote_commit = get_remote_commit_hash(pipeline["html_url"], "HEAD")
# Check if we need to run prints_help test for pipelines with zero errors
# that were cached before this feature was added
needs_prints_help = (
cached.get("errors", 0) == 0
and not cached.get("parse_error", False)
and cached.get("prints_help") is None
)
if remote_commit and remote_commit == cached.get("commit") and not needs_prints_help:
console.print(f"[dim]Skipping {name} (unchanged at {remote_commit[:8]})[/dim]")
results.append(
{
"name": name,
"full_name": pipeline["full_name"],
"html_url": pipeline["html_url"],
"commit": remote_commit,
"errors": cached["errors"],
"warnings": cached["warnings"],
"parse_error": cached.get("parse_error", False),
"prints_help": cached.get("prints_help"),
"lint_details": {}, # Don't store full details in cache
}
)
skipped_count += 1
continue
# Cache miss or commit changed - need to clone and lint
console.print(f"Processing pipeline {name}...")
try:
repo_path = clone_pipeline(pipeline)
commit_hash = get_local_commit_hash(repo_path)
lint_result = lint_pipeline(repo_path)
lint_component_markdown(repo_path, name, PIPELINES_LINT_RESULTS_DIR)
error_count = lint_result.get("summary", {}).get("errors", 0)
warning_count = len(lint_result.get("warnings", []))
parse_error = lint_result.get("parse_error", False)
# Run prints_help test only if there are no errors
prints_help = None
if not parse_error and error_count == 0:
console.print(" Testing --help with v2 parser...")
prints_help = test_prints_help(repo_path, name)
if prints_help:
console.print(" [green]--help test passed[/green]")
else:
console.print(" [yellow]--help test failed[/yellow]")
results.append(
{
"name": name,
"full_name": pipeline["full_name"],
"html_url": pipeline["html_url"],
"commit": commit_hash,
"errors": error_count,
"warnings": warning_count,
"parse_error": parse_error,
"prints_help": prints_help,
"lint_details": lint_result,
}
)
linted_count += 1
except subprocess.CalledProcessError as e:
console.print(f"[red]Failed to process {name}: {e}[/red]")
results.append(
{
"name": name,
"full_name": pipeline["full_name"],
"html_url": pipeline["html_url"],
"errors": 0,
"warnings": 0,
"parse_error": True,
"prints_help": None,
"lint_details": {},
}
)
linted_count += 1
if skipped_count > 0:
console.print(f"[green]Skipped {skipped_count} unchanged pipelines, linted {linted_count}[/green]")
return results
def run_modules_lint(modules: list[dict], nextflow_version: str = "unknown") -> list[dict]:
"""Lint all modules using bulk lint for efficiency.
Args:
modules: List of module dicts with name, path, html_url
nextflow_version: Nextflow version string for markdown output
"""
# Check if we're filtering to specific modules (small list)
# If so, use individual linting for accuracy; otherwise use bulk
if len(modules) <= 5:
results = _run_modules_lint_individual(modules, nextflow_version)
else:
results = _run_modules_lint_bulk(modules, nextflow_version)
return results
def load_cached_modules_results(modules: list[dict]) -> list[dict]:
"""Load cached lint results for modules when repo is unchanged.
Args:
modules: List of module dicts with name, path, html_url
Returns:
List of result dicts with cached error/warning counts
"""
results_cache = load_results_dict_for_type("modules")
results = []
for module in modules:
name = module["name"]
cached = results_cache.get(name, {})
results.append(
{
"name": name,
"html_url": module["html_url"],
"errors": cached.get("errors", 0),
"warnings": cached.get("warnings", 0),
"parse_error": cached.get("parse_error", False),
"lint_details": {},
}
)
return results
def _run_modules_lint_individual(modules: list[dict], nextflow_version: str) -> list[dict]:
"""Lint modules individually (used when filtering to specific modules)."""
results = []
for module in modules:
console.print(f"Processing module {module['name']}...")
try:
lint_result = lint_component(MODULES_DIR, module["path"])
lint_component_markdown(MODULES_DIR, module["name"], MODULES_LINT_RESULTS_DIR, module["path"])
results.append(
{
"name": module["name"],
"html_url": module["html_url"],
"errors": lint_result.get("summary", {}).get("errors", 0),
"warnings": len(lint_result.get("warnings", [])),
"parse_error": lint_result.get("parse_error", False),
"lint_details": lint_result,
}
)
except subprocess.CalledProcessError as e:
console.print(f"[red]Failed to process module {module['name']}: {e}[/red]")
results.append(
{
"name": module["name"],
"html_url": module["html_url"],
"errors": 0,
"warnings": 0,
"parse_error": True,
"lint_details": {},
}
)
return results
def _run_modules_lint_bulk(modules: list[dict], nextflow_version: str) -> list[dict]:
"""Lint all modules at once using bulk lint (much faster)."""
console.print(f"Running bulk lint on {len(modules)} modules...")
# Run lint once on the entire modules/nf-core directory
modules_path = MODULES_DIR / "modules" / "nf-core"
bulk_result = lint_directory_bulk(MODULES_DIR, modules_path)
# Group results by component name
grouped = _group_lint_results_by_component(bulk_result, "modules")
# Generate results and markdown files for each module
results = []
MODULES_LINT_RESULTS_DIR.mkdir(parents=True, exist_ok=True)
for module in modules:
name = module["name"]
component_issues = grouped.get(name, {"errors": [], "warnings": []})
errors = component_issues["errors"]
warnings = component_issues["warnings"]
# Generate markdown file
markdown_content = _generate_markdown_from_issues(errors, warnings, nextflow_version, MODULES_DIR)
output_file = MODULES_LINT_RESULTS_DIR / f"{name}_lint.md"
output_file.write_text(markdown_content)
results.append(
{
"name": name,
"html_url": module["html_url"],
"errors": len(errors),
"warnings": len(warnings),
"parse_error": False,
"lint_details": {"errors": errors, "warnings": warnings},
}
)
console.print(f"Generated {len(results)} module lint reports")
return results
def run_subworkflows_lint(subworkflows: list[dict], nextflow_version: str = "unknown") -> list[dict]:
"""Lint all subworkflows using bulk lint for efficiency.
Args:
subworkflows: List of subworkflow dicts with name, path, html_url
nextflow_version: Nextflow version string for markdown output
"""
# Check if we're filtering to specific subworkflows (small list)
# If so, use individual linting for accuracy; otherwise use bulk
if len(subworkflows) <= 5:
results = _run_subworkflows_lint_individual(subworkflows, nextflow_version)
else:
results = _run_subworkflows_lint_bulk(subworkflows, nextflow_version)
return results
def load_cached_subworkflows_results(subworkflows: list[dict]) -> list[dict]:
"""Load cached lint results for subworkflows when repo is unchanged.
Args:
subworkflows: List of subworkflow dicts with name, path, html_url
Returns:
List of result dicts with cached error/warning counts
"""
results_cache = load_results_dict_for_type("subworkflows")
results = []
for subworkflow in subworkflows:
name = subworkflow["name"]
cached = results_cache.get(name, {})
results.append(
{
"name": name,
"html_url": subworkflow["html_url"],
"errors": cached.get("errors", 0),
"warnings": cached.get("warnings", 0),
"parse_error": cached.get("parse_error", False),
"lint_details": {},
}
)
return results
def _run_subworkflows_lint_individual(subworkflows: list[dict], nextflow_version: str) -> list[dict]:
"""Lint subworkflows individually (used when filtering to specific subworkflows)."""
results = []
for subworkflow in subworkflows:
console.print(f"Processing subworkflow {subworkflow['name']}...")
try:
lint_result = lint_component(MODULES_DIR, subworkflow["path"])
lint_component_markdown(
MODULES_DIR, subworkflow["name"], SUBWORKFLOWS_LINT_RESULTS_DIR, subworkflow["path"]
)
results.append(
{
"name": subworkflow["name"],
"html_url": subworkflow["html_url"],
"errors": lint_result.get("summary", {}).get("errors", 0),
"warnings": len(lint_result.get("warnings", [])),
"parse_error": lint_result.get("parse_error", False),
"lint_details": lint_result,
}
)
except subprocess.CalledProcessError as e:
console.print(f"[red]Failed to process subworkflow {subworkflow['name']}: {e}[/red]")
results.append(
{
"name": subworkflow["name"],
"html_url": subworkflow["html_url"],
"errors": 0,
"warnings": 0,
"parse_error": True,
"lint_details": {},
}
)
return results
def _run_subworkflows_lint_bulk(subworkflows: list[dict], nextflow_version: str) -> list[dict]:
"""Lint all subworkflows at once using bulk lint (much faster)."""
console.print(f"Running bulk lint on {len(subworkflows)} subworkflows...")
# Run lint once on the entire subworkflows/nf-core directory
subworkflows_path = MODULES_DIR / "subworkflows" / "nf-core"
bulk_result = lint_directory_bulk(MODULES_DIR, subworkflows_path)
# Group results by component name
grouped = _group_lint_results_by_component(bulk_result, "subworkflows")
# Generate results and markdown files for each subworkflow
results = []
SUBWORKFLOWS_LINT_RESULTS_DIR.mkdir(parents=True, exist_ok=True)
for subworkflow in subworkflows:
name = subworkflow["name"]
component_issues = grouped.get(name, {"errors": [], "warnings": []})
errors = component_issues["errors"]
warnings = component_issues["warnings"]
# Generate markdown file
markdown_content = _generate_markdown_from_issues(errors, warnings, nextflow_version, MODULES_DIR)
output_file = SUBWORKFLOWS_LINT_RESULTS_DIR / f"{name}_lint.md"
output_file.write_text(markdown_content)