patchloop 0.2.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.
Files changed (56) hide show
  1. patchloop/__init__.py +23 -0
  2. patchloop/api.py +110 -0
  3. patchloop/build.py +118 -0
  4. patchloop/classify.py +137 -0
  5. patchloop/cli.py +370 -0
  6. patchloop/config.py +148 -0
  7. patchloop/detect.py +133 -0
  8. patchloop/doctor.py +207 -0
  9. patchloop/enrich/__init__.py +66 -0
  10. patchloop/enrich/epss.py +65 -0
  11. patchloop/enrich/kev.py +39 -0
  12. patchloop/fixers/__init__.py +1 -0
  13. patchloop/fixers/base.py +20 -0
  14. patchloop/fixers/js_fix.py +288 -0
  15. patchloop/fixers/poetry_fix.py +144 -0
  16. patchloop/fixers/uv_fix.py +118 -0
  17. patchloop/git_ops.py +171 -0
  18. patchloop/github.py +161 -0
  19. patchloop/hints.py +180 -0
  20. patchloop/images.py +208 -0
  21. patchloop/isolate.py +57 -0
  22. patchloop/js/__init__.py +1 -0
  23. patchloop/js/lockfiles.py +237 -0
  24. patchloop/js/manifest.py +121 -0
  25. patchloop/js/ranges.py +130 -0
  26. patchloop/js/registry.py +67 -0
  27. patchloop/js/yarn.py +189 -0
  28. patchloop/lockgraph.py +181 -0
  29. patchloop/models.py +248 -0
  30. patchloop/plan.py +194 -0
  31. patchloop/pr_body.py +253 -0
  32. patchloop/prioritize.py +38 -0
  33. patchloop/proc.py +71 -0
  34. patchloop/py.typed +0 -0
  35. patchloop/pypi.py +60 -0
  36. patchloop/report/__init__.py +1 -0
  37. patchloop/report/console.py +243 -0
  38. patchloop/report/json_out.py +26 -0
  39. patchloop/report/sarif.py +143 -0
  40. patchloop/runner.py +494 -0
  41. patchloop/scanner.py +214 -0
  42. patchloop/sources/__init__.py +1 -0
  43. patchloop/sources/base.py +5 -0
  44. patchloop/sources/imports.py +292 -0
  45. patchloop/sources/merge.py +113 -0
  46. patchloop/sources/osv.py +255 -0
  47. patchloop/specifiers.py +259 -0
  48. patchloop/validate.py +198 -0
  49. patchloop/versions.py +81 -0
  50. patchloop/workspaces.py +142 -0
  51. patchloop/worktree.py +153 -0
  52. patchloop-0.2.0.dist-info/METADATA +388 -0
  53. patchloop-0.2.0.dist-info/RECORD +56 -0
  54. patchloop-0.2.0.dist-info/WHEEL +4 -0
  55. patchloop-0.2.0.dist-info/entry_points.txt +3 -0
  56. patchloop-0.2.0.dist-info/licenses/LICENSE +21 -0
patchloop/cli.py ADDED
@@ -0,0 +1,370 @@
1
+ """Command-line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import signal
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Annotated, NoReturn
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.table import Table
13
+
14
+ from patchloop import __version__, doctor, proc
15
+ from patchloop.build import BuildError, resolve_build_args
16
+ from patchloop.config import BuildConfig, Config, ConfigError, load_config
17
+ from patchloop.detect import DetectError
18
+ from patchloop.fixers.base import LockError
19
+ from patchloop.git_ops import GitError
20
+ from patchloop.github import GitHubError
21
+ from patchloop.hints import hint_for
22
+ from patchloop.images import ImageScanError, parse_scanners
23
+ 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
26
+ from patchloop.report.sarif import build_sarif, remaining, write_sarif
27
+ from patchloop.runner import FixError, run_fix
28
+ from patchloop.scanner import resolve_imports, run_scan
29
+ from patchloop.sources.base import SourceError
30
+ from patchloop.worktree import WorktreeError
31
+
32
+ app = typer.Typer(
33
+ name="patchloop",
34
+ help="Scan a Python project for vulnerable dependencies, fix them, test, rescan, open one PR.",
35
+ no_args_is_help=True,
36
+ add_completion=False,
37
+ )
38
+ console = Console()
39
+ err_console = Console(stderr=True)
40
+
41
+ PathArg = Annotated[
42
+ Path,
43
+ typer.Argument(exists=True, file_okay=False, resolve_path=True, help="Project directory."),
44
+ ]
45
+ ImportOpt = Annotated[
46
+ list[Path] | None,
47
+ typer.Option(
48
+ "--import",
49
+ exists=True,
50
+ dir_okay=False,
51
+ help="Trivy or Wiz JSON file to merge in. Repeatable.",
52
+ ),
53
+ ]
54
+ SeverityOpt = Annotated[
55
+ str | None,
56
+ typer.Option("--severity", help="Only these severities, e.g. MEDIUM,HIGH,CRITICAL."),
57
+ ]
58
+ ConfigOpt = Annotated[
59
+ Path | None,
60
+ typer.Option(
61
+ "--config",
62
+ dir_okay=False,
63
+ resolve_path=True,
64
+ help="Config file to use instead of <PATH>/patchloop.yml.",
65
+ ),
66
+ ]
67
+ ImageOpt = Annotated[
68
+ list[str] | None,
69
+ typer.Option("--image", help="Container image to scan (repeatable), e.g. myapp:latest."),
70
+ ]
71
+ ScannerOpt = Annotated[
72
+ str | None,
73
+ typer.Option("--scanner", help="Image scanner: trivy (default), wiz, or trivy,wiz."),
74
+ ]
75
+ PlatformOpt = Annotated[
76
+ str | None,
77
+ typer.Option("--platform", help="Image platform for multi-platform images, e.g. linux/amd64."),
78
+ ]
79
+ BuildOpt = Annotated[
80
+ bool,
81
+ typer.Option("--build", help="Build the image from the Dockerfile and scan it."),
82
+ ]
83
+ DockerfileOpt = Annotated[
84
+ Path | None,
85
+ typer.Option(
86
+ "--dockerfile", help="Dockerfile path, relative to the project (implies --build)."
87
+ ),
88
+ ]
89
+ BuildArgOpt = Annotated[
90
+ list[str] | None,
91
+ typer.Option(
92
+ "--build-arg",
93
+ help="NAME=VALUE or NAME (value from the environment). Never logged. Repeatable.",
94
+ ),
95
+ ]
96
+ MinSeverityOpt = Annotated[
97
+ str | None,
98
+ typer.Option(
99
+ "--min-severity",
100
+ help="Lowest severity to include (LOW, MEDIUM, HIGH, CRITICAL). "
101
+ "Overrides severity_threshold in patchloop.yml; the default is HIGH.",
102
+ ),
103
+ ]
104
+
105
+
106
+ def _version_callback(value: bool) -> None:
107
+ if value:
108
+ console.print(f"patchloop {__version__}")
109
+ raise typer.Exit()
110
+
111
+
112
+ @app.callback()
113
+ def main(
114
+ version: Annotated[
115
+ bool,
116
+ typer.Option("--version", callback=_version_callback, is_eager=True, help="Show version."),
117
+ ] = False,
118
+ ) -> None:
119
+ """PatchLoop v1."""
120
+ # A kill (SIGTERM) unwinds like Ctrl+C, so the temporary worktree is removed and a
121
+ # running install or test command is stopped with it.
122
+ signal.signal(signal.SIGTERM, _exit_on_sigterm)
123
+
124
+
125
+ def _exit_on_sigterm(signum: int, frame: object) -> NoReturn:
126
+ raise SystemExit(128 + signum)
127
+
128
+
129
+ @app.command("doctor")
130
+ def doctor_cmd(path: PathArg = Path(), config: ConfigOpt = None) -> None:
131
+ """Check the tools PatchLoop uses, and show how to install any that are missing."""
132
+ cfg = _load_config_or_exit(path, config)
133
+ if sys.platform == "win32":
134
+ err_console.print(
135
+ "[yellow]Windows is not supported; run PatchLoop inside WSL "
136
+ "(https://learn.microsoft.com/windows/wsl/install).[/yellow]"
137
+ )
138
+ results = doctor.run_checks(gh_user=cfg.pr.gh_user)
139
+ table = Table(title="patchloop doctor", show_lines=False)
140
+ table.add_column("Tool")
141
+ table.add_column("Status")
142
+ table.add_column("Version")
143
+ table.add_column("Detail")
144
+ for r in results:
145
+ if r.ok:
146
+ status = "[green]ok[/green]"
147
+ elif r.required:
148
+ status = "[red]missing[/red]"
149
+ else:
150
+ status = "[yellow]optional[/yellow]"
151
+ table.add_row(r.name, status, r.version or "-", r.detail)
152
+ console.print(table)
153
+ if not doctor.all_required_ok(results):
154
+ err_console.print("[red]Some required tools are missing or not ready.[/red]")
155
+ raise typer.Exit(ExitCode.ERROR)
156
+
157
+
158
+ def _fail(message: str | Exception) -> NoReturn:
159
+ err_console.print(f"[red]Error:[/red] {message}", highlight=False)
160
+ hint = hint_for(message) if isinstance(message, Exception) else None
161
+ if hint:
162
+ err_console.print(f"[yellow]Fix:[/yellow] {hint}", highlight=False)
163
+ raise typer.Exit(ExitCode.ERROR)
164
+
165
+
166
+ def _load_config_or_exit(path: Path, file: Path | None = None) -> Config:
167
+ try:
168
+ return load_config(path, file)
169
+ except ConfigError as exc:
170
+ _fail(exc)
171
+
172
+
173
+ def lockfile_uri(lockfile: Path) -> str:
174
+ """The lockfile's path from the repo root (what SARIF viewers expect), else its name."""
175
+ try:
176
+ top = proc.run(["git", "rev-parse", "--show-toplevel"], cwd=lockfile.parent, timeout=30)
177
+ except (proc.ToolNotFoundError, proc.ToolTimeoutError):
178
+ return lockfile.name
179
+ if not top.ok:
180
+ return lockfile.name
181
+ try:
182
+ return lockfile.resolve().relative_to(Path(top.stdout.strip()).resolve()).as_posix()
183
+ except ValueError:
184
+ return lockfile.name
185
+
186
+
187
+ _THRESHOLDS = ("LOW", "MEDIUM", "HIGH", "CRITICAL")
188
+
189
+
190
+ def with_build(cfg: Config, build: bool, dockerfile: Path | None) -> Config:
191
+ if not build and dockerfile is None:
192
+ return cfg
193
+ spec = cfg.build or BuildConfig()
194
+ if dockerfile is not None:
195
+ spec = spec.model_copy(update={"dockerfile": dockerfile})
196
+ return cfg.model_copy(update={"build": spec})
197
+
198
+
199
+ def _build_args(cfg: Config, cli: list[str] | None) -> dict[str, str]:
200
+ if cfg.build is None:
201
+ if cli:
202
+ _fail("--build-arg needs --build")
203
+ return {}
204
+ try:
205
+ return resolve_build_args(cfg.build.args, cli or [])
206
+ except BuildError as exc:
207
+ _fail(exc)
208
+
209
+
210
+ def with_images(
211
+ cfg: Config, images: list[str] | None, scanner: str | None, platform: str | None
212
+ ) -> Config:
213
+ update: dict[str, object] = {}
214
+ if images:
215
+ update["images"] = list(dict.fromkeys([*cfg.images, *images]))
216
+ if scanner is not None:
217
+ try:
218
+ update["image_scanners"] = parse_scanners(scanner)
219
+ except ValueError as exc:
220
+ _fail(str(exc))
221
+ if platform is not None:
222
+ update["image_platform"] = platform
223
+ return cfg.model_copy(update=update) if update else cfg
224
+
225
+
226
+ def with_min_severity(cfg: Config, value: str | None) -> Config:
227
+ if value is None:
228
+ return cfg
229
+ name = value.strip().upper()
230
+ if name not in _THRESHOLDS:
231
+ _fail(f"unknown --min-severity '{value}'; use: {', '.join(_THRESHOLDS)}")
232
+ return cfg.model_copy(update={"severity_threshold": name})
233
+
234
+
235
+ def parse_severity_option(value: str | None) -> set[Severity] | None:
236
+ if value is None:
237
+ return None
238
+ wanted: set[Severity] = set()
239
+ for part in value.split(","):
240
+ name = part.strip().upper()
241
+ if not name:
242
+ continue
243
+ try:
244
+ wanted.add(Severity(name))
245
+ except ValueError:
246
+ choices = ", ".join(s.value for s in Severity)
247
+ _fail(f"unknown severity '{part.strip()}'; use: {choices}")
248
+ return wanted or None
249
+
250
+
251
+ @app.command("scan")
252
+ def scan_cmd(
253
+ path: PathArg = Path(),
254
+ imports: ImportOpt = None,
255
+ image: ImageOpt = None,
256
+ scanner: ScannerOpt = None,
257
+ platform: PlatformOpt = None,
258
+ build: BuildOpt = False,
259
+ dockerfile: DockerfileOpt = None,
260
+ build_arg: BuildArgOpt = None,
261
+ severity: SeverityOpt = None,
262
+ min_severity: MinSeverityOpt = None,
263
+ config: ConfigOpt = None,
264
+ json_out: Annotated[Path | None, typer.Option("--json", help="Write a JSON report.")] = None,
265
+ sarif_out: Annotated[Path | None, typer.Option("--sarif", help="Write a SARIF report.")] = None,
266
+ ) -> None:
267
+ """Collect, merge and prioritize findings. Changes nothing."""
268
+ cfg = with_images(
269
+ with_min_severity(_load_config_or_exit(path, config), min_severity),
270
+ image,
271
+ scanner,
272
+ platform,
273
+ )
274
+ cfg = with_build(cfg, build, dockerfile)
275
+ build_args = _build_args(cfg, build_arg)
276
+ only = parse_severity_option(severity)
277
+ try:
278
+ result = run_scan(
279
+ path, cfg, only, imports=resolve_imports(path, cfg, imports), build_args=build_args
280
+ )
281
+ except (DetectError, SourceError, ImageScanError, BuildError) as exc:
282
+ _fail(exc)
283
+ render_scan(result, console)
284
+ if json_out is not None:
285
+ write_scan_json(result, json_out)
286
+ console.print(f"JSON report: {json_out}")
287
+ if sarif_out is not None:
288
+ lock = result.project.lockfile
289
+ write_sarif(build_sarif(result.shown, lock, lockfile_uri(lock)), sarif_out)
290
+ console.print(f"SARIF report: {sarif_out}")
291
+ if result.shown:
292
+ raise typer.Exit(ExitCode.FINDINGS_REMAIN)
293
+
294
+
295
+ @app.command("fix")
296
+ def fix_cmd(
297
+ path: PathArg = Path(),
298
+ imports: ImportOpt = None,
299
+ image: ImageOpt = None,
300
+ scanner: ScannerOpt = None,
301
+ platform: PlatformOpt = None,
302
+ build: BuildOpt = False,
303
+ dockerfile: DockerfileOpt = None,
304
+ build_arg: BuildArgOpt = None,
305
+ severity: SeverityOpt = None,
306
+ min_severity: MinSeverityOpt = None,
307
+ config: ConfigOpt = None,
308
+ dry_run: Annotated[
309
+ bool, typer.Option("--dry-run", help="Show planned upgrades; change nothing.")
310
+ ] = False,
311
+ no_push: Annotated[
312
+ bool,
313
+ typer.Option("--no-push", help="Commit locally and write the PR body to a file only."),
314
+ ] = False,
315
+ keep_worktree: Annotated[
316
+ bool, typer.Option("--keep-worktree", help="Keep the temporary worktree for inspection.")
317
+ ] = False,
318
+ json_out: Annotated[
319
+ Path | None, typer.Option("--json", help="Write the run report as JSON.")
320
+ ] = None,
321
+ sarif_out: Annotated[
322
+ Path | None, typer.Option("--sarif", help="Write the findings still open as SARIF.")
323
+ ] = None,
324
+ ) -> None:
325
+ """Full loop in a temporary worktree, then open or update the one PR."""
326
+ cfg = with_images(
327
+ with_min_severity(_load_config_or_exit(path, config), min_severity),
328
+ image,
329
+ scanner,
330
+ platform,
331
+ )
332
+ cfg = with_build(cfg, build, dockerfile)
333
+ build_args = _build_args(cfg, build_arg)
334
+ only = parse_severity_option(severity)
335
+ try:
336
+ outcome = run_fix(
337
+ path,
338
+ cfg,
339
+ only,
340
+ dry_run=dry_run,
341
+ push_pr=not no_push,
342
+ keep_worktree=keep_worktree,
343
+ imports=resolve_imports(path, cfg, imports),
344
+ build_args=build_args,
345
+ )
346
+ except (
347
+ DetectError,
348
+ SourceError,
349
+ ImageScanError,
350
+ BuildError,
351
+ WorktreeError,
352
+ FixError,
353
+ LockError,
354
+ GitError,
355
+ GitHubError,
356
+ ) as exc:
357
+ _fail(exc)
358
+ render_fix(outcome, console)
359
+ report = outcome.report
360
+ if report is not None and json_out is not None:
361
+ json_out.write_text(report.model_dump_json(indent=2) + "\n", encoding="utf-8")
362
+ console.print(f"JSON report: {json_out}")
363
+ if report is not None and sarif_out is not None and outcome.scan is not None:
364
+ every = {f.key: f for f in [*report.findings_after, *report.findings_before]}
365
+ still_open = remaining(list(every.values()), report.results)
366
+ lock = path / outcome.scan.project.lockfile.name
367
+ statuses = {r.finding_key: r for r in report.results}
368
+ write_sarif(build_sarif(still_open, lock, lockfile_uri(lock), statuses), sarif_out)
369
+ console.print(f"SARIF report: {sarif_out}")
370
+ raise typer.Exit(outcome.exit_code)
patchloop/config.py ADDED
@@ -0,0 +1,148 @@
1
+ """Load ``patchloop.yml``. Every key is optional; unknown keys are an error.
2
+
3
+ Test and install commands come only from this local file, never from a remote source.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from datetime import date
9
+ from pathlib import Path
10
+ from typing import Literal
11
+
12
+ import yaml
13
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
14
+
15
+ from patchloop.models import Manager, Severity
16
+
17
+ CONFIG_FILENAME = "patchloop.yml"
18
+ NO_TESTS = "none"
19
+
20
+ _DEFAULT_INSTALL: dict[Manager, str] = {"uv": "uv sync --frozen", "poetry": "poetry sync"}
21
+ _DEFAULT_TEST: dict[Manager, str] = {"uv": "uv run pytest -q", "poetry": "poetry run pytest -q"}
22
+
23
+
24
+ ImageScanner = Literal["trivy", "wiz"]
25
+
26
+
27
+ def _default_scanners() -> list[ImageScanner]:
28
+ return ["trivy"]
29
+
30
+
31
+ class ConfigError(Exception):
32
+ """patchloop.yml is missing required structure or has unknown keys."""
33
+
34
+
35
+ class _Strict(BaseModel):
36
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
37
+
38
+
39
+ class ValidateConfig(_Strict):
40
+ install: str | None = None
41
+ """None = the manager's default (``uv sync --frozen`` / ``poetry sync``)."""
42
+ test: str | None = None
43
+ """None = the manager's default; ``"none"`` = do not run tests (FIXED_NOT_TESTED)."""
44
+ timeout_minutes: int = Field(default=15, gt=0)
45
+ retries: int = Field(default=1, ge=0, le=3)
46
+ isolate_breakers: bool = True
47
+
48
+ def install_command(self, manager: Manager) -> str:
49
+ return self.install or _DEFAULT_INSTALL[manager]
50
+
51
+ def test_command(self, manager: Manager) -> str | None:
52
+ """The test command, or None when tests are turned off."""
53
+ cmd = self.test or _DEFAULT_TEST[manager]
54
+ return None if cmd.strip().lower() == NO_TESTS else cmd
55
+
56
+ @property
57
+ def tests_enabled(self) -> bool:
58
+ """False when ``test: none``. (A JS project without a test script also runs no tests;
59
+ the Validator decides that.)"""
60
+ return (self.test or "").strip().lower() != NO_TESTS
61
+
62
+
63
+ class BuildConfig(_Strict):
64
+ """Build the image from this Dockerfile (paths relative to the project folder)."""
65
+
66
+ dockerfile: Path = Path("Dockerfile")
67
+ context: Path = Path()
68
+ args: list[str] = Field(default_factory=list)
69
+ """Build-arg NAMES only; their values are read from the environment, never from here."""
70
+
71
+
72
+ class IgnoreRule(_Strict):
73
+ id: str
74
+ reason: str = Field(min_length=1)
75
+ expires: date
76
+
77
+ def is_expired(self, today: date) -> bool:
78
+ return today > self.expires
79
+
80
+
81
+ class PRConfig(_Strict):
82
+ base_branch: str = "main"
83
+ branch: str = "patchloop/security-fixes"
84
+ reviewers: list[str] = Field(default_factory=list)
85
+ labels: list[str] = Field(default_factory=lambda: ["security", "dependencies"])
86
+ gh_user: str | None = None
87
+ """gh account to open the PR with (its token is used for PatchLoop's commands only).
88
+ None = the account active in gh."""
89
+ repo: str | None = Field(default=None, pattern=r"^[\w.-]+/[\w.-]+$")
90
+ """GitHub ``owner/name``; None = read it from the ``origin`` remote."""
91
+
92
+
93
+ class Config(_Strict):
94
+ imports: list[Path] = Field(default_factory=list)
95
+ images: list[str] = Field(default_factory=list)
96
+ """Container images to scan on every run (pulled or built locally, or reachable)."""
97
+ image_scanners: list[ImageScanner] = Field(default_factory=_default_scanners)
98
+ image_platform: str | None = None
99
+ """e.g. linux/amd64, for multi-platform images; default: this machine's platform."""
100
+ build: BuildConfig | None = None
101
+ """Set to build and scan the image (`fix` also rebuilds and rescans after the fix)."""
102
+ severity_threshold: Literal["LOW", "MEDIUM", "HIGH", "CRITICAL"] = "HIGH"
103
+ """Fix findings at or above this. Unrated findings count as HIGH; KEV-listed or likely
104
+ exploited (EPSS) findings are always included."""
105
+ allow_major_upgrades: bool = False
106
+ osv_offline: bool = True
107
+ """Match the lockfile against a local copy of the OSV database (downloaded and kept
108
+ up to date in the cache) instead of sending package names and versions to osv.dev."""
109
+ enrich: bool = True
110
+ """Look up CISA KEV and FIRST EPSS for each CVE (only CVE IDs are sent)."""
111
+ # "validate" would shadow BaseModel.validate, so the attribute has another name.
112
+ validation: ValidateConfig = Field(default_factory=ValidateConfig, alias="validate")
113
+ ignore: list[IgnoreRule] = Field(default_factory=list)
114
+ pr: PRConfig = Field(default_factory=PRConfig)
115
+
116
+ @field_validator("severity_threshold", mode="before")
117
+ @classmethod
118
+ def _upper(cls, value: object) -> object:
119
+ return value.upper() if isinstance(value, str) else value
120
+
121
+ @property
122
+ def threshold(self) -> Severity:
123
+ return Severity(self.severity_threshold)
124
+
125
+
126
+ def load_config(project_root: Path, file: Path | None = None) -> Config:
127
+ """Read ``file``, else ``<project_root>/patchloop.yml`` if it exists, else the defaults."""
128
+ path = file or project_root / CONFIG_FILENAME
129
+ if file is not None and not file.is_file():
130
+ raise ConfigError(f"{file}: no such config file")
131
+ if not path.is_file():
132
+ return Config()
133
+ try:
134
+ raw = yaml.safe_load(path.read_text(encoding="utf-8"))
135
+ except yaml.YAMLError as exc:
136
+ raise ConfigError(f"{path}: not valid YAML ({exc})") from exc
137
+ if raw is None:
138
+ return Config()
139
+ if not isinstance(raw, dict):
140
+ raise ConfigError(f"{path}: expected a mapping of keys at the top level")
141
+ try:
142
+ return Config.model_validate(raw)
143
+ except ValidationError as exc:
144
+ problems = "; ".join(
145
+ f"{'.'.join(str(p) for p in err['loc']) or '<root>'}: {err['msg']}"
146
+ for err in exc.errors()
147
+ )
148
+ raise ConfigError(f"{path}: {problems}") from exc
patchloop/detect.py ADDED
@@ -0,0 +1,133 @@
1
+ """Find the project, its package manager and lockfile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import tomllib
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from patchloop import proc
11
+ from patchloop.models import Manager, Project
12
+ from patchloop.proc import ToolNotFoundError
13
+ from patchloop.workspaces import (
14
+ enclosing_workspace,
15
+ expand,
16
+ find_projects,
17
+ js_patterns,
18
+ uv_patterns,
19
+ )
20
+
21
+
22
+ class DetectError(Exception):
23
+ """The path is not a project PatchLoop can work on."""
24
+
25
+
26
+ def _read_toml(path: Path) -> dict[str, Any]:
27
+ try:
28
+ return tomllib.loads(path.read_text(encoding="utf-8"))
29
+ except tomllib.TOMLDecodeError as exc:
30
+ raise DetectError(f"{path} is not valid TOML: {exc}") from exc
31
+
32
+
33
+ def project_name(pyproject: dict[str, Any]) -> str | None:
34
+ name = pyproject.get("project", {}).get("name")
35
+ if name is None:
36
+ name = pyproject.get("tool", {}).get("poetry", {}).get("name")
37
+ return str(name) if name else None
38
+
39
+
40
+ def _commit_sha(root: Path) -> str | None:
41
+ try:
42
+ result = proc.run(["git", "rev-parse", "HEAD"], cwd=root, timeout=10)
43
+ except ToolNotFoundError:
44
+ return None
45
+ return result.stdout.strip() if result.ok else None
46
+
47
+
48
+ _JS_LOCKS = (("pnpm", "pnpm-lock.yaml"), ("yarn", "yarn.lock"), ("npm", "package-lock.json"))
49
+
50
+
51
+ def _not_a_project(root: Path, what: str) -> DetectError:
52
+ """No project here: point at the workspace above, or at the projects below."""
53
+ above = enclosing_workspace(root)
54
+ if above is not None:
55
+ return DetectError(
56
+ f"{root} is a member of the workspace at {above}; run PatchLoop on {above} "
57
+ "(the lockfile there covers every member)"
58
+ )
59
+ below = find_projects(root)
60
+ if below:
61
+ listed = ", ".join(below[:10]) + (f" and {len(below) - 10} more" if len(below) > 10 else "")
62
+ return DetectError(
63
+ f"{what} in {root}; it holds separate projects: {listed}. "
64
+ "Run PatchLoop on each folder (each gets its own PR)"
65
+ )
66
+ return DetectError(f"{what} in {root}")
67
+
68
+
69
+ def _detect_js(root: Path) -> tuple[Manager, Path, list[str]] | None:
70
+ if not (root / "package.json").is_file():
71
+ return None
72
+ try:
73
+ manifest = json.loads((root / "package.json").read_text("utf-8"))
74
+ except json.JSONDecodeError as exc:
75
+ raise DetectError(f"{root / 'package.json'} is not valid JSON: {exc}") from exc
76
+ patterns = js_patterns(root, manifest)
77
+ members = expand(root, patterns, "package.json") if patterns else []
78
+ for manager, name in _JS_LOCKS:
79
+ if (root / name).is_file():
80
+ return manager, root / name, members # type: ignore[return-value]
81
+ above = enclosing_workspace(root)
82
+ if above is not None:
83
+ raise _not_a_project(root, "")
84
+ raise DetectError(
85
+ f"no package-lock.json, pnpm-lock.yaml or yarn.lock in {root}; "
86
+ "run `npm install`, `pnpm install` or `yarn install` and commit the lockfile first"
87
+ )
88
+
89
+
90
+ def detect_project(path: Path, base_branch: str = "main") -> Project:
91
+ root = path.resolve()
92
+ pyproject_path = root / "pyproject.toml"
93
+ python_lock = (root / "uv.lock").is_file() or (root / "poetry.lock").is_file()
94
+ if not pyproject_path.is_file() or not python_lock:
95
+ js = _detect_js(root)
96
+ if js is not None:
97
+ return Project(
98
+ root=root,
99
+ manager=js[0],
100
+ lockfile=js[1],
101
+ commit_sha=_commit_sha(root),
102
+ base_branch=base_branch,
103
+ members=js[2],
104
+ )
105
+ if not pyproject_path.is_file():
106
+ raise _not_a_project(root, "no pyproject.toml or package.json")
107
+ pyproject = _read_toml(pyproject_path)
108
+
109
+ uv_lock = root / "uv.lock"
110
+ poetry_lock = root / "poetry.lock"
111
+ members: list[str] = []
112
+ if uv_lock.is_file():
113
+ manager, lockfile = "uv", uv_lock
114
+ ws = uv_patterns(pyproject)
115
+ if ws is not None:
116
+ members = expand(root, ws[0], "pyproject.toml", ws[1])
117
+ elif poetry_lock.is_file():
118
+ manager, lockfile = "poetry", poetry_lock
119
+ else:
120
+ if enclosing_workspace(root) is not None:
121
+ raise _not_a_project(root, "")
122
+ raise DetectError(
123
+ f"no uv.lock or poetry.lock in {root}; run `uv lock` or `poetry lock` first"
124
+ )
125
+
126
+ return Project(
127
+ root=root,
128
+ manager=manager,
129
+ lockfile=lockfile,
130
+ commit_sha=_commit_sha(root),
131
+ base_branch=base_branch,
132
+ members=members,
133
+ )