patchloop 0.3.0__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
patchloop/cli.py CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  import signal
6
7
  import sys
7
8
  from pathlib import Path
@@ -21,9 +22,18 @@ from patchloop.github import GitHubError
21
22
  from patchloop.hints import hint_for
22
23
  from patchloop.images import ImageScanError, parse_scanners
23
24
  from patchloop.models import ExitCode, Severity
24
- from patchloop.report.console import render_fix, render_scan
25
- from patchloop.report.json_out import write_scan_json
25
+ from patchloop.report.console import (
26
+ FixRow,
27
+ ScanRow,
28
+ overall_exit_code,
29
+ render_fix,
30
+ render_fix_summary,
31
+ render_scan,
32
+ render_scan_summary,
33
+ )
34
+ from patchloop.report.json_out import scan_payload, write_scan_json
26
35
  from patchloop.report.sarif import build_sarif, remaining, write_sarif
36
+ from patchloop.report.sarif import merge as merge_sarif
27
37
  from patchloop.runner import FixError, run_fix
28
38
  from patchloop.scanner import resolve_imports, run_scan
29
39
  from patchloop.schedule import (
@@ -36,11 +46,25 @@ from patchloop.schedule import (
36
46
  write_workflow,
37
47
  )
38
48
  from patchloop.sources.base import SourceError
49
+ from patchloop.targets import Target, TargetError
50
+ from patchloop.targets import select as select_targets
39
51
  from patchloop.worktree import WorktreeError
40
52
 
41
53
  app = typer.Typer(
42
54
  name="patchloop",
43
- help="Scan a Python project for vulnerable dependencies, fix them, test, rescan, open one PR.",
55
+ help="Fix vulnerable dependencies in Python and JavaScript projects: upgrade, test, "
56
+ "rescan, and open one pull request.",
57
+ epilog=(
58
+ "What do you want to do?\n\n"
59
+ " Check my setup ............. patchloop doctor\n\n"
60
+ " See what is vulnerable ..... patchloop scan\n\n"
61
+ " Preview the fixes .......... patchloop fix --dry-run\n\n"
62
+ " Fix on a local branch ...... patchloop fix --no-push\n\n"
63
+ " Fix and open a PR .......... patchloop fix\n\n"
64
+ " Run it every week on GitHub patchloop schedule\n\n"
65
+ "Run `patchloop COMMAND --help` for a command's options. "
66
+ "Docs: https://ayushsingh012.github.io/PatchLoop/"
67
+ ),
44
68
  no_args_is_help=True,
45
69
  add_completion=False,
46
70
  )
@@ -51,6 +75,26 @@ PathArg = Annotated[
51
75
  Path,
52
76
  typer.Argument(exists=True, file_okay=False, resolve_path=True, help="Project directory."),
53
77
  ]
78
+ PathsArg = Annotated[
79
+ list[Path] | None,
80
+ typer.Argument(
81
+ exists=True,
82
+ file_okay=False,
83
+ resolve_path=True,
84
+ show_default=False,
85
+ help="Project folder(s). Default: this folder.",
86
+ ),
87
+ ]
88
+ AllOpt = Annotated[
89
+ bool,
90
+ typer.Option(
91
+ "--all", help="Every project found in the folder(s), including ones inside projects."
92
+ ),
93
+ ]
94
+ SkipOpt = Annotated[
95
+ list[str] | None,
96
+ typer.Option("--skip", help="Leave out this project folder, e.g. legacy/app. Repeatable."),
97
+ ]
54
98
  ImportOpt = Annotated[
55
99
  list[Path] | None,
56
100
  typer.Option(
@@ -125,7 +169,7 @@ def main(
125
169
  typer.Option("--version", callback=_version_callback, is_eager=True, help="Show version."),
126
170
  ] = False,
127
171
  ) -> None:
128
- """PatchLoop v1."""
172
+ """PatchLoop: fix vulnerable dependencies, test, rescan, open one PR."""
129
173
  # A kill (SIGTERM) unwinds like Ctrl+C, so the temporary worktree is removed and a
130
174
  # running install or test command is stopped with it.
131
175
  signal.signal(signal.SIGTERM, _exit_on_sigterm)
@@ -135,9 +179,12 @@ def _exit_on_sigterm(signum: int, frame: object) -> NoReturn:
135
179
  raise SystemExit(128 + signum)
136
180
 
137
181
 
138
- @app.command("doctor")
182
+ @app.command(
183
+ "doctor",
184
+ epilog="Run this first on a new machine. Exit code 2 means a required tool is missing.",
185
+ )
139
186
  def doctor_cmd(path: PathArg = Path(), config: ConfigOpt = None) -> None:
140
- """Check the tools PatchLoop uses, and show how to install any that are missing."""
187
+ """Check that the tools PatchLoop needs are installed, and how to install any missing."""
141
188
  cfg = _load_config_or_exit(path, config)
142
189
  if sys.platform == "win32":
143
190
  err_console.print(
@@ -257,9 +304,155 @@ def parse_severity_option(value: str | None) -> set[Severity] | None:
257
304
  return wanted or None
258
305
 
259
306
 
260
- @app.command("scan")
307
+ _STOPS = (
308
+ ConfigError,
309
+ DetectError,
310
+ SourceError,
311
+ ImageScanError,
312
+ BuildError,
313
+ WorktreeError,
314
+ FixError,
315
+ LockError,
316
+ GitError,
317
+ GitHubError,
318
+ )
319
+
320
+
321
+ def _targets(
322
+ paths: list[Path] | None, all_projects: bool, skip: list[str] | None, *, expand: bool
323
+ ) -> list[Target]:
324
+ try:
325
+ targets = select_targets(
326
+ paths or [Path()], all_projects=all_projects, expand=expand, skip=skip
327
+ )
328
+ except TargetError as exc:
329
+ _fail(exc)
330
+ return targets
331
+
332
+
333
+ def _project_config(path: Path, file: Path | None, min_severity: str | None) -> Config:
334
+ return with_min_severity(load_config(path, file), min_severity)
335
+
336
+
337
+ def _scan_many(
338
+ targets: list[Target],
339
+ severity: str | None,
340
+ min_severity: str | None,
341
+ config: Path | None,
342
+ json_out: Path | None,
343
+ sarif_out: Path | None,
344
+ ) -> NoReturn:
345
+ only = parse_severity_option(severity)
346
+ rows: list[ScanRow] = []
347
+ for t in targets:
348
+ err_console.print(f"[dim]Scanning {t.label}…[/dim]", highlight=False)
349
+ try:
350
+ cfg = _project_config(t.path, config, min_severity)
351
+ result = run_scan(t.path, cfg, only, imports=resolve_imports(t.path, cfg, None))
352
+ except _STOPS as exc:
353
+ rows.append(ScanRow(t.label, error=str(exc)))
354
+ continue
355
+ rows.append(ScanRow(t.label, result))
356
+ render_scan_summary(rows, console)
357
+ if json_out is not None:
358
+ projects = [
359
+ {"project": r.label, **scan_payload(r.result)}
360
+ if r.result
361
+ else {"project": r.label, "error": r.error}
362
+ for r in rows
363
+ ]
364
+ json_out.write_text(json.dumps({"projects": projects}, indent=2) + "\n", "utf-8")
365
+ console.print(f"JSON report: {json_out}")
366
+ if sarif_out is not None:
367
+ payloads = []
368
+ for r in rows:
369
+ if r.result is not None:
370
+ lock = r.result.project.lockfile
371
+ payloads.append(build_sarif(r.result.shown, lock, lockfile_uri(lock)))
372
+ write_sarif(merge_sarif(payloads), sarif_out)
373
+ console.print(f"SARIF report: {sarif_out}")
374
+ raise typer.Exit(overall_exit_code([r.exit_code for r in rows]))
375
+
376
+
377
+ def _fix_many(
378
+ targets: list[Target],
379
+ severity: str | None,
380
+ min_severity: str | None,
381
+ config: Path | None,
382
+ json_out: Path | None,
383
+ sarif_out: Path | None,
384
+ *,
385
+ dry_run: bool,
386
+ no_push: bool,
387
+ keep_worktree: bool,
388
+ ) -> NoReturn:
389
+ only = parse_severity_option(severity)
390
+ rows: list[FixRow] = []
391
+ for i, t in enumerate(targets, 1):
392
+ console.rule(f"{t.label} ({i}/{len(targets)})")
393
+ try:
394
+ cfg = _project_config(t.path, config, min_severity)
395
+ outcome = run_fix(
396
+ t.path, cfg, only, dry_run=dry_run, push_pr=not no_push,
397
+ keep_worktree=keep_worktree, imports=resolve_imports(t.path, cfg, None),
398
+ ) # fmt: skip
399
+ except _STOPS as exc:
400
+ err_console.print(f"[red]Error:[/red] {exc}", highlight=False)
401
+ hint = hint_for(exc)
402
+ if hint:
403
+ err_console.print(f"[yellow]Fix:[/yellow] {hint}", highlight=False)
404
+ rows.append(FixRow(t.label, error=str(exc)))
405
+ continue
406
+ render_fix(outcome, console)
407
+ rows.append(FixRow(t.label, outcome))
408
+ console.rule("Summary")
409
+ render_fix_summary(rows, console)
410
+ if json_out is not None:
411
+ projects = [
412
+ {
413
+ "project": r.label,
414
+ "report": json.loads(r.outcome.report.model_dump_json())
415
+ if r.outcome and r.outcome.report
416
+ else None,
417
+ "error": r.error or None,
418
+ }
419
+ for r in rows
420
+ ]
421
+ json_out.write_text(json.dumps({"projects": projects}, indent=2) + "\n", "utf-8")
422
+ console.print(f"JSON report: {json_out}")
423
+ if sarif_out is not None:
424
+ payloads = []
425
+ for r in rows:
426
+ report = r.outcome.report if r.outcome else None
427
+ if r.outcome is None or report is None or r.outcome.scan is None:
428
+ continue
429
+ every = {f.key: f for f in [*report.findings_after, *report.findings_before]}
430
+ still_open = remaining(list(every.values()), report.results)
431
+ lock = r.outcome.scan.project.lockfile
432
+ statuses = {x.finding_key: x for x in report.results}
433
+ payloads.append(build_sarif(still_open, lock, lockfile_uri(lock), statuses))
434
+ write_sarif(merge_sarif(payloads), sarif_out)
435
+ console.print(f"SARIF report: {sarif_out}")
436
+ raise typer.Exit(overall_exit_code([r.exit_code for r in rows]))
437
+
438
+
439
+ @app.command(
440
+ "scan",
441
+ epilog=(
442
+ "Examples:\n\n"
443
+ " patchloop scan HIGH and CRITICAL findings in this folder\n\n"
444
+ " patchloop scan --min-severity LOW every finding\n\n"
445
+ " patchloop scan apps/web --json r.json\n\n"
446
+ " patchloop scan --image myapp:latest also scan a container image\n\n"
447
+ " patchloop scan in a folder of repos: every project in it\n\n"
448
+ " patchloop scan server client just these project folders\n\n"
449
+ "Exit code: 0 nothing found, 1 findings, 2 error."
450
+ ),
451
+ )
261
452
  def scan_cmd(
262
- path: PathArg = Path(),
453
+ paths: PathsArg = None,
454
+ all_projects: AllOpt = False,
455
+ skip: SkipOpt = None,
263
456
  imports: ImportOpt = None,
264
457
  image: ImageOpt = None,
265
458
  scanner: ScannerOpt = None,
@@ -273,7 +466,13 @@ def scan_cmd(
273
466
  json_out: Annotated[Path | None, typer.Option("--json", help="Write a JSON report.")] = None,
274
467
  sarif_out: Annotated[Path | None, typer.Option("--sarif", help="Write a SARIF report.")] = None,
275
468
  ) -> None:
276
- """Collect, merge and prioritize findings. Changes nothing."""
469
+ """Show which dependencies are vulnerable. Changes nothing."""
470
+ targets = _targets(paths, all_projects, skip, expand=True)
471
+ if len(targets) > 1:
472
+ if imports or image or build or dockerfile or build_arg:
473
+ _fail("--import, --image and --build work on one project at a time")
474
+ _scan_many(targets, severity, min_severity, config, json_out, sarif_out)
475
+ path = targets[0].path
277
476
  cfg = with_images(
278
477
  with_min_severity(_load_config_or_exit(path, config), min_severity),
279
478
  image,
@@ -301,9 +500,24 @@ def scan_cmd(
301
500
  raise typer.Exit(ExitCode.FINDINGS_REMAIN)
302
501
 
303
502
 
304
- @app.command("fix")
503
+ @app.command(
504
+ "fix",
505
+ epilog=(
506
+ "Examples:\n\n"
507
+ " patchloop fix --dry-run show the planned upgrades; change nothing\n\n"
508
+ " patchloop fix --no-push upgrade, test, rescan; commit to a local branch only\n\n"
509
+ " patchloop fix the same, then open or update the pull request\n\n"
510
+ " patchloop fix backend a project in a subfolder (each folder gets its own PR)\n\n"
511
+ " patchloop fix --all every project in the folder, one PR each\n\n"
512
+ " patchloop fix --all --skip legacy all but some\n\n"
513
+ "Your own checkout is never touched: the work happens in a temporary copy. "
514
+ "Exit code: 0 nothing left to fix, 1 findings remain, 2 error."
515
+ ),
516
+ )
305
517
  def fix_cmd(
306
- path: PathArg = Path(),
518
+ paths: PathsArg = None,
519
+ all_projects: AllOpt = False,
520
+ skip: SkipOpt = None,
307
521
  imports: ImportOpt = None,
308
522
  image: ImageOpt = None,
309
523
  scanner: ScannerOpt = None,
@@ -331,7 +545,16 @@ def fix_cmd(
331
545
  Path | None, typer.Option("--sarif", help="Write the findings still open as SARIF.")
332
546
  ] = None,
333
547
  ) -> None:
334
- """Full loop in a temporary worktree, then open or update the one PR."""
548
+ """Upgrade vulnerable dependencies, run your tests, rescan, and open one PR."""
549
+ targets = _targets(paths, all_projects, skip, expand=False)
550
+ if len(targets) > 1:
551
+ if imports or image or build or dockerfile or build_arg:
552
+ _fail("--import, --image and --build work on one project at a time")
553
+ _fix_many(
554
+ targets, severity, min_severity, config, json_out, sarif_out,
555
+ dry_run=dry_run, no_push=no_push, keep_worktree=keep_worktree,
556
+ ) # fmt: skip
557
+ path = targets[0].path
335
558
  cfg = with_images(
336
559
  with_min_severity(_load_config_or_exit(path, config), min_severity),
337
560
  image,
@@ -379,7 +602,16 @@ def fix_cmd(
379
602
  raise typer.Exit(outcome.exit_code)
380
603
 
381
604
 
382
- @app.command("schedule")
605
+ @app.command(
606
+ "schedule",
607
+ epilog=(
608
+ "Examples:\n\n"
609
+ " patchloop schedule every Monday at 06:00 UTC\n\n"
610
+ " patchloop schedule --every day --at 22:00\n\n"
611
+ ' patchloop schedule apps/web --cron "0 6 * * 1-5"\n\n'
612
+ "It only writes the workflow file; commit and push it to start the schedule."
613
+ ),
614
+ )
383
615
  def schedule_cmd(
384
616
  path: PathArg = Path(),
385
617
  every: Annotated[
@@ -393,7 +625,7 @@ def schedule_cmd(
393
625
  min_severity: MinSeverityOpt = None,
394
626
  force: Annotated[bool, typer.Option("--force", help="Replace an existing workflow.")] = False,
395
627
  ) -> None:
396
- """Run PatchLoop on a schedule on GitHub's servers (writes a GitHub Actions workflow)."""
628
+ """Run PatchLoop on a schedule on GitHub's servers (writes a workflow file)."""
397
629
  if min_severity is not None:
398
630
  try:
399
631
  Severity(min_severity.upper())
patchloop/detect.py CHANGED
@@ -61,7 +61,7 @@ def _not_a_project(root: Path, what: str) -> DetectError:
61
61
  listed = ", ".join(below[:10]) + (f" and {len(below) - 10} more" if len(below) > 10 else "")
62
62
  return DetectError(
63
63
  f"{what} in {root}; it holds separate projects: {listed}. "
64
- "Run PatchLoop on each folder (each gets its own PR)"
64
+ "Name one (each gets its own PR), or use --all for every one"
65
65
  )
66
66
  return DetectError(f"{what} in {root}")
67
67
 
patchloop/hints.py CHANGED
@@ -25,7 +25,12 @@ _CREDENTIALS = (
25
25
 
26
26
  # (error type, text in the message or "" for any, hint). First match wins.
27
27
  _HINTS: list[tuple[type[Exception], str, str]] = [
28
- (ConfigError, "", "fix patchloop.yml; the README lists every key and its default"),
28
+ (
29
+ ConfigError,
30
+ "",
31
+ "fix patchloop.yml; every key and its default: "
32
+ "https://ayushsingh012.github.io/PatchLoop/configuration/",
33
+ ),
29
34
  (BuildError, "no value", "export the build arg's value first, or pass --build-arg NAME=VALUE"),
30
35
  (BuildError, "no Dockerfile", "pass --dockerfile path/to/Dockerfile (relative to the project)"),
31
36
  (BuildError, "not installed", "install Docker and start it, then run `patchloop doctor`"),
@@ -53,7 +58,8 @@ _HINTS: list[tuple[type[Exception], str, str]] = [
53
58
  (
54
59
  DetectError,
55
60
  "separate projects",
56
- "run it once per folder, e.g. `patchloop fix backend`; each folder gets its own PR branch",
61
+ "`patchloop fix --all` fixes every project (one PR each), or name one: "
62
+ "`patchloop fix backend`",
57
63
  ),
58
64
  (
59
65
  DetectError,
@@ -3,11 +3,12 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from collections import Counter
6
+ from dataclasses import dataclass
6
7
 
7
8
  from rich.console import Console
8
9
  from rich.table import Table
9
10
 
10
- from patchloop.models import Finding, FixStatus, Severity
11
+ from patchloop.models import ExitCode, Finding, FixStatus, Severity
11
12
  from patchloop.runner import FixOutcome
12
13
  from patchloop.scanner import ScanResult
13
14
  from patchloop.versions import is_major_upgrade
@@ -241,3 +242,116 @@ def render_publish(outcome: FixOutcome, console: Console) -> None:
241
242
  console.print(f"[yellow]{outcome.pr_note}[/yellow]")
242
243
  for warning in outcome.warnings:
243
244
  console.print(f"[yellow]Warning: {warning}[/yellow]")
245
+
246
+
247
+ # --- several projects in one run ---------------------------------------------------------
248
+
249
+
250
+ @dataclass
251
+ class ScanRow:
252
+ label: str
253
+ result: ScanResult | None = None
254
+ error: str = ""
255
+
256
+ @property
257
+ def exit_code(self) -> int:
258
+ if self.error:
259
+ return ExitCode.ERROR
260
+ return ExitCode.FINDINGS_REMAIN if self.result and self.result.shown else ExitCode.OK
261
+
262
+
263
+ @dataclass
264
+ class FixRow:
265
+ label: str
266
+ outcome: FixOutcome | None = None
267
+ error: str = ""
268
+
269
+ @property
270
+ def exit_code(self) -> int:
271
+ if self.error or self.outcome is None:
272
+ return ExitCode.ERROR
273
+ return int(self.outcome.exit_code)
274
+
275
+
276
+ def overall_exit_code(codes: list[int]) -> int:
277
+ """2 if any project failed, else 1 if findings remain anywhere, else 0."""
278
+ for code in (ExitCode.ERROR, ExitCode.FINDINGS_REMAIN):
279
+ if code in codes:
280
+ return int(code)
281
+ return int(ExitCode.OK)
282
+
283
+
284
+ def _short(text: str, limit: int = 90) -> str:
285
+ line = text.strip().splitlines()[0] if text.strip() else ""
286
+ return line if len(line) <= limit else line[: limit - 1] + "…"
287
+
288
+
289
+ def render_scan_summary(rows: list[ScanRow], console: Console) -> None:
290
+ table = Table(title=f"{len(rows)} projects", header_style="bold", title_justify="left")
291
+ table.add_column("Project", overflow="fold")
292
+ table.add_column("Type")
293
+ for name in ("Findings", "Critical", "High", "Medium", "Low"):
294
+ table.add_column(name, justify="right")
295
+ table.add_column("Note", overflow="fold")
296
+ for row in rows:
297
+ if row.result is None:
298
+ table.add_row(row.label, "", "", "", "", "", "", f"[red]{_short(row.error)}[/red]")
299
+ continue
300
+ shown = row.result.shown
301
+ counts = Counter(f.severity for f in shown)
302
+ cells = [
303
+ str(counts.get(s, 0) or "")
304
+ for s in (Severity.CRITICAL, Severity.HIGH, Severity.MEDIUM, Severity.LOW)
305
+ ]
306
+ table.add_row(
307
+ row.label,
308
+ row.result.project.manager,
309
+ str(len(shown)),
310
+ *cells,
311
+ "" if shown else "[green]clean[/green]",
312
+ )
313
+ console.print(table)
314
+ with_findings = sum(1 for r in rows if r.result and r.result.shown)
315
+ errors = sum(1 for r in rows if r.error)
316
+ console.print(
317
+ f"{with_findings} with findings · {len(rows) - with_findings - errors} clean"
318
+ + (f" · {errors} failed" if errors else "")
319
+ )
320
+ console.print("[dim]Details for one project: patchloop scan <folder>[/dim]")
321
+
322
+
323
+ def _fix_result(outcome: FixOutcome) -> str:
324
+ if outcome.dry_run or outcome.report is None:
325
+ return f"dry run: {len(outcome.resolvable)} upgrade(s) planned"
326
+ pr = outcome.pr
327
+ if outcome.pr_action in ("created", "updated", "unchanged") and pr is not None:
328
+ word = {"created": "opened", "updated": "updated", "unchanged": "already up to date"}
329
+ return f"PR #{pr.number} {word[outcome.pr_action]}: {pr.url}"
330
+ if outcome.pr_action == "local":
331
+ return f"local branch {outcome.branch}"
332
+ return _short(outcome.pr_note) or "nothing to change"
333
+
334
+
335
+ def render_fix_summary(rows: list[FixRow], console: Console) -> None:
336
+ table = Table(title=f"{len(rows)} projects", header_style="bold", title_justify="left")
337
+ table.add_column("Project", overflow="fold")
338
+ table.add_column("Fixed", justify="right")
339
+ table.add_column("Left", justify="right")
340
+ table.add_column("Result", overflow="fold")
341
+ for row in rows:
342
+ if row.outcome is None:
343
+ table.add_row(row.label, "", "", f"[red]{_short(row.error)}[/red]")
344
+ continue
345
+ report = row.outcome.report
346
+ results = report.results if report else []
347
+ fixed = sum(1 for r in results if r.status.counts_as_fixed)
348
+ left = sum(
349
+ 1 for r in results if not r.status.counts_as_fixed and r.status is not FixStatus.SKIPPED
350
+ )
351
+ table.add_row(
352
+ row.label,
353
+ str(fixed) if report else "",
354
+ str(left) if report else "",
355
+ _fix_result(row.outcome),
356
+ )
357
+ console.print(table)
@@ -4,12 +4,17 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  from pathlib import Path
7
+ from typing import Any
7
8
 
8
9
  from patchloop.scanner import ScanResult
9
10
 
10
11
 
11
12
  def write_scan_json(result: ScanResult, path: Path) -> None:
12
- payload = {
13
+ path.write_text(json.dumps(scan_payload(result), indent=2) + "\n", encoding="utf-8")
14
+
15
+
16
+ def scan_payload(result: ScanResult) -> dict[str, Any]:
17
+ return {
13
18
  "run_id": result.run_id,
14
19
  "project": result.project.root.name,
15
20
  "manager": result.project.manager,
@@ -23,4 +28,3 @@ def write_scan_json(result: ScanResult, path: Path) -> None:
23
28
  "expired_ignore_rules": [r.id for r in result.expired_rules],
24
29
  "warnings": result.warnings,
25
30
  }
26
- path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
patchloop/report/sarif.py CHANGED
@@ -129,6 +129,11 @@ def build_sarif(
129
129
  }
130
130
 
131
131
 
132
+ def merge(payloads: list[dict[str, Any]]) -> dict[str, Any]:
133
+ """One SARIF file holding the runs of several projects."""
134
+ return {"$schema": SCHEMA, "version": "2.1.0", "runs": [r for p in payloads for r in p["runs"]]}
135
+
136
+
132
137
  def remaining(findings: list[Finding], results: list[FixResult]) -> list[Finding]:
133
138
  """After a fix run: the findings still open (not fixed, not skipped)."""
134
139
  open_keys = {
patchloop/targets.py ADDED
@@ -0,0 +1,82 @@
1
+ """Which project folders a command runs on: the folders given, ``--all`` projects below
2
+ them, minus ``--skip``.
3
+
4
+ ``scan`` on a folder that is not itself a project covers every project inside it (scanning
5
+ changes nothing). ``fix`` does that only with ``--all``, because it can open many PRs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from patchloop.workspaces import find_projects, is_project
14
+
15
+
16
+ class TargetError(Exception):
17
+ """The folders and flags given select no project to run on."""
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Target:
22
+ path: Path
23
+ label: str
24
+ """How the project is shown: its path relative to the current folder."""
25
+
26
+
27
+ def label_for(path: Path, cwd: Path | None = None) -> str:
28
+ cwd = (cwd or Path.cwd()).resolve()
29
+ path = path.resolve()
30
+ if path == cwd:
31
+ return path.name or str(path)
32
+ try:
33
+ return path.relative_to(cwd).as_posix()
34
+ except ValueError:
35
+ return str(path)
36
+
37
+
38
+ def _skipped(label: str, skip: list[str]) -> bool:
39
+ """``--skip a/b`` leaves out that folder and everything below it; ``--skip name`` (no
40
+ slash) also matches a project folder of that name anywhere."""
41
+ for s in skip:
42
+ s = s.strip().strip("/").removeprefix("./")
43
+ if not s:
44
+ continue
45
+ if label == s or label.startswith(f"{s}/"):
46
+ return True
47
+ if "/" not in s and label.rsplit("/", 1)[-1] == s:
48
+ return True
49
+ return False
50
+
51
+
52
+ def select(
53
+ paths: list[Path],
54
+ *,
55
+ all_projects: bool,
56
+ expand: bool,
57
+ skip: list[str] | None = None,
58
+ cwd: Path | None = None,
59
+ ) -> list[Target]:
60
+ """The projects to run on, in order, without duplicates.
61
+
62
+ ``expand``: a folder that is not a project stands for the projects inside it (``scan``).
63
+ Otherwise it is kept as is, and detection explains what is there (``fix`` without --all).
64
+ """
65
+ found: list[Path] = []
66
+ for p in paths or [Path()]:
67
+ p = p.resolve()
68
+ inside = [p / rel for rel in find_projects(p)] if (all_projects or expand) else []
69
+ if all_projects:
70
+ found += ([p] if is_project(p) else []) + inside
71
+ if not is_project(p) and not inside:
72
+ found.append(p) # nothing here: let detection say why
73
+ elif is_project(p) or not inside:
74
+ found.append(p)
75
+ else:
76
+ found += inside
77
+ unique = list(dict.fromkeys(found))
78
+ targets = [Target(p, label_for(p, cwd)) for p in unique]
79
+ kept = [t for t in targets if not _skipped(t.label, skip or [])]
80
+ if targets and not kept:
81
+ raise TargetError("--skip left no project to run on")
82
+ return kept
patchloop/workspaces.py CHANGED
@@ -88,8 +88,10 @@ def is_project(d: Path) -> bool:
88
88
  return (d / "package.json").is_file() and any((d / f).is_file() for f in JS_LOCKFILES)
89
89
 
90
90
 
91
- def find_projects(root: Path, max_depth: int = 3) -> list[str]:
92
- """Folders under ``root`` (relative) that hold a project with its lockfile."""
91
+ def find_projects(root: Path, max_depth: int = 4) -> list[str]:
92
+ """Folders under ``root`` (relative, not ``root`` itself) that hold a project with its
93
+ lockfile. Projects inside projects count too (a repo with one at its root and more in
94
+ client/ and server/); workspace members have no lockfile of their own, so they don't."""
93
95
  out: list[str] = []
94
96
 
95
97
  def walk(d: Path, depth: int) -> None:
@@ -100,11 +102,10 @@ def find_projects(root: Path, max_depth: int = 3) -> list[str]:
100
102
  except OSError:
101
103
  return
102
104
  for c in children:
103
- if c.name in SKIP_DIRS or c.name.startswith("."):
105
+ if c.name in SKIP_DIRS or c.name.startswith(".") or c.is_symlink():
104
106
  continue
105
107
  if is_project(c):
106
108
  out.append(c.relative_to(root).as_posix())
107
- continue # a workspace's members are part of it
108
109
  walk(c, depth + 1)
109
110
 
110
111
  walk(root, 1)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: patchloop
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Fix vulnerable dependencies in Python and JavaScript projects: upgrade, test, rescan, one PR.
5
5
  Keywords: security,vulnerabilities,cve,dependencies,uv,poetry,npm,pnpm,yarn
6
6
  Author: Ayush Kumar Singh
@@ -26,12 +26,17 @@ Requires-Dist: rich>=13.7
26
26
  Requires-Dist: tomlkit>=0.13
27
27
  Requires-Dist: typer>=0.12
28
28
  Requires-Python: >=3.12
29
+ Project-URL: Documentation, https://ayushsingh012.github.io/PatchLoop/
29
30
  Project-URL: Repository, https://github.com/AyushSingh012/PatchLoop
30
31
  Project-URL: Issues, https://github.com/AyushSingh012/PatchLoop/issues
31
32
  Description-Content-Type: text/markdown
32
33
 
33
34
  # PatchLoop
34
35
 
36
+ 📖 **[Documentation](https://ayushsingh012.github.io/PatchLoop/)** ·
37
+ **[Which command do I run?](https://ayushsingh012.github.io/PatchLoop/commands/)** ·
38
+ [PyPI](https://pypi.org/project/patchloop/)
39
+
35
40
  Finds vulnerable dependencies in a Python project (uv or Poetry) or a JavaScript project
36
41
  (npm, pnpm or yarn: Next.js, React, Node), upgrades them to the
37
42
  lowest safe version, runs your tests, rescans to confirm each fix, and opens **one** GitHub
@@ -49,6 +54,10 @@ pipx install patchloop # or: uv tool install patchloop
49
54
  patchloop --version
50
55
  ```
51
56
 
57
+ Upgrade with the same tool you installed with: `pipx upgrade patchloop`,
58
+ `uv tool upgrade patchloop`, or `pip install --upgrade patchloop` (there is no
59
+ `pip upgrade`).
60
+
52
61
  To get the latest unreleased code instead:
53
62
  `uv tool install "git+https://github.com/AyushSingh012/PatchLoop"`.
54
63
 
@@ -294,17 +303,24 @@ and refreshed only when it changes.
294
303
  widened in each member that has it; the PR names the file (`packages/web/package.json`).
295
304
  - Tests: the root's `test` script when there is one; otherwise each member's own `test`
296
305
  script, run in that member's folder. uv runs `uv sync --frozen --all-packages` and
297
- `uv run --all-packages pytest -q`. Set `validation.test` to use your own command.
306
+ `uv run --all-packages pytest -q`. Set `validate.test` to use your own command.
298
307
  - npm does not apply new `overrides` to packages under workspace members once they are
299
308
  locked, so a vulnerable package capped by its parent in an npm workspace is reported as
300
309
  blocked instead of forced. pnpm and yarn force it as usual.
301
310
  - Running it on a member folder says which workspace root to use instead.
302
311
 
303
- **Repos with separate projects** (say `backend/` with uv.lock and `web/` with
304
- package-lock.json) are fixed one folder at a time: `patchloop fix backend`, then
305
- `patchloop fix web`. Each folder gets its own branch (`patchloop/security-fixes-backend`)
306
- and its own PR, titled with the folder. Run at the repo root, PatchLoop lists the folders it
307
- found.
312
+ **Several projects at once** (a folder of repos, or a repo with `backend/` and `web/`):
313
+
314
+ ```sh
315
+ patchloop scan # in a folder that isn't a project: scans every one
316
+ patchloop scan backend web # just these folders
317
+ patchloop fix --all --no-push # fix every project, local branches only
318
+ patchloop fix --all --skip legacy # all but some; one branch and PR per project
319
+ ```
320
+
321
+ A summary table lists each project's findings (or fixes and PR link). If one project
322
+ fails, the rest still run; the exit code is 2 if any failed, else 1 if findings remain.
323
+ Details: [Many projects at once](https://ayushsingh012.github.io/PatchLoop/guides/many-projects/).
308
324
 
309
325
  ## Poetry projects
310
326
 
@@ -2,9 +2,9 @@ patchloop/__init__.py,sha256=skVZghYJ0bFTzRwyCjjy1CLzQmFc5OPbSZtc4dACiJQ,806
2
2
  patchloop/api.py,sha256=6uN9gTJccm8Q3MfKWmhHmDqH16qcVfQ4ZOK_NVfC79Q,3704
3
3
  patchloop/build.py,sha256=1BGabcRIEN_wCvxNWGrbjxJItyqFCIK1r6Mtkx3sTrs,4288
4
4
  patchloop/classify.py,sha256=s2Py6nPjp1NIeE6CZVEHCav5TT44TmNZS5BWuPW3mcI,5452
5
- patchloop/cli.py,sha256=zKQlj1HLmZx14l1SWp0oTDZCH9PA8haU9JiyADbNKlU,15022
5
+ patchloop/cli.py,sha256=MUcyYTY9clA8F_4td7-wRiOs4Ub80m9qwnleewbRrpw,23816
6
6
  patchloop/config.py,sha256=BbmqcuqeaeTd6TmOpwry-L9JBfj7XLvifLpSYOQ9OMI,5762
7
- patchloop/detect.py,sha256=rmzG_8Yo9xNPU9DEQK9UXHusTfKqNkadVXNwu5EhIuw,4531
7
+ patchloop/detect.py,sha256=YAeyY4tCfuIE0t6FjSwm5WS7oHXAliTICXkmtCOIApE,4539
8
8
  patchloop/doctor.py,sha256=ZfB5GlNlakj_9Qxnri2_PAW_1aEQsterJ881QGziYUE,7028
9
9
  patchloop/enrich/__init__.py,sha256=0JmQD5MkqdEIToIflYSDAv4FFH-GSoToEQ5h7BCV1Sg,2015
10
10
  patchloop/enrich/epss.py,sha256=-recWudnVgP8yXAW9dtN071ShF-5_TFjhRcXok9rfUg,2176
@@ -16,7 +16,7 @@ patchloop/fixers/poetry_fix.py,sha256=biNzKQNq8JW6UKPI7-QTwGONXn01v9vumldpQ1G4de
16
16
  patchloop/fixers/uv_fix.py,sha256=sAMqcH1wyqH52QtEF23M7YYx-FJubJNT1T8ihGs-zcU,4766
17
17
  patchloop/git_ops.py,sha256=WUaROKeEz_f1HvFv_TtIT_YB7utN9N04i_uTqPn9gaU,6833
18
18
  patchloop/github.py,sha256=wxi6qTSem6EuoCbCQ9xGYXPuBj-leeDxXXs6mO7sE6c,6555
19
- patchloop/hints.py,sha256=WYsYoiUPzIAJVPECW8QFn_J1GEQG33BJVNuDoZr9cGs,6418
19
+ patchloop/hints.py,sha256=4SPDBZTwgPx510M-QeUnW_zCRxRcsMn42lEqebyF7CE,6517
20
20
  patchloop/images.py,sha256=BreHOE1-11W91zchle6hxoATDsR0f20lf_GJ4B5Nlpk,7828
21
21
  patchloop/isolate.py,sha256=DNSWHeW7D9zXVXUWpNxLElN4faSS9CPKLABuQykdMaQ,2029
22
22
  patchloop/js/__init__.py,sha256=NJgYCatQ2VJnOe8u73go_5PxiT7NOEctpe0Ibb9iMlE,47
@@ -34,9 +34,9 @@ patchloop/proc.py,sha256=2rj9wYpNAGMKBpoY9e2c7EZqVRTEnYrvUmlE1v6i6h8,2047
34
34
  patchloop/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
35
35
  patchloop/pypi.py,sha256=CfygOhlnuEpE9UHw7nExSFZficqKsIGTBohzsJyDD4M,1956
36
36
  patchloop/report/__init__.py,sha256=S0JeaIt3vqGbyNcdA2xAlsRcQFeW1le-Ogmb74lhAJ0,75
37
- patchloop/report/console.py,sha256=6RHteZw_HB6rp_O9yg9K2T9aXcR0ZC2_2krGDWyU-Lc,9389
38
- patchloop/report/json_out.py,sha256=6z3tRnvFDKNt0TwYS5rpH3Ruf7NO8ctMIPxldJhAwkw,953
39
- patchloop/report/sarif.py,sha256=SyJTH_dugDKqjn8lRES-_hcLD4Q_SYDbBSNCJiMEZu8,5157
37
+ patchloop/report/console.py,sha256=JzO19cCL-REBXvCl050yf33yt7jfPcXGj1P3O1NdfSs,13526
38
+ patchloop/report/json_out.py,sha256=JlaXeiXEVhz0HQk6m-ERyZ32JdXdKLMsrKlxt6lM2UY,1044
39
+ patchloop/report/sarif.py,sha256=O0x0uojDind1CCmqMss0fd_8B8pXqkhAWh1qT2w1CHA,5384
40
40
  patchloop/runner.py,sha256=nS671LB_40eZh4ZG8U9ShVjdmCQwNVSQCVoiT1p7D7E,18509
41
41
  patchloop/scanner.py,sha256=lZiF59YV_Jl9Uo8DIkDNC-P-HDvtx4bgZTSJ-wrPS1U,7688
42
42
  patchloop/schedule.py,sha256=kNR83roWsXdU52k3XSwmmMwUhy-xubi58-iF-sRaLF4,4571
@@ -46,12 +46,13 @@ patchloop/sources/imports.py,sha256=Y9NKyBz5dNRSJF8yenHkAw2x1M3ub1tjlqgFFFeGaGI,
46
46
  patchloop/sources/merge.py,sha256=Qt0--PnKxNebk1XE7uRLvacD3BAQUesKllWjfmPPdZ4,4018
47
47
  patchloop/sources/osv.py,sha256=NIqWECxJ_J4E5mMvJ_Rql_pNJiYgz8suhPzWIu-NjKE,10004
48
48
  patchloop/specifiers.py,sha256=1endLujc63Ban4i-BE96fQN8fa5rU1Z7FKoM3HTjt6k,10269
49
+ patchloop/targets.py,sha256=BKsgVxQeIqGc6Zb2-FZ_Cpg5PGq9ala_kWZk5orKx3s,2678
49
50
  patchloop/validate.py,sha256=jHgjKRgwNXFWSGeKHwUmtnm9q3AAcoLp69ryIAao7zI,7853
50
51
  patchloop/versions.py,sha256=w1RLRVX3qPWMe6KeBDWmikEZTRfDPKH23NcVxu_uZ2k,2567
51
- patchloop/workspaces.py,sha256=DDVR_Yxpx-DQqwkRjJKvFBADYo9AjGVdQNZ-zFVeyLg,5502
52
+ patchloop/workspaces.py,sha256=CwVgq79eLWXnQ4Q3uZsYiHIawTXYmobjT7eVrWyRKRI,5646
52
53
  patchloop/worktree.py,sha256=Nhrg6mXJJdAkCpItykbGHZ62l0x_1svVlWB15EzbGMY,5653
53
- patchloop-0.3.0.dist-info/licenses/LICENSE,sha256=b9nK3LhprXJT-KtmuZJIuDeFdNy7Hq0FR-R_f2oAer4,1074
54
- patchloop-0.3.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
55
- patchloop-0.3.0.dist-info/entry_points.txt,sha256=6Rzny6Msr-FRkBmtG1Wwi3vN2BCnhyovObirG5MAFhI,49
56
- patchloop-0.3.0.dist-info/METADATA,sha256=6KlaJgtUGX4hTZpUgHLBembUjKTDqUS2E8JAV0kpBEY,20660
57
- patchloop-0.3.0.dist-info/RECORD,,
54
+ patchloop-0.4.0.dist-info/licenses/LICENSE,sha256=b9nK3LhprXJT-KtmuZJIuDeFdNy7Hq0FR-R_f2oAer4,1074
55
+ patchloop-0.4.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
56
+ patchloop-0.4.0.dist-info/entry_points.txt,sha256=6Rzny6Msr-FRkBmtG1Wwi3vN2BCnhyovObirG5MAFhI,49
57
+ patchloop-0.4.0.dist-info/METADATA,sha256=SxHAiyRHhqGvVNIdzAKgQK5tg85ews1CpzX9IqNG1po,21444
58
+ patchloop-0.4.0.dist-info/RECORD,,