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.
- patchloop/__init__.py +23 -0
- patchloop/api.py +110 -0
- patchloop/build.py +118 -0
- patchloop/classify.py +137 -0
- patchloop/cli.py +370 -0
- patchloop/config.py +148 -0
- patchloop/detect.py +133 -0
- patchloop/doctor.py +207 -0
- patchloop/enrich/__init__.py +66 -0
- patchloop/enrich/epss.py +65 -0
- patchloop/enrich/kev.py +39 -0
- patchloop/fixers/__init__.py +1 -0
- patchloop/fixers/base.py +20 -0
- patchloop/fixers/js_fix.py +288 -0
- patchloop/fixers/poetry_fix.py +144 -0
- patchloop/fixers/uv_fix.py +118 -0
- patchloop/git_ops.py +171 -0
- patchloop/github.py +161 -0
- patchloop/hints.py +180 -0
- patchloop/images.py +208 -0
- patchloop/isolate.py +57 -0
- patchloop/js/__init__.py +1 -0
- patchloop/js/lockfiles.py +237 -0
- patchloop/js/manifest.py +121 -0
- patchloop/js/ranges.py +130 -0
- patchloop/js/registry.py +67 -0
- patchloop/js/yarn.py +189 -0
- patchloop/lockgraph.py +181 -0
- patchloop/models.py +248 -0
- patchloop/plan.py +194 -0
- patchloop/pr_body.py +253 -0
- patchloop/prioritize.py +38 -0
- patchloop/proc.py +71 -0
- patchloop/py.typed +0 -0
- patchloop/pypi.py +60 -0
- patchloop/report/__init__.py +1 -0
- patchloop/report/console.py +243 -0
- patchloop/report/json_out.py +26 -0
- patchloop/report/sarif.py +143 -0
- patchloop/runner.py +494 -0
- patchloop/scanner.py +214 -0
- patchloop/sources/__init__.py +1 -0
- patchloop/sources/base.py +5 -0
- patchloop/sources/imports.py +292 -0
- patchloop/sources/merge.py +113 -0
- patchloop/sources/osv.py +255 -0
- patchloop/specifiers.py +259 -0
- patchloop/validate.py +198 -0
- patchloop/versions.py +81 -0
- patchloop/workspaces.py +142 -0
- patchloop/worktree.py +153 -0
- patchloop-0.2.0.dist-info/METADATA +388 -0
- patchloop-0.2.0.dist-info/RECORD +56 -0
- patchloop-0.2.0.dist-info/WHEEL +4 -0
- patchloop-0.2.0.dist-info/entry_points.txt +3 -0
- patchloop-0.2.0.dist-info/licenses/LICENSE +21 -0
patchloop/specifiers.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Read and minimally edit dependency specifiers in pyproject.toml.
|
|
2
|
+
|
|
3
|
+
Covers PEP 621 (``[project]``), PEP 735 dependency groups, and Poetry's own tables
|
|
4
|
+
(``[tool.poetry.dependencies]``, ``[tool.poetry.group.<name>.dependencies]``).
|
|
5
|
+
|
|
6
|
+
Edits use tomlkit so comments and formatting survive. Only the requirement strings for
|
|
7
|
+
the package being fixed are touched.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import tomlkit
|
|
17
|
+
from packaging.requirements import InvalidRequirement, Requirement
|
|
18
|
+
from packaging.specifiers import InvalidSpecifier, SpecifierSet
|
|
19
|
+
from packaging.version import Version
|
|
20
|
+
from tomlkit.items import Array
|
|
21
|
+
|
|
22
|
+
from patchloop.models import normalize_package
|
|
23
|
+
from patchloop.versions import bump_at, parse
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SpecifierEditError(Exception):
|
|
27
|
+
"""The requirement can't be changed to allow the fix without a bigger change."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _arrays(doc: Any) -> Iterator[Array]:
|
|
31
|
+
project = doc.get("project", {})
|
|
32
|
+
if isinstance(project.get("dependencies"), Array):
|
|
33
|
+
yield project["dependencies"]
|
|
34
|
+
for arr in (project.get("optional-dependencies") or {}).values():
|
|
35
|
+
if isinstance(arr, Array):
|
|
36
|
+
yield arr
|
|
37
|
+
for arr in (doc.get("dependency-groups") or {}).values():
|
|
38
|
+
if isinstance(arr, Array):
|
|
39
|
+
yield arr
|
|
40
|
+
uv = (doc.get("tool") or {}).get("uv") or {}
|
|
41
|
+
for key in ("dev-dependencies", "constraint-dependencies", "override-dependencies"):
|
|
42
|
+
if isinstance(uv.get(key), Array):
|
|
43
|
+
yield uv[key]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _matching(doc: Any, package: str) -> Iterator[tuple[Array, int, Requirement]]:
|
|
47
|
+
name = normalize_package(package)
|
|
48
|
+
for arr in _arrays(doc):
|
|
49
|
+
for i, item in enumerate(arr):
|
|
50
|
+
if not isinstance(item, str):
|
|
51
|
+
continue # e.g. {include-group = "..."}
|
|
52
|
+
try:
|
|
53
|
+
req = Requirement(str(item))
|
|
54
|
+
except InvalidRequirement:
|
|
55
|
+
continue
|
|
56
|
+
if normalize_package(req.name) == name:
|
|
57
|
+
yield arr, i, req
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def requirement_strings(pyproject_text: str, package: str) -> list[str]:
|
|
61
|
+
"""Every requirement on ``package`` in pyproject.toml, as written (for messages)."""
|
|
62
|
+
doc = tomlkit.parse(pyproject_text)
|
|
63
|
+
out = [str(req) for _, _, req in _matching(doc, package)]
|
|
64
|
+
for table, key in _poetry_entries(doc, package):
|
|
65
|
+
out += [f'{key} = "{c}"' for _, _, c in _poetry_versions(table, key)]
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def allows(pyproject_text: str, package: str, version: str) -> bool:
|
|
70
|
+
"""Do all requirements on ``package`` in pyproject.toml allow ``version``?"""
|
|
71
|
+
doc = tomlkit.parse(pyproject_text)
|
|
72
|
+
v = Version(version)
|
|
73
|
+
if not all(
|
|
74
|
+
req.specifier.contains(v, prereleases=True) for _, _, req in _matching(doc, package)
|
|
75
|
+
):
|
|
76
|
+
return False
|
|
77
|
+
return all(
|
|
78
|
+
poetry_allows(constraint, version)
|
|
79
|
+
for table, key in _poetry_entries(doc, package)
|
|
80
|
+
for _, _, constraint in _poetry_versions(table, key)
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _components(text: str) -> int:
|
|
85
|
+
return len(text.rstrip(".*").split("."))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def adjust_specifier(spec: SpecifierSet, target: str) -> SpecifierSet:
|
|
89
|
+
"""Smallest change to ``spec`` so it allows ``target`` (and nothing below it)."""
|
|
90
|
+
t = Version(target)
|
|
91
|
+
out: list[str] = []
|
|
92
|
+
for s in spec:
|
|
93
|
+
op, ver = s.operator, s.version
|
|
94
|
+
if s.contains(t, prereleases=True):
|
|
95
|
+
if op in (">=", ">") and (pv := parse(ver)) is not None and pv < t:
|
|
96
|
+
out.append(f">={target}") # raise the floor so a later lock can't go back
|
|
97
|
+
else:
|
|
98
|
+
out.append(str(s))
|
|
99
|
+
continue
|
|
100
|
+
if op in ("==", "==="):
|
|
101
|
+
if ver.endswith(".*"):
|
|
102
|
+
n = _components(ver)
|
|
103
|
+
out.append("==" + ".".join(str(p) for p in t.release[:n]) + ".*")
|
|
104
|
+
out.append(f">={target}")
|
|
105
|
+
else:
|
|
106
|
+
out.append(f"=={target}")
|
|
107
|
+
elif op == "~=":
|
|
108
|
+
n = _components(ver)
|
|
109
|
+
release = [*t.release, *[0] * max(0, n - len(t.release))] # "2" -> 2.0 for ~=1.4
|
|
110
|
+
if n >= 3:
|
|
111
|
+
out.append("~=" + ".".join(str(p) for p in release))
|
|
112
|
+
else:
|
|
113
|
+
out.append("~=" + ".".join(str(p) for p in release[:n]))
|
|
114
|
+
out.append(f">={target}")
|
|
115
|
+
elif op in ("<", "<="):
|
|
116
|
+
out.append("<" + bump_at(target, _components(ver)))
|
|
117
|
+
elif op == "!=":
|
|
118
|
+
raise SpecifierEditError(f"the fixed version {target} is excluded with !=")
|
|
119
|
+
elif op in (">=", ">"):
|
|
120
|
+
out.append(f">={target}")
|
|
121
|
+
else: # pragma: no cover - packaging knows no other operators
|
|
122
|
+
raise SpecifierEditError(f"unsupported specifier {s}")
|
|
123
|
+
try:
|
|
124
|
+
new = SpecifierSet(",".join(dict.fromkeys(out)))
|
|
125
|
+
except InvalidSpecifier as exc:
|
|
126
|
+
raise SpecifierEditError(f"could not rewrite '{spec}' to allow {target}") from exc
|
|
127
|
+
if not new.contains(t, prereleases=True):
|
|
128
|
+
raise SpecifierEditError(f"could not rewrite '{spec}' to allow {target}")
|
|
129
|
+
return new
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _format(req: Requirement, spec: SpecifierSet) -> str:
|
|
133
|
+
extras = f"[{','.join(sorted(req.extras))}]" if req.extras else ""
|
|
134
|
+
specs = ",".join(sorted(str(s) for s in spec))
|
|
135
|
+
marker = f"; {req.marker}" if req.marker else ""
|
|
136
|
+
return f"{req.name}{extras}{specs}{marker}"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def raise_to(pyproject_text: str, package: str, target: str) -> tuple[str, list[tuple[str, str]]]:
|
|
140
|
+
"""Rewrite every requirement on ``package`` that blocks ``target``.
|
|
141
|
+
|
|
142
|
+
Returns the new file text and a list of (old, new) requirement strings.
|
|
143
|
+
"""
|
|
144
|
+
doc = tomlkit.parse(pyproject_text)
|
|
145
|
+
t = Version(target)
|
|
146
|
+
changes: list[tuple[str, str]] = []
|
|
147
|
+
for arr, i, req in list(_matching(doc, package)):
|
|
148
|
+
if req.specifier.contains(t, prereleases=True):
|
|
149
|
+
continue
|
|
150
|
+
new = _format(req, adjust_specifier(req.specifier, target))
|
|
151
|
+
changes.append((str(arr[i]), new))
|
|
152
|
+
arr[i] = new
|
|
153
|
+
for table, key in list(_poetry_entries(doc, package)):
|
|
154
|
+
for holder, field, constraint in _poetry_versions(table, key):
|
|
155
|
+
if poetry_allows(constraint, target):
|
|
156
|
+
continue
|
|
157
|
+
new_constraint = raise_poetry(constraint, target)
|
|
158
|
+
holder[field] = new_constraint
|
|
159
|
+
changes.append((f'{key} = "{constraint}"', f'{key} = "{new_constraint}"'))
|
|
160
|
+
return tomlkit.dumps(doc), changes
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# --- Poetry-style constraints: [tool.poetry.dependencies] and [tool.poetry.group.*] -----
|
|
164
|
+
|
|
165
|
+
_POETRY_TOKEN = re.compile(r"(\^|~=|~|==|!=|>=|<=|>|<|=)?\s*(\*|[0-9][0-9A-Za-z.*+!-]*)")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _caret_upper(v: Version, given: int) -> str:
|
|
169
|
+
parts = list(v.release[:given]) or [0]
|
|
170
|
+
for i, p in enumerate(parts):
|
|
171
|
+
if p != 0:
|
|
172
|
+
return ".".join(str(x) for x in [*parts[:i], p + 1])
|
|
173
|
+
bumped = [*parts[:-1], parts[-1] + 1]
|
|
174
|
+
return ".".join(str(x) for x in bumped)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def poetry_specifier(constraint: str) -> SpecifierSet:
|
|
178
|
+
"""One Poetry constraint (no ``||``) as a PEP 440 specifier set.
|
|
179
|
+
|
|
180
|
+
``^1.2.3`` -> ``>=1.2.3,<2``; ``~1.2.3`` -> ``>=1.2.3,<1.3``; ``1.2.3`` -> ``==1.2.3``.
|
|
181
|
+
"""
|
|
182
|
+
specs: list[str] = []
|
|
183
|
+
for op, ver in _POETRY_TOKEN.findall(constraint.replace(",", " ")):
|
|
184
|
+
if ver == "*":
|
|
185
|
+
continue
|
|
186
|
+
v = Version(ver.rstrip(".*")) if ver.rstrip(".*") else None
|
|
187
|
+
given = _components(ver)
|
|
188
|
+
if op == "^" and v is not None:
|
|
189
|
+
specs += [f">={ver}", f"<{_caret_upper(v, given)}"]
|
|
190
|
+
elif op == "~" and v is not None:
|
|
191
|
+
upper = v.release[0] + 1 if given == 1 else None
|
|
192
|
+
if upper is not None:
|
|
193
|
+
specs += [f">={ver}", f"<{upper}"]
|
|
194
|
+
else:
|
|
195
|
+
specs += [f">={ver}", f"<{v.release[0]}.{v.release[1] + 1}"]
|
|
196
|
+
elif op in ("", "="):
|
|
197
|
+
specs.append(f"=={ver}")
|
|
198
|
+
else:
|
|
199
|
+
specs.append(f"{op}{ver}")
|
|
200
|
+
return SpecifierSet(",".join(specs))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def poetry_allows(constraint: str, version: str) -> bool:
|
|
204
|
+
v = Version(version)
|
|
205
|
+
return any(
|
|
206
|
+
poetry_specifier(alt).contains(v, prereleases=True) for alt in constraint.split("||")
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def raise_poetry(constraint: str, target: str) -> str:
|
|
211
|
+
"""Smallest Poetry-style rewrite of ``constraint`` that allows ``target``, same style."""
|
|
212
|
+
c = constraint.strip()
|
|
213
|
+
if "||" in c:
|
|
214
|
+
raise SpecifierEditError(f"cannot safely rewrite the Poetry constraint '{c}'")
|
|
215
|
+
if c.startswith("^") and "," not in c:
|
|
216
|
+
return f"^{target}"
|
|
217
|
+
if c.startswith("~") and not c.startswith("~=") and "," not in c:
|
|
218
|
+
return f"~{target}" if _components(c[1:]) > 1 else f"~{Version(target).major}"
|
|
219
|
+
if re.fullmatch(r"=?=?\s*[0-9][0-9A-Za-z.+!-]*", c):
|
|
220
|
+
return target
|
|
221
|
+
new = adjust_specifier(poetry_specifier(c), target)
|
|
222
|
+
return ",".join(sorted(str(s) for s in new))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _poetry_tables(doc: Any) -> Iterator[Any]:
|
|
226
|
+
poetry = (doc.get("tool") or {}).get("poetry") or {}
|
|
227
|
+
for key in ("dependencies", "dev-dependencies"): # dev-dependencies: Poetry < 1.2 style
|
|
228
|
+
if key in poetry:
|
|
229
|
+
yield poetry[key]
|
|
230
|
+
for group in (poetry.get("group") or {}).values():
|
|
231
|
+
if "dependencies" in group:
|
|
232
|
+
yield group["dependencies"]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _poetry_entries(doc: Any, package: str) -> Iterator[tuple[Any, str]]:
|
|
236
|
+
"""(table, key) for every Poetry dependency entry on ``package`` (not ``python``)."""
|
|
237
|
+
name = normalize_package(package)
|
|
238
|
+
for table in _poetry_tables(doc):
|
|
239
|
+
for key in list(table.keys()):
|
|
240
|
+
if key != "python" and normalize_package(key) == name:
|
|
241
|
+
yield table, key
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _poetry_versions(table: Any, key: str) -> list[tuple[Any, str | int, str]]:
|
|
245
|
+
"""(holder, field, constraint) for each version constraint of a Poetry entry.
|
|
246
|
+
|
|
247
|
+
A string entry is held by the table itself; ``{version = ...}`` by the inline table;
|
|
248
|
+
a multiple-constraint entry (a list, one per Python version or platform) by each item.
|
|
249
|
+
Path, git and url entries have no version and give nothing.
|
|
250
|
+
"""
|
|
251
|
+
value = table[key]
|
|
252
|
+
if isinstance(value, str):
|
|
253
|
+
return [(table, key, value)]
|
|
254
|
+
items = value if isinstance(value, list) else [value]
|
|
255
|
+
return [
|
|
256
|
+
(item, "version", str(item["version"]))
|
|
257
|
+
for item in items
|
|
258
|
+
if hasattr(item, "get") and item.get("version") is not None
|
|
259
|
+
]
|
patchloop/validate.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Install the project and run its tests (commands come only from local config)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shlex
|
|
8
|
+
import shutil
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from patchloop import proc
|
|
12
|
+
from patchloop.config import NO_TESTS, ValidateConfig
|
|
13
|
+
from patchloop.fixers.poetry_fix import poetry_major
|
|
14
|
+
from patchloop.js.lockfiles import is_berry, read_manifest
|
|
15
|
+
from patchloop.models import JS_MANAGERS, Manager, ValidationResult
|
|
16
|
+
from patchloop.proc import ToolNotFoundError, ToolTimeoutError
|
|
17
|
+
|
|
18
|
+
# One pattern per test runner; each captures the failing test's name, never its output.
|
|
19
|
+
_FAILED_PATTERNS = [
|
|
20
|
+
re.compile(r"^(?:FAILED|ERROR) (\S+)", re.MULTILINE), # pytest
|
|
21
|
+
re.compile(r"^\s*not ok \d+ - (.+?)\s*(?:#.*)?$", re.MULTILINE), # TAP (node --test)
|
|
22
|
+
re.compile(r"^\s*✖ (.+?)(?: \([\d.]+m?s\))?$", re.MULTILINE), # node --test spec reporter
|
|
23
|
+
re.compile(r"^\s*● (.+?)$", re.MULTILINE), # Jest
|
|
24
|
+
re.compile("^\\s*(?:\u00d7|\u2717) (.+?)(?: \\d+m?s)?$", re.MULTILINE), # Vitest
|
|
25
|
+
re.compile(r"^\s*\d+\) (.+)$", re.MULTILINE), # Mocha
|
|
26
|
+
]
|
|
27
|
+
_NOISE = re.compile(r"^(failing tests:|tests? failed|\d+ failing)$", re.IGNORECASE)
|
|
28
|
+
MAX_FAILED_NAMES = 20
|
|
29
|
+
INSTALL_FAILED = "<install failed>"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def tool_env(run_dir: Path) -> dict[str, str]:
|
|
33
|
+
"""Environment for uv / Poetry / test runs: keep venvs and bytecode out of the worktree."""
|
|
34
|
+
env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"}
|
|
35
|
+
env["UV_PROJECT_ENVIRONMENT"] = str(run_dir / "venv")
|
|
36
|
+
env["POETRY_VIRTUALENVS_PATH"] = str(run_dir / "poetry-venvs")
|
|
37
|
+
env["POETRY_VIRTUALENVS_IN_PROJECT"] = "false"
|
|
38
|
+
env["POETRY_VIRTUALENVS_CREATE"] = "true"
|
|
39
|
+
env["POETRY_NO_INTERACTION"] = "1"
|
|
40
|
+
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
|
41
|
+
return env
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_NPM_PLACEHOLDER = "no test specified"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _js_runner(manager: str) -> str:
|
|
48
|
+
if manager != "yarn":
|
|
49
|
+
return manager
|
|
50
|
+
return "yarn" if shutil.which("yarn") else "corepack yarn"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def install_command(
|
|
54
|
+
cfg: ValidateConfig,
|
|
55
|
+
manager: Manager,
|
|
56
|
+
env: dict[str, str],
|
|
57
|
+
project_dir: Path | None = None,
|
|
58
|
+
workspace: bool = False,
|
|
59
|
+
) -> str:
|
|
60
|
+
"""The configured install command, else the manager's default for its version."""
|
|
61
|
+
if cfg.install:
|
|
62
|
+
return cfg.install
|
|
63
|
+
if manager == "uv" and workspace:
|
|
64
|
+
return "uv sync --frozen --all-packages"
|
|
65
|
+
if manager == "npm":
|
|
66
|
+
return "npm ci"
|
|
67
|
+
if manager == "pnpm":
|
|
68
|
+
return "pnpm install --frozen-lockfile"
|
|
69
|
+
if manager == "yarn":
|
|
70
|
+
lock = (project_dir or Path()) / "yarn.lock"
|
|
71
|
+
berry = lock.is_file() and is_berry(lock)
|
|
72
|
+
return f"{_js_runner('yarn')} install {'--immutable' if berry else '--frozen-lockfile'}"
|
|
73
|
+
if manager == "poetry":
|
|
74
|
+
return "poetry sync" if poetry_major(env) >= 2 else "poetry install --sync"
|
|
75
|
+
return cfg.install_command(manager)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _has_js_tests(project_dir: Path) -> bool:
|
|
79
|
+
if not (project_dir / "package.json").is_file():
|
|
80
|
+
return False
|
|
81
|
+
test = str((read_manifest(project_dir).get("scripts") or {}).get("test", ""))
|
|
82
|
+
return bool(test.strip()) and _NPM_PLACEHOLDER not in test
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_command(
|
|
86
|
+
cfg: ValidateConfig, manager: Manager, project_dir: Path, workspace: bool = False
|
|
87
|
+
) -> str | None:
|
|
88
|
+
"""The configured test command, else the manager's default; None = no tests."""
|
|
89
|
+
if manager not in JS_MANAGERS:
|
|
90
|
+
if manager == "uv" and workspace and cfg.test is None:
|
|
91
|
+
return "uv run --all-packages pytest -q"
|
|
92
|
+
return cfg.test_command(manager)
|
|
93
|
+
if cfg.test is not None:
|
|
94
|
+
return None if cfg.test.strip().lower() == NO_TESTS else cfg.test
|
|
95
|
+
if not _has_js_tests(project_dir):
|
|
96
|
+
return None # the project has no tests to run
|
|
97
|
+
return f"{_js_runner(manager)} test"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_commands(
|
|
101
|
+
cfg: ValidateConfig, manager: Manager, project_dir: Path, members: list[str] | None = None
|
|
102
|
+
) -> list[tuple[str, str]]:
|
|
103
|
+
"""(folder relative to the project, command) for each test run.
|
|
104
|
+
|
|
105
|
+
A workspace runs the root's ``test`` script when it has one; otherwise each member's.
|
|
106
|
+
"""
|
|
107
|
+
root = test_command(cfg, manager, project_dir, workspace=bool(members))
|
|
108
|
+
if root is not None or manager not in JS_MANAGERS or cfg.test is not None or not members:
|
|
109
|
+
return [("", root)] if root else []
|
|
110
|
+
runner = f"{_js_runner(manager)} test"
|
|
111
|
+
return [(m, runner) for m in members if _has_js_tests(project_dir / m)]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def failed_test_names(output: str) -> list[str]:
|
|
115
|
+
"""Failing test names from pytest, node --test, Jest, Vitest or Mocha output.
|
|
116
|
+
|
|
117
|
+
Only names are returned, never test output (it can hold secrets).
|
|
118
|
+
"""
|
|
119
|
+
clean = re.sub(r"\x1b\[[0-9;]*m", "", output) # colour codes
|
|
120
|
+
names: list[str] = []
|
|
121
|
+
for pattern in _FAILED_PATTERNS:
|
|
122
|
+
names += [n.strip() for n in pattern.findall(clean) if not _NOISE.match(n.strip())]
|
|
123
|
+
return list(dict.fromkeys(names))[:MAX_FAILED_NAMES]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class Validator:
|
|
127
|
+
def __init__(
|
|
128
|
+
self,
|
|
129
|
+
project_dir: Path,
|
|
130
|
+
cfg: ValidateConfig,
|
|
131
|
+
manager: Manager,
|
|
132
|
+
env: dict[str, str],
|
|
133
|
+
logs_dir: Path,
|
|
134
|
+
members: list[str] | None = None,
|
|
135
|
+
) -> None:
|
|
136
|
+
self.project_dir = project_dir
|
|
137
|
+
self.install_cmd = shlex.split(
|
|
138
|
+
install_command(cfg, manager, env, project_dir, workspace=bool(members))
|
|
139
|
+
)
|
|
140
|
+
self.tests = [
|
|
141
|
+
(where, shlex.split(cmd))
|
|
142
|
+
for where, cmd in test_commands(cfg, manager, project_dir, members)
|
|
143
|
+
]
|
|
144
|
+
self.timeout = cfg.timeout_minutes * 60
|
|
145
|
+
self.retries = cfg.retries
|
|
146
|
+
self.env = env
|
|
147
|
+
self.logs_dir = logs_dir
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def tests_enabled(self) -> bool:
|
|
151
|
+
return bool(self.tests)
|
|
152
|
+
|
|
153
|
+
def _exec(self, cmd: list[str], log: Path, where: str = "") -> tuple[bool, str]:
|
|
154
|
+
cwd = self.project_dir / where if where else self.project_dir
|
|
155
|
+
with log.open("a", encoding="utf-8") as fh:
|
|
156
|
+
fh.write(f"$ {f'(cd {where}) ' if where else ''}{shlex.join(cmd)}\n")
|
|
157
|
+
try:
|
|
158
|
+
result = proc.run(cmd, cwd=cwd, timeout=self.timeout, env=self.env)
|
|
159
|
+
except ToolNotFoundError:
|
|
160
|
+
fh.write(f"{cmd[0]}: not found\n")
|
|
161
|
+
return False, f"{cmd[0]}: not found"
|
|
162
|
+
except ToolTimeoutError:
|
|
163
|
+
fh.write(f"timed out after {self.timeout}s\n")
|
|
164
|
+
return False, f"timed out after {self.timeout // 60} min"
|
|
165
|
+
output = result.stdout + result.stderr
|
|
166
|
+
fh.write(output + f"\n[exit {result.returncode}]\n\n")
|
|
167
|
+
return result.ok, output
|
|
168
|
+
|
|
169
|
+
def _run_tests(self, where: str, cmd: list[str], log: Path) -> list[str]:
|
|
170
|
+
"""Failing test names (empty when the tests pass), retrying flaky runs."""
|
|
171
|
+
failed: list[str] = []
|
|
172
|
+
for _ in range(self.retries + 1):
|
|
173
|
+
ok, output = self._exec(cmd, log, where)
|
|
174
|
+
if ok:
|
|
175
|
+
return []
|
|
176
|
+
failed = failed_test_names(output) or ["<tests failed; see log>"]
|
|
177
|
+
return [f"{where}: {name}" for name in failed] if where else failed
|
|
178
|
+
|
|
179
|
+
def run(self, label: str) -> ValidationResult:
|
|
180
|
+
self.logs_dir.mkdir(parents=True, exist_ok=True)
|
|
181
|
+
log = self.logs_dir / f"{label}.log"
|
|
182
|
+
log.unlink(missing_ok=True)
|
|
183
|
+
ok, _ = self._exec(self.install_cmd, log)
|
|
184
|
+
if not ok:
|
|
185
|
+
return ValidationResult(
|
|
186
|
+
ran=self.tests_enabled,
|
|
187
|
+
passed=False,
|
|
188
|
+
failed_tests=[INSTALL_FAILED],
|
|
189
|
+
log_path=str(log),
|
|
190
|
+
)
|
|
191
|
+
if not self.tests:
|
|
192
|
+
return ValidationResult(ran=False, passed=True, log_path=str(log))
|
|
193
|
+
failed: list[str] = []
|
|
194
|
+
for where, cmd in self.tests:
|
|
195
|
+
failed += self._run_tests(where, cmd, log)
|
|
196
|
+
return ValidationResult(
|
|
197
|
+
ran=True, passed=not failed, failed_tests=failed[:MAX_FAILED_NAMES], log_path=str(log)
|
|
198
|
+
)
|
patchloop/versions.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Version helpers shared by the planner and the specifier editor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
|
|
7
|
+
from packaging.version import InvalidVersion, Version
|
|
8
|
+
|
|
9
|
+
from patchloop.models import Finding, VersionRange
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse(text: str) -> Version | None:
|
|
13
|
+
try:
|
|
14
|
+
return Version(text)
|
|
15
|
+
except InvalidVersion:
|
|
16
|
+
return None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def major(text: str) -> int | None:
|
|
20
|
+
v = parse(text)
|
|
21
|
+
return v.major if v else None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_CALVER_FIRST_YEAR = 1990
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def is_major_upgrade(current: str, candidate: str) -> bool:
|
|
28
|
+
"""Does going from ``current`` to ``candidate`` cross a major version?
|
|
29
|
+
|
|
30
|
+
Calendar-versioned packages (certifi 2025.11.12 -> 2026.10.18, pytz, tzdata) put the
|
|
31
|
+
year first; a new year is a routine release there, not a breaking one.
|
|
32
|
+
"""
|
|
33
|
+
a, b = major(current), major(candidate)
|
|
34
|
+
if a is None or b is None or a == b:
|
|
35
|
+
return False
|
|
36
|
+
return not (a >= _CALVER_FIRST_YEAR and b >= _CALVER_FIRST_YEAR)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def sort_versions(versions: Iterable[str]) -> list[str]:
|
|
40
|
+
parsed = [(pv, v) for v in set(versions) if (pv := parse(v)) is not None]
|
|
41
|
+
return [v for _, v in sorted(parsed)]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def in_range(version: Version, rng: VersionRange) -> bool:
|
|
45
|
+
lo = parse(rng.introduced) if rng.introduced not in ("", "0") else None
|
|
46
|
+
if lo is not None and version < lo:
|
|
47
|
+
return False
|
|
48
|
+
if rng.fixed is not None:
|
|
49
|
+
hi = parse(rng.fixed)
|
|
50
|
+
return hi is None or version < hi
|
|
51
|
+
if rng.last_affected is not None:
|
|
52
|
+
last = parse(rng.last_affected)
|
|
53
|
+
return last is None or version <= last
|
|
54
|
+
return True
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_affected(version: str, finding: Finding) -> bool:
|
|
58
|
+
"""Is ``version`` still affected by this finding's advisory?
|
|
59
|
+
|
|
60
|
+
Uses the advisory's ranges when known. Otherwise (e.g. an imported file with only a
|
|
61
|
+
fixed version) anything below the lowest known fixed version counts as affected.
|
|
62
|
+
"""
|
|
63
|
+
v = parse(version)
|
|
64
|
+
if v is None:
|
|
65
|
+
return True
|
|
66
|
+
if finding.affected_ranges:
|
|
67
|
+
return any(in_range(v, r) for r in finding.affected_ranges)
|
|
68
|
+
if not finding.fixed_versions:
|
|
69
|
+
return True
|
|
70
|
+
lowest = parse(finding.fixed_versions[0])
|
|
71
|
+
return lowest is None or v < lowest
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def bump_at(version: str, components: int) -> str:
|
|
75
|
+
"""Smallest version above ``version`` at a given granularity: (2.32.4, 2) -> 2.33."""
|
|
76
|
+
v = parse(version)
|
|
77
|
+
if v is None:
|
|
78
|
+
raise ValueError(f"not a version: {version}")
|
|
79
|
+
parts = [*v.release, 0, 0, 0][: max(components, 1)]
|
|
80
|
+
parts[-1] += 1
|
|
81
|
+
return ".".join(str(p) for p in parts)
|
patchloop/workspaces.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Workspaces (several projects sharing one lockfile at the root) and finding projects.
|
|
2
|
+
|
|
3
|
+
npm and yarn list members under ``workspaces`` in package.json, pnpm in
|
|
4
|
+
pnpm-workspace.yaml, uv under ``[tool.uv.workspace]`` in pyproject.toml. Each entry is a
|
|
5
|
+
glob of folders; ``!`` (JavaScript) or ``exclude`` (uv) leaves folders out.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import fnmatch
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import tomllib
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import yaml
|
|
18
|
+
|
|
19
|
+
SKIP_DIRS = {
|
|
20
|
+
"node_modules", ".git", ".venv", "venv", "__pycache__", ".tox", ".yarn", ".next",
|
|
21
|
+
"dist", "build", ".turbo", ".pnpm-store",
|
|
22
|
+
} # fmt: skip
|
|
23
|
+
JS_LOCKFILES = ("pnpm-lock.yaml", "yarn.lock", "package-lock.json")
|
|
24
|
+
PY_LOCKFILES = ("uv.lock", "poetry.lock")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _clean(pattern: str) -> str:
|
|
28
|
+
return pattern.strip().removeprefix("./").rstrip("/")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _braces(pattern: str) -> list[str]:
|
|
32
|
+
"""``packages/{a,b}`` -> ``packages/a``, ``packages/b`` (Python's glob has no braces)."""
|
|
33
|
+
m = re.search(r"\{([^{}]*)\}", pattern)
|
|
34
|
+
if not m:
|
|
35
|
+
return [pattern]
|
|
36
|
+
head, tail = pattern[: m.start()], pattern[m.end() :]
|
|
37
|
+
return [p for alt in m.group(1).split(",") for p in _braces(head + alt + tail)]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def expand(
|
|
41
|
+
root: Path, patterns: list[str], manifest: str, exclude: list[str] | None = None
|
|
42
|
+
) -> list[str]:
|
|
43
|
+
"""Member folders (relative, posix) matching ``patterns`` that hold ``manifest``."""
|
|
44
|
+
include = [_clean(x) for p in patterns if not p.strip().startswith("!") for x in _braces(p)]
|
|
45
|
+
skip = [_clean(x) for p in patterns if p.strip().startswith("!") for x in _braces(p[1:])]
|
|
46
|
+
skip += [_clean(x) for p in exclude or [] for x in _braces(p)]
|
|
47
|
+
found: set[str] = set()
|
|
48
|
+
for pattern in include:
|
|
49
|
+
if pattern in ("", ".") or pattern.startswith(("/", "..")):
|
|
50
|
+
continue # "." is the root itself, which is always included
|
|
51
|
+
for d in root.glob(pattern):
|
|
52
|
+
rel = d.relative_to(root)
|
|
53
|
+
if not d.is_dir() or not (d / manifest).is_file() or not rel.parts:
|
|
54
|
+
continue
|
|
55
|
+
if any(p in SKIP_DIRS for p in rel.parts):
|
|
56
|
+
continue
|
|
57
|
+
found.add(rel.as_posix())
|
|
58
|
+
return sorted(r for r in found if not any(fnmatch.fnmatch(r, s) for s in skip))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def js_patterns(root: Path, manifest: dict[str, Any]) -> list[str] | None:
|
|
62
|
+
"""Member globs of a JavaScript workspace, or None when ``root`` is not one."""
|
|
63
|
+
workspaces = manifest.get("workspaces")
|
|
64
|
+
if isinstance(workspaces, dict):
|
|
65
|
+
workspaces = workspaces.get("packages")
|
|
66
|
+
if isinstance(workspaces, list) and workspaces:
|
|
67
|
+
return [str(p) for p in workspaces]
|
|
68
|
+
pnpm = root / "pnpm-workspace.yaml"
|
|
69
|
+
if pnpm.is_file():
|
|
70
|
+
data = yaml.safe_load(pnpm.read_text("utf-8")) or {}
|
|
71
|
+
packages = data.get("packages") if isinstance(data, dict) else None
|
|
72
|
+
if isinstance(packages, list) and packages:
|
|
73
|
+
return [str(p) for p in packages]
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def uv_patterns(pyproject: dict[str, Any]) -> tuple[list[str], list[str]] | None:
|
|
78
|
+
"""(members, exclude) of a uv workspace, or None."""
|
|
79
|
+
ws = pyproject.get("tool", {}).get("uv", {}).get("workspace")
|
|
80
|
+
if not isinstance(ws, dict):
|
|
81
|
+
return None
|
|
82
|
+
return [str(m) for m in ws.get("members") or []], [str(e) for e in ws.get("exclude") or []]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_project(d: Path) -> bool:
|
|
86
|
+
if (d / "pyproject.toml").is_file() and any((d / f).is_file() for f in PY_LOCKFILES):
|
|
87
|
+
return True
|
|
88
|
+
return (d / "package.json").is_file() and any((d / f).is_file() for f in JS_LOCKFILES)
|
|
89
|
+
|
|
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."""
|
|
93
|
+
out: list[str] = []
|
|
94
|
+
|
|
95
|
+
def walk(d: Path, depth: int) -> None:
|
|
96
|
+
if depth > max_depth:
|
|
97
|
+
return
|
|
98
|
+
try:
|
|
99
|
+
children = sorted(c for c in d.iterdir() if c.is_dir())
|
|
100
|
+
except OSError:
|
|
101
|
+
return
|
|
102
|
+
for c in children:
|
|
103
|
+
if c.name in SKIP_DIRS or c.name.startswith("."):
|
|
104
|
+
continue
|
|
105
|
+
if is_project(c):
|
|
106
|
+
out.append(c.relative_to(root).as_posix())
|
|
107
|
+
continue # a workspace's members are part of it
|
|
108
|
+
walk(c, depth + 1)
|
|
109
|
+
|
|
110
|
+
walk(root, 1)
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def enclosing_workspace(d: Path) -> Path | None:
|
|
115
|
+
"""The workspace root above ``d`` whose members include ``d``, if any."""
|
|
116
|
+
d = d.resolve()
|
|
117
|
+
for parent in d.parents:
|
|
118
|
+
if (parent / "package.json").is_file() and any(
|
|
119
|
+
(parent / f).is_file() for f in JS_LOCKFILES
|
|
120
|
+
):
|
|
121
|
+
try:
|
|
122
|
+
manifest = json.loads((parent / "package.json").read_text("utf-8"))
|
|
123
|
+
except json.JSONDecodeError:
|
|
124
|
+
return None
|
|
125
|
+
patterns = js_patterns(parent, manifest)
|
|
126
|
+
if patterns and d.relative_to(parent).as_posix() in expand(
|
|
127
|
+
parent, patterns, "package.json"
|
|
128
|
+
):
|
|
129
|
+
return parent
|
|
130
|
+
if (parent / "pyproject.toml").is_file() and (parent / "uv.lock").is_file():
|
|
131
|
+
try:
|
|
132
|
+
pyproject = tomllib.loads((parent / "pyproject.toml").read_text("utf-8"))
|
|
133
|
+
except tomllib.TOMLDecodeError:
|
|
134
|
+
return None
|
|
135
|
+
uv = uv_patterns(pyproject)
|
|
136
|
+
if uv and d.relative_to(parent).as_posix() in expand(
|
|
137
|
+
parent, uv[0], "pyproject.toml", uv[1]
|
|
138
|
+
):
|
|
139
|
+
return parent
|
|
140
|
+
if (parent / ".git").exists():
|
|
141
|
+
return None
|
|
142
|
+
return None
|