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/models.py ADDED
@@ -0,0 +1,248 @@
1
+ """Core data models. These are the stable part of PatchLoop: later versions build on them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from enum import IntEnum, StrEnum
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ from packaging.utils import canonicalize_name
11
+ from pydantic import BaseModel, ConfigDict, Field
12
+
13
+
14
+ class ExitCode(IntEnum):
15
+ OK = 0
16
+ """Nothing at or above the severity threshold remains."""
17
+ FINDINGS_REMAIN = 1
18
+ """Findings remain, or an upgrade introduced a new finding."""
19
+ ERROR = 2
20
+ """A tool or config error, or tests already fail before any change."""
21
+
22
+
23
+ class Severity(StrEnum):
24
+ UNKNOWN = "UNKNOWN"
25
+ LOW = "LOW"
26
+ MEDIUM = "MEDIUM"
27
+ HIGH = "HIGH"
28
+ CRITICAL = "CRITICAL"
29
+
30
+ @property
31
+ def rank(self) -> int:
32
+ return _SEVERITY_RANK[self]
33
+
34
+ @classmethod
35
+ def from_cvss(cls, score: float | None) -> Severity:
36
+ """Bucket a CVSS 0-10 score the standard way."""
37
+ if score is None:
38
+ return cls.UNKNOWN
39
+ if score >= 9.0:
40
+ return cls.CRITICAL
41
+ if score >= 7.0:
42
+ return cls.HIGH
43
+ if score >= 4.0:
44
+ return cls.MEDIUM
45
+ if score > 0.0:
46
+ return cls.LOW
47
+ return cls.UNKNOWN
48
+
49
+
50
+ _SEVERITY_RANK = {
51
+ Severity.UNKNOWN: 0,
52
+ Severity.LOW: 1,
53
+ Severity.MEDIUM: 2,
54
+ Severity.HIGH: 3,
55
+ Severity.CRITICAL: 4,
56
+ }
57
+
58
+
59
+ class FixStatus(StrEnum):
60
+ FIXED_AND_VALIDATED = "FIXED_AND_VALIDATED"
61
+ FIXED_NOT_TESTED = "FIXED_NOT_TESTED"
62
+ FIXED_BUT_TESTS_FAILED = "FIXED_BUT_TESTS_FAILED"
63
+ STILL_PRESENT = "STILL_PRESENT"
64
+ NO_SAFE_FIX = "NO_SAFE_FIX"
65
+ FIXED_IN_SOURCE = "FIXED_IN_SOURCE"
66
+ OUT_OF_SCOPE = "OUT_OF_SCOPE"
67
+ INTRODUCED = "INTRODUCED"
68
+ SKIPPED = "SKIPPED"
69
+ ERROR = "ERROR"
70
+
71
+ @property
72
+ def counts_as_fixed(self) -> bool:
73
+ return self in {FixStatus.FIXED_AND_VALIDATED, FixStatus.FIXED_NOT_TESTED}
74
+
75
+
76
+ Manager = Literal["uv", "poetry", "npm", "pnpm", "yarn"]
77
+ JS_MANAGERS: frozenset[str] = frozenset({"npm", "pnpm", "yarn"})
78
+
79
+
80
+ def ecosystem_of(manager: str) -> str:
81
+ """The OSV ecosystem a package manager's packages belong to."""
82
+ return "npm" if manager in JS_MANAGERS else "PyPI"
83
+
84
+
85
+ MANIFEST = {"uv": "pyproject.toml", "poetry": "pyproject.toml"} | {
86
+ m: "package.json" for m in ("npm", "pnpm", "yarn")
87
+ }
88
+ UpgradeMethod = Literal[
89
+ "lock-upgrade", # version already allowed: uv lock --upgrade-package pkg==ver
90
+ "raise-bound", # direct dependency whose specifier blocks the fix: edit pyproject.toml
91
+ "parent-upgrade", # transitive dependency blocked by its parent: upgrade the parent too
92
+ "override", # JS only: forced with overrides / resolutions because a parent caps it
93
+ "poetry-update",
94
+ "poetry-add",
95
+ ]
96
+
97
+
98
+ class _Model(BaseModel):
99
+ model_config = ConfigDict(frozen=False, extra="forbid")
100
+
101
+
102
+ class Project(_Model):
103
+ root: Path
104
+ """The worktree for ``fix``; the given path for ``scan``."""
105
+ manager: Manager
106
+ lockfile: Path
107
+ commit_sha: str | None = None
108
+ base_branch: str = "main"
109
+ members: list[str] = Field(default_factory=list)
110
+ """Workspace members sharing the root lockfile, relative to ``root`` ('' never appears)."""
111
+
112
+ def manifests(self) -> list[Path]:
113
+ """The root manifest, then each member's."""
114
+ name = MANIFEST[self.manager]
115
+ return [self.root / name, *(self.root / m / name for m in self.members)]
116
+
117
+ def manifest_label(self, path: Path) -> str:
118
+ return path.relative_to(self.root).as_posix()
119
+
120
+
121
+ class VersionRange(_Model):
122
+ """One affected interval from an advisory: introduced <= v < fixed (or <= last_affected)."""
123
+
124
+ introduced: str = "0"
125
+ fixed: str | None = None
126
+ last_affected: str | None = None
127
+
128
+
129
+ class SourceHit(_Model):
130
+ """One scanner's report of a finding."""
131
+
132
+ source: str
133
+ """"osv" or "import:<file>"."""
134
+ tool: str
135
+ """"osv-scanner", "trivy" or "wiz"."""
136
+ tool_version: str | None = None
137
+ target: str = "source"
138
+ """"source" (repo/lockfile) or "image:<ref>"."""
139
+ raw_id: str
140
+ """The advisory ID that tool used."""
141
+ severity: Severity = Severity.UNKNOWN
142
+ installed_version: str
143
+ """As that tool saw it; an image can be older than the lockfile."""
144
+ fixed_version: str | None = None
145
+
146
+
147
+ def normalize_package(name: str, ecosystem: str = "PyPI") -> str:
148
+ """The name two findings must share to be the same package.
149
+
150
+ PyPI: PEP 503 (``Jinja2`` and ``jinja2`` are one package). npm: lower case only, since
151
+ ``lodash.merge`` and ``lodash-merge`` are different packages there.
152
+ """
153
+ if ecosystem == "PyPI":
154
+ return str(canonicalize_name(name))
155
+ return name.lower()
156
+
157
+
158
+ def finding_key(ecosystem: str, package: str, aliases: list[str]) -> str:
159
+ """Stable identity for a finding: ecosystem | package | alias group. Never the version.
160
+
161
+ The alias group is represented by its lowest-sorted ID. Comparisons between scans
162
+ must still match on alias *overlap* (see the rescan step), because an advisory can
163
+ gain a new alias, such as a CVE assigned after the GHSA, between runs.
164
+ """
165
+ if not aliases:
166
+ raise ValueError("a finding needs at least one advisory ID")
167
+ return f"{ecosystem}|{normalize_package(package, ecosystem)}|{min(aliases)}"
168
+
169
+
170
+ class Finding(_Model):
171
+ key: str
172
+ """ecosystem|package|alias group; see :func:`finding_key`."""
173
+ advisory_id: str
174
+ """Preferred CVE, else GHSA / PYSEC id."""
175
+ aliases: list[str]
176
+ """The alias group: all IDs for the same issue."""
177
+ ecosystem: str
178
+ """"PyPI", or the OS package type ("apk", "deb")."""
179
+ package: str
180
+ installed_version: str
181
+ """Version in the lockfile (or the image, if the package is not in the lockfile)."""
182
+ fixed_versions: list[str] = Field(default_factory=list)
183
+ """Fixed versions above the installed one, lowest first."""
184
+ affected_ranges: list[VersionRange] = Field(default_factory=list)
185
+ """Where the advisory applies; used to test whether a candidate version is still affected."""
186
+ in_lockfile: bool = True
187
+ fixed_in_source: bool = False
188
+ """Reported by an image import, but the lockfile already holds a fixed version."""
189
+ is_direct: bool = False
190
+ dev_only: bool = False
191
+ """Reached only through dependency groups (dev), not at runtime."""
192
+ dependency_paths: list[list[str]] = Field(default_factory=list)
193
+ """Each path: app -> parent -> vulnerable package."""
194
+ severity: Severity = Severity.UNKNOWN
195
+ """Highest across sources."""
196
+ cvss: float | None = None
197
+ epss: float | None = None
198
+ in_kev: bool = False
199
+ references: list[str] = Field(default_factory=list)
200
+ sources: list[SourceHit] = Field(default_factory=list)
201
+
202
+
203
+ class Upgrade(_Model):
204
+ """One planned package change."""
205
+
206
+ package: str
207
+ from_version: str
208
+ to_version: str
209
+ """Lowest non-yanked version that fixes all of this package's advisories."""
210
+ method: UpgradeMethod
211
+ finding_keys: list[str]
212
+ """The findings this upgrade is expected to fix."""
213
+ unfixed_keys: list[str] = Field(default_factory=list)
214
+ """Findings of this package that the target does not fix (partial fix within the major)."""
215
+ parents: list[str] = Field(default_factory=list)
216
+ """For parent-upgrade: the direct dependencies upgraded along with it."""
217
+
218
+
219
+ class ValidationResult(_Model):
220
+ ran: bool
221
+ """False when ``validate.test`` is ``none``."""
222
+ passed: bool | None = None
223
+ failed_tests: list[str] = Field(default_factory=list)
224
+ """Test names only, never log output."""
225
+ log_path: str | None = None
226
+ """The full log stays on disk."""
227
+
228
+
229
+ class FixResult(_Model):
230
+ finding_key: str
231
+ status: FixStatus
232
+ upgrade: Upgrade | None = None
233
+ note: str = ""
234
+ """Why, in plain words."""
235
+
236
+
237
+ class RunReport(_Model):
238
+ run_id: str
239
+ repo: str
240
+ commit_sha: str | None
241
+ started_at: datetime
242
+ tool_versions: dict[str, str] = Field(default_factory=dict)
243
+ findings_before: list[Finding] = Field(default_factory=list)
244
+ findings_after: list[Finding] = Field(default_factory=list)
245
+ results: list[FixResult] = Field(default_factory=list)
246
+ baseline: ValidationResult | None = None
247
+ final: ValidationResult | None = None
248
+ pr_url: str | None = None
patchloop/plan.py ADDED
@@ -0,0 +1,194 @@
1
+ """Pick a target version for each vulnerable package.
2
+
3
+ Rules (see the plan, step 6):
4
+ - If an allowed version fixes all of a package's advisories, pick the lowest non-yanked one.
5
+ - Otherwise pick the lowest version in the current major that fixes the most advisories
6
+ (a partial fix); the rest are NO_SAFE_FIX ("needs a major upgrade").
7
+ - If nothing fixes any of them, the package is NO_SAFE_FIX.
8
+ - Ride-along: when a package is upgraded anyway, its below-threshold advisories are fixed
9
+ too if the target, or a later version in the same major, also fixes them. They never
10
+ change which in-scope advisories get fixed, and are never reported as NO_SAFE_FIX.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import tomllib
16
+ from collections import defaultdict
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+ from patchloop.lockgraph import LockGraph
22
+ from patchloop.models import Finding, Upgrade, normalize_package
23
+ from patchloop.pypi import ReleaseIndex
24
+ from patchloop.specifiers import allows
25
+ from patchloop.versions import is_affected, is_major_upgrade, parse, sort_versions
26
+
27
+
28
+ @dataclass
29
+ class Plan:
30
+ upgrades: list[Upgrade] = field(default_factory=list)
31
+ no_fix: dict[str, str] = field(default_factory=dict)
32
+ """finding key -> plain-words reason it gets NO_SAFE_FIX."""
33
+ warnings: list[str] = field(default_factory=list)
34
+
35
+
36
+ _POETRY_INDEX_SOURCES = {"legacy", "pypi"}
37
+
38
+
39
+ def _from_index(pkg: dict[str, object], poetry: bool) -> bool:
40
+ source = pkg.get("source") or {}
41
+ if not isinstance(source, dict):
42
+ return False
43
+ if poetry: # poetry.lock: no [package.source] means PyPI; "legacy" is a private index
44
+ return not source or source.get("type") in _POETRY_INDEX_SOURCES
45
+ return "registry" in source # uv.lock
46
+
47
+
48
+ def registry_packages(lockfile: Path) -> set[str]:
49
+ """Packages that come from a package index (not a path, git or URL source)."""
50
+ data = tomllib.loads(lockfile.read_text(encoding="utf-8"))
51
+ poetry = lockfile.name == "poetry.lock"
52
+ return {normalize_package(p["name"]) for p in data.get("package", []) if _from_index(p, poetry)}
53
+
54
+
55
+ def candidates(
56
+ package: str, installed: str, findings: list[Finding], index: ReleaseIndex
57
+ ) -> tuple[list[str], bool]:
58
+ """Versions above ``installed`` to consider, and whether they came from the index."""
59
+ current = parse(installed)
60
+ allow_pre = bool(current and current.is_prerelease)
61
+ released = index.releases(package)
62
+ from_index = released is not None
63
+ pool = released if released is not None else [v for f in findings for v in f.fixed_versions]
64
+ out = []
65
+ for text in sort_versions(pool):
66
+ v = parse(text)
67
+ if v is None or current is None or v <= current:
68
+ continue
69
+ if v.is_prerelease and not allow_pre:
70
+ continue
71
+ out.append(text)
72
+ return out, from_index
73
+
74
+
75
+ def choose_target(
76
+ installed: str, findings: list[Finding], cands: list[str], allow_major: bool
77
+ ) -> tuple[str | None, list[Finding], dict[str, str]]:
78
+ """Return (target, fixed findings, {unfixed key: reason})."""
79
+ allowed = [c for c in cands if allow_major or not is_major_upgrade(installed, c)]
80
+
81
+ def fixed_by(c: str) -> list[Finding]:
82
+ return [f for f in findings if not is_affected(c, f)]
83
+
84
+ target: str | None = None
85
+ fixed: list[Finding] = []
86
+ for c in allowed:
87
+ hit = fixed_by(c)
88
+ if len(hit) == len(findings):
89
+ target, fixed = c, hit
90
+ break
91
+ if len(hit) > len(fixed):
92
+ target, fixed = c, hit
93
+
94
+ reasons: dict[str, str] = {}
95
+ fixed_keys = {f.key for f in fixed}
96
+ for f in findings:
97
+ if f.key in fixed_keys:
98
+ continue
99
+ anywhere = next((c for c in cands if not is_affected(c, f)), None)
100
+ if anywhere is not None and not allow_major and is_major_upgrade(installed, anywhere):
101
+ reasons[f.key] = f"needs a major upgrade (fixed in {anywhere}); majors are not allowed"
102
+ elif anywhere is not None:
103
+ reasons[f.key] = f"fixed in {anywhere}, but no single version fixes it with the rest"
104
+ else:
105
+ reasons[f.key] = "no fixed version has been released"
106
+ return target, fixed, reasons
107
+
108
+
109
+ def ride_along(
110
+ target: str, fixed: list[Finding], extras: list[Finding], cands: list[str]
111
+ ) -> tuple[str, list[Finding]]:
112
+ """A target in the same major that also fixes extras, without losing any fixed finding.
113
+
114
+ Prefers the lowest version that fixes every extra; else keeps ``target`` and whichever
115
+ extras it already fixes.
116
+ """
117
+ if not extras:
118
+ return target, []
119
+ tv = parse(target)
120
+ same_major = [
121
+ c for c in cands if not is_major_upgrade(target, c) and (p := parse(c)) and tv and p >= tv
122
+ ]
123
+ for c in same_major:
124
+ if all(not is_affected(c, f) for f in [*fixed, *extras]):
125
+ return c, extras
126
+ return target, [f for f in extras if not is_affected(target, f)]
127
+
128
+
129
+ def build_plan(
130
+ findings: list[Finding],
131
+ graph: LockGraph,
132
+ pyproject_text: str,
133
+ lockfile: Path,
134
+ index: ReleaseIndex,
135
+ allow_major: bool,
136
+ extras: list[Finding] | None = None,
137
+ *,
138
+ registry: set[str] | None = None,
139
+ manifest_allows: Callable[[str, str, str], bool] | None = None,
140
+ ) -> Plan:
141
+ """Plan upgrades for ``findings``; ``extras`` (below the threshold) only ride along.
142
+
143
+ ``registry`` (packages from an index) and ``manifest_allows(text, package, version)``
144
+ default to Python's (the lockfile's sources, pyproject.toml's specifiers).
145
+ """
146
+ plan = Plan()
147
+ from_registry = registry if registry is not None else registry_packages(lockfile)
148
+ allows_fn = manifest_allows or allows
149
+ groups: dict[tuple[str, str], list[Finding]] = defaultdict(list)
150
+ for f in findings:
151
+ if f.in_lockfile and not f.fixed_in_source:
152
+ groups[(normalize_package(f.package, f.ecosystem), f.installed_version)].append(f)
153
+ riders: dict[tuple[str, str], list[Finding]] = defaultdict(list)
154
+ for f in extras or []:
155
+ key = (normalize_package(f.package, f.ecosystem), f.installed_version)
156
+ if f.in_lockfile and not f.fixed_in_source and key in groups:
157
+ riders[key].append(f)
158
+
159
+ for (package, installed), items in sorted(groups.items()):
160
+ if package not in from_registry:
161
+ for f in items:
162
+ plan.no_fix[f.key] = "installed from a path, git or URL source, not an index"
163
+ continue
164
+ cands, from_index = candidates(
165
+ package, installed, [*items, *riders[(package, installed)]], index
166
+ )
167
+ if not from_index:
168
+ plan.warnings.append(
169
+ f"could not read {package}'s releases from the index; "
170
+ "using advisory fixed versions without a yanked check"
171
+ )
172
+ target, fixed, reasons = choose_target(installed, items, cands, allow_major)
173
+ plan.no_fix.update(reasons)
174
+ if target is None:
175
+ continue
176
+ target, riding = ride_along(target, fixed, riders[(package, installed)], cands)
177
+ # A copy the manifest's range does not allow is a nested one (npm can install an
178
+ # older copy under a parent): fixing it must not touch the direct entry's range.
179
+ is_direct = graph.is_direct(package) and allows_fn(pyproject_text, package, installed)
180
+ if is_direct and not allows_fn(pyproject_text, package, target):
181
+ method = "raise-bound"
182
+ else:
183
+ method = "lock-upgrade"
184
+ plan.upgrades.append(
185
+ Upgrade(
186
+ package=package,
187
+ from_version=installed,
188
+ to_version=target,
189
+ method=method,
190
+ finding_keys=[f.key for f in [*fixed, *riding]],
191
+ unfixed_keys=list(reasons),
192
+ )
193
+ )
194
+ return plan
patchloop/pr_body.py ADDED
@@ -0,0 +1,253 @@
1
+ """Title and Markdown body of the PatchLoop PR.
2
+
3
+ Every finding appears somewhere: fixed, fixed but untested, or not fixed with the reason.
4
+ Failing tests are listed by name only (test output can hold secrets), and no local paths
5
+ from the developer's machine are included.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import defaultdict
11
+ from dataclasses import dataclass, field
12
+
13
+ from patchloop import __version__
14
+ from patchloop.build import ImageCheck
15
+ from patchloop.models import Finding, FixResult, FixStatus, RunReport, Severity
16
+
17
+ MARKER = "<!-- patchloop:pr -->"
18
+ GITHUB_LIMIT = 60_000 # GitHub allows 65,536 characters; keep a margin
19
+ _OSV = "https://osv.dev/vulnerability/"
20
+
21
+
22
+ @dataclass
23
+ class BodyInput:
24
+ report: RunReport
25
+ base_ref: str
26
+ manifest_changes: dict[str, list[tuple[str, str, str]]] = field(default_factory=dict)
27
+ image_check: ImageCheck | None = None
28
+ manifest: str = "pyproject.toml"
29
+ project_rel: str = ""
30
+ """The project's folder in the repo ('' for the root)."""
31
+
32
+
33
+ def _cell(text: str) -> str:
34
+ return text.replace("|", "\\|").replace("\n", " ").strip()
35
+
36
+
37
+ def _plural(n: int, word: str, many: str | None = None) -> str:
38
+ return f"{n} {word if n == 1 else (many or word + 's')}"
39
+
40
+
41
+ def _advisory(f: Finding) -> str:
42
+ sev = "" if f.severity is Severity.UNKNOWN else f" ({f.severity.value.lower()})"
43
+ kev = " **KEV**" if f.in_kev else ""
44
+ epss = f" EPSS {f.epss:.0%}" if f.epss is not None and f.epss >= 0.1 else ""
45
+ return f"[{f.advisory_id}]({_OSV}{f.advisory_id}){sev}{kev}{epss}"
46
+
47
+
48
+ def _how(r: FixResult, changes: dict[str, list[tuple[str, str, str]]]) -> str:
49
+ u = r.upgrade
50
+ if u is None:
51
+ return ""
52
+ if u.method == "raise-bound" and changes.get(u.package):
53
+ return "; ".join(f"{file}: `{old}` → `{new}`" for file, old, new in changes[u.package])
54
+ if u.method == "parent-upgrade":
55
+ return f"upgraded with {', '.join(u.parents)}"
56
+ if u.method == "override":
57
+ parents = f" ({', '.join(u.parents)} caps it)" if u.parents else ""
58
+ return f"**forced via override**{parents}; check it works with the parent"
59
+ return "lockfile only"
60
+
61
+
62
+ def _table(header: list[str], rows: list[list[str]], max_rows: int | None) -> list[str]:
63
+ lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
64
+ shown = rows if max_rows is None else rows[:max_rows]
65
+ lines += ["| " + " | ".join(_cell(c) for c in row) + " |" for row in shown]
66
+ if len(shown) < len(rows):
67
+ lines.append(f"\n…and {len(rows) - len(shown)} more (see report.json from this run).")
68
+ return lines
69
+
70
+
71
+ def _by_package(results: list[FixResult], by_key: dict[str, Finding]) -> dict[str, list[FixResult]]:
72
+ grouped: dict[str, list[FixResult]] = defaultdict(list)
73
+ for r in results:
74
+ grouped[by_key[r.finding_key].package.lower()].append(r)
75
+ return dict(sorted(grouped.items()))
76
+
77
+
78
+ def _fixed_rows(
79
+ results: list[FixResult],
80
+ by_key: dict[str, Finding],
81
+ changes: dict[str, list[tuple[str, str, str]]],
82
+ ) -> list[list[str]]:
83
+ rows = []
84
+ for pkg, items in _by_package(results, by_key).items():
85
+ u = items[0].upgrade
86
+ change = f"{u.from_version} → {u.to_version}" if u else ""
87
+ advisories = ", ".join(_advisory(by_key[r.finding_key]) for r in items)
88
+ rows.append([f"`{pkg}`", change, advisories, _how(items[0], changes)])
89
+ return rows
90
+
91
+
92
+ def _reason(r: FixResult) -> str:
93
+ if r.status is FixStatus.FIXED_BUT_TESTS_FAILED and r.upgrade is not None:
94
+ return f"upgrading to {r.upgrade.to_version} {r.note}"
95
+ return r.note
96
+
97
+
98
+ def _reason_rows(results: list[FixResult], by_key: dict[str, Finding]) -> list[list[str]]:
99
+ """One row per package and reason, with all its advisories in that row."""
100
+ grouped: dict[tuple[str, str, str], list[Finding]] = defaultdict(list)
101
+ for r in results:
102
+ f = by_key[r.finding_key]
103
+ grouped[(f.package.lower(), f.installed_version, _reason(r))].append(f)
104
+ return [
105
+ [f"`{pkg}` {version}", ", ".join(_advisory(f) for f in findings), why]
106
+ for (pkg, version, why), findings in sorted(grouped.items())
107
+ ]
108
+
109
+
110
+ def _image_check(check: ImageCheck) -> list[str]:
111
+ tools = " and ".join(s.capitalize() for s in check.scanners)
112
+ lines = [
113
+ "",
114
+ "## Image check",
115
+ "",
116
+ f"The image was built from the Dockerfile before and after this change and scanned "
117
+ f"with {tools}: **{check.total_before} → {check.total_after} findings**.",
118
+ "",
119
+ "| Severity | Before | After |",
120
+ "|---|---|---|",
121
+ ]
122
+ for sev in reversed(Severity):
123
+ if check.before[sev] or check.after[sev]:
124
+ lines.append(f"| {sev.value.lower()} | {check.before[sev]} | {check.after[sev]} |")
125
+ if check.gone:
126
+ lines += [
127
+ "",
128
+ f"<details><summary>Gone from the rebuilt image ({len(check.gone)})</summary>",
129
+ "",
130
+ ]
131
+ lines += [f"- {_cell(g)}" for g in sorted(check.gone)]
132
+ lines += ["", "</details>"]
133
+ return lines
134
+
135
+
136
+ def title(report: RunReport, project_rel: str = "") -> str:
137
+ by_key = {f.key: f for f in report.findings_before}
138
+ fixed = [r for r in report.results if r.status.counts_as_fixed]
139
+ pkgs = sorted({by_key[r.finding_key].package.lower() for r in fixed})
140
+ names = ", ".join(pkgs[:3]) + (f", +{len(pkgs) - 3} more" if len(pkgs) > 3 else "")
141
+ where = f" in {project_rel}" if project_rel else ""
142
+ count = _plural(len(fixed), "vulnerability", "vulnerabilities")
143
+ return f"PatchLoop: fix {count}{where} ({names})"
144
+
145
+
146
+ def body(data: BodyInput, *, max_rows: int | None = None, with_skipped: bool = True) -> str:
147
+ report = data.report
148
+ by_key = {f.key: f for f in [*report.findings_after, *report.findings_before]}
149
+ groups: dict[FixStatus, list[FixResult]] = defaultdict(list)
150
+ for r in report.results:
151
+ groups[r.status].append(r)
152
+ validated = groups[FixStatus.FIXED_AND_VALIDATED]
153
+ untested = groups[FixStatus.FIXED_NOT_TESTED]
154
+ fixed_total = len(validated) + len(untested)
155
+ not_fixed_statuses = (
156
+ FixStatus.FIXED_BUT_TESTS_FAILED,
157
+ FixStatus.STILL_PRESENT,
158
+ FixStatus.NO_SAFE_FIX,
159
+ FixStatus.FIXED_IN_SOURCE,
160
+ FixStatus.OUT_OF_SCOPE,
161
+ )
162
+ not_fixed = sum(len(groups[s]) for s in not_fixed_statuses)
163
+ pkgs = {by_key[r.finding_key].package.lower() for r in [*validated, *untested]}
164
+
165
+ out = [
166
+ MARKER,
167
+ f"This PR fixes **{_plural(fixed_total, 'vulnerability', 'vulnerabilities')}** in "
168
+ f"{_plural(len(pkgs), 'package')}. It changes only `{data.manifest}` and the lockfile.",
169
+ ]
170
+ if not_fixed:
171
+ out.append(
172
+ f"{_plural(not_fixed, 'other finding')} could not be fixed here; each is listed "
173
+ "below with the reason."
174
+ )
175
+
176
+ fixed_header = ["Package", "Change", "Advisories", "How"]
177
+ if validated:
178
+ out += ["", "## Fixed", ""]
179
+ tested = report.final is not None and report.final.ran and report.final.passed
180
+ out += [
181
+ ("The project's tests passed before the change and with it. " if tested else "")
182
+ + "A rescan with OSV-Scanner confirms each of these is gone.",
183
+ "",
184
+ ]
185
+ out += _table(
186
+ fixed_header,
187
+ _fixed_rows(validated, by_key, data.manifest_changes),
188
+ max_rows,
189
+ )
190
+ if untested:
191
+ out += [
192
+ "",
193
+ "## Not tested locally — check CI",
194
+ "",
195
+ "No tests ran for this repo (tests are turned off, or the project has no test "
196
+ "script), so these upgrades were not run against a test suite. A rescan "
197
+ "confirms each one is gone.",
198
+ "",
199
+ ]
200
+ out += _table(
201
+ fixed_header,
202
+ _fixed_rows(untested, by_key, data.manifest_changes),
203
+ max_rows,
204
+ )
205
+
206
+ if data.image_check is not None:
207
+ out += _image_check(data.image_check)
208
+
209
+ sections = [
210
+ (FixStatus.FIXED_BUT_TESTS_FAILED, "Needs code changes",
211
+ "The upgrade removes the vulnerability but makes these tests fail, so it is left out."),
212
+ (FixStatus.STILL_PRESENT, "Still present",
213
+ "An upgrade was tried but the vulnerability is still there."),
214
+ (FixStatus.NO_SAFE_FIX, "No safe fix", "No fixed release fits, or only a major upgrade."),
215
+ (FixStatus.FIXED_IN_SOURCE, "Rebuild the image",
216
+ "The lockfile already has a fixed version; the image was built before it."),
217
+ (FixStatus.OUT_OF_SCOPE, "Needs a base-image or Dockerfile change",
218
+ "Found in an image, but not managed by the lockfile."),
219
+ ] # fmt: skip
220
+ if not_fixed:
221
+ out += ["", "## Not fixed"]
222
+ for status, heading, intro in sections:
223
+ if groups[status]:
224
+ out += ["", f"### {heading} ({len(groups[status])})", "", intro, ""]
225
+ rows = _reason_rows(groups[status], by_key)
226
+ out += _table(["Package", "Advisories", "Why"], rows, max_rows)
227
+
228
+ skipped = groups[FixStatus.SKIPPED]
229
+ if skipped and with_skipped:
230
+ out += ["", f"<details><summary>Skipped ({len(skipped)})</summary>", ""]
231
+ out += _table(["Package", "Advisories", "Why"], _reason_rows(skipped, by_key), max_rows)
232
+ out += ["", "</details>"]
233
+
234
+ tools = ", ".join(f"{k} {v}" for k, v in sorted(report.tool_versions.items()))
235
+ sha = (report.commit_sha or "")[:8]
236
+ out += [
237
+ "",
238
+ "---",
239
+ f"<sub>PatchLoop {__version__} · run `{report.run_id}` · base `{data.base_ref}` @ "
240
+ f"`{sha}`{' · ' + tools if tools else ''}. This branch is rebuilt on every run; "
241
+ "push your own changes to a different branch.</sub>",
242
+ ]
243
+ return "\n".join(out) + "\n"
244
+
245
+
246
+ def render(data: BodyInput) -> tuple[str, str]:
247
+ """(title, body), shortened if the body would pass GitHub's size limit."""
248
+ text = body(data)
249
+ if len(text) > GITHUB_LIMIT:
250
+ text = body(data, max_rows=50, with_skipped=False)
251
+ if len(text) > GITHUB_LIMIT:
252
+ text = body(data, max_rows=10, with_skipped=False)
253
+ return title(data.report, data.project_rel), text