|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Verify declared workaround removal conditions against lockfiles. |
| 3 | +
|
| 4 | +Checks `.github/workarounds.toml` against `uv.lock`, `Cargo.lock`, |
| 5 | +`package-lock.json`, and `pnpm-lock.yaml`. |
| 6 | +
|
| 7 | +Each entry in `.github/workarounds.toml` declares: |
| 8 | +- `id`: stable kebab-case identifier cited in the target source file |
| 9 | +- `path`: repository-relative code path containing the workaround |
| 10 | +- `owner`: upstream package or external tool that owns the root cause |
| 11 | +- `issue`: pinned upstream issue, pull request, commit, or specification URL |
| 12 | +- `remove_when` (optional only when `issue_only = true` for a non-lockfile tool): |
| 13 | + `"<ecosystem>:<package>>=<version>"` where `<ecosystem>` is `pypi`, `cargo`, |
| 14 | + or `npm`. The check fails once every locked copy of `<package>` meets or |
| 15 | + exceeds `<version>`, proving the workaround is ready to delete. |
| 16 | +
|
| 17 | +Examples |
| 18 | +-------- |
| 19 | +>>> sample_toml = ''' |
| 20 | +... [[workaround]] |
| 21 | +... id = "vcspull-daemon-url-schemes" |
| 22 | +... path = "src/vcspull/validator.py" |
| 23 | +... owner = "libvcs" |
| 24 | +... issue = "https://github.com/vcs-python/libvcs/issues/546" |
| 25 | +... remove_when = "pypi:libvcs>=0.49.0" |
| 26 | +... ''' |
| 27 | +>>> locks = {"pypi": {"libvcs": "0.48.0"}, "cargo": {}, "npm": {}} |
| 28 | +>>> check_entries( |
| 29 | +... parse_workarounds(sample_toml), |
| 30 | +... locks, |
| 31 | +... existing_paths={"src/vcspull/validator.py"}, |
| 32 | +... ) |
| 33 | +[] |
| 34 | +>>> version_key("0.49.0-rc.1") < version_key("0.49.0") < version_key("0.49.1a1") |
| 35 | +True |
| 36 | +>>> version_key("0.49") == version_key("0.49.0") |
| 37 | +True |
| 38 | +>>> locks_bumped = {"pypi": {"libvcs": "0.49.0"}, "cargo": {}, "npm": {}} |
| 39 | +>>> [ |
| 40 | +... e["reason"] |
| 41 | +... for e in check_entries( |
| 42 | +... parse_workarounds(sample_toml), |
| 43 | +... locks_bumped, |
| 44 | +... existing_paths={"src/vcspull/validator.py"}, |
| 45 | +... ) |
| 46 | +... ] |
| 47 | +['condition met (pypi:libvcs is 0.49.0 >= 0.49.0); remove workaround'] |
| 48 | +""" |
| 49 | + |
| 50 | +from __future__ import annotations |
| 51 | + |
| 52 | +import json |
| 53 | +import pathlib |
| 54 | +import re |
| 55 | +import sys |
| 56 | +import tomllib |
| 57 | + |
| 58 | +COND_RE = re.compile(r"^(pypi|cargo|npm):([A-Za-z0-9_./@-]+)>=([0-9][0-9A-Za-z._-]*)$") |
| 59 | +DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") |
| 60 | +ISSUE_URL_RE = re.compile(r"^https://[^/\s]+/[^/\s]+/\S+$") |
| 61 | +PRE_SEG_RE = re.compile(r"^(\d+)([A-Za-z]+)(\d*)$") |
| 62 | +EXACT_VER_RE = re.compile(r"^\d+(?:\.\d+)*(?:[-.][0-9A-Za-z.-]+)?$") |
| 63 | +PNPM_PKG_RE = re.compile( |
| 64 | + r"""(?m)^\s{2,4}['"]?/?(@?[^'"@\s:]+)@(\d[^'"(\s:]*)(?:\([^)]*\))*['"]?:""" |
| 65 | +) |
| 66 | +DOC_SUFFIXES = {".md", ".rst", ".txt", ".adoc"} |
| 67 | + |
| 68 | + |
| 69 | +def normalize_pkg(eco: str, name: str) -> str: |
| 70 | + """Normalize package names per ecosystem rules (PEP 503 for PyPI).""" |
| 71 | + if eco == "pypi": |
| 72 | + return re.sub(r"[-_.]+", "-", name).lower() |
| 73 | + if eco == "cargo": |
| 74 | + return name.lower() |
| 75 | + return name |
| 76 | + |
| 77 | + |
| 78 | +def _tag_stage(tag: str) -> int: |
| 79 | + if tag.startswith("post"): |
| 80 | + return 1 |
| 81 | + if tag.startswith("dev"): |
| 82 | + return -4 |
| 83 | + if tag in {"a", "alpha"}: |
| 84 | + return -3 |
| 85 | + if tag in {"b", "beta"}: |
| 86 | + return -2 |
| 87 | + return -1 |
| 88 | + |
| 89 | + |
| 90 | +def version_key( |
| 91 | + ver: str, |
| 92 | +) -> tuple[tuple[int, ...], int, tuple[tuple[int, int, str], ...]]: |
| 93 | + """Order dev < alpha < beta < rc < final < post releases.""" |
| 94 | + base = ver.split("+", 1)[0] |
| 95 | + nums: list[int] = [] |
| 96 | + tail: list[tuple[int, int, str]] = [] |
| 97 | + stage = 0 |
| 98 | + in_tail = False |
| 99 | + for tok in re.split(r"[.-]", base): |
| 100 | + if not tok: |
| 101 | + continue |
| 102 | + if not in_tail and tok.isdigit(): |
| 103 | + nums.append(int(tok)) |
| 104 | + continue |
| 105 | + m = PRE_SEG_RE.match(tok) if not in_tail else None |
| 106 | + if m: |
| 107 | + nums.append(int(m.group(1))) |
| 108 | + tag = m.group(2).lower() |
| 109 | + in_tail = True |
| 110 | + stage = _tag_stage(tag) |
| 111 | + tail.append((0, 0, tag)) |
| 112 | + if m.group(3): |
| 113 | + tail.append((1, int(m.group(3)), "")) |
| 114 | + continue |
| 115 | + low = tok.lower() |
| 116 | + if not in_tail: |
| 117 | + m2 = re.match(r"^([a-z]+)(\d+)$", low) |
| 118 | + if m2: |
| 119 | + stage = _tag_stage(m2.group(1)) |
| 120 | + in_tail = True |
| 121 | + tail.append((0, 0, m2.group(1))) |
| 122 | + tail.append((1, int(m2.group(2)), "")) |
| 123 | + continue |
| 124 | + stage = _tag_stage(low) |
| 125 | + in_tail = True |
| 126 | + tail.append((1, int(tok), "") if tok.isdigit() else (0, 0, low)) |
| 127 | + while len(nums) > 1 and nums[-1] == 0: |
| 128 | + nums.pop() |
| 129 | + return (tuple(nums), stage, tuple(tail)) |
| 130 | + |
| 131 | + |
| 132 | +def _record_min(bucket: dict[str, str], name: str, ver: str) -> None: |
| 133 | + prev = bucket.get(name) |
| 134 | + if prev is None or version_key(ver) < version_key(prev): |
| 135 | + bucket[name] = ver |
| 136 | + |
| 137 | + |
| 138 | +def parse_workarounds(toml_text: str) -> list[dict[str, object]]: |
| 139 | + """Parse ``[[workaround]]`` tables from TOML text.""" |
| 140 | + data = tomllib.loads(toml_text) |
| 141 | + raw = data.get("workaround", []) |
| 142 | + if not isinstance(raw, list): |
| 143 | + msg = "'workaround' must be an array of tables" |
| 144 | + raise TypeError(msg) |
| 145 | + return [dict(item) for item in raw if isinstance(item, dict)] |
| 146 | + |
| 147 | + |
| 148 | +def load_locks(repo_root: pathlib.Path) -> dict[str, dict[str, str]]: |
| 149 | + """Read minimum locked versions from uv, Cargo, pnpm, or npm lockfiles.""" |
| 150 | + locks: dict[str, dict[str, str]] = {"pypi": {}, "cargo": {}, "npm": {}} |
| 151 | + uv_lock = repo_root / "uv.lock" |
| 152 | + if uv_lock.is_file(): |
| 153 | + data = tomllib.loads(uv_lock.read_text(encoding="utf-8")) |
| 154 | + for pkg in data.get("package", []): |
| 155 | + if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: |
| 156 | + _record_min( |
| 157 | + locks["pypi"], |
| 158 | + normalize_pkg("pypi", str(pkg["name"])), |
| 159 | + str(pkg["version"]), |
| 160 | + ) |
| 161 | + cargo_lock = repo_root / "Cargo.lock" |
| 162 | + if cargo_lock.is_file(): |
| 163 | + data = tomllib.loads(cargo_lock.read_text(encoding="utf-8")) |
| 164 | + for pkg in data.get("package", []): |
| 165 | + if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: |
| 166 | + _record_min( |
| 167 | + locks["cargo"], |
| 168 | + normalize_pkg("cargo", str(pkg["name"])), |
| 169 | + str(pkg["version"]), |
| 170 | + ) |
| 171 | + pnpm_lock = repo_root / "pnpm-lock.yaml" |
| 172 | + npm_lock = repo_root / "package-lock.json" |
| 173 | + if pnpm_lock.is_file(): |
| 174 | + for m in PNPM_PKG_RE.finditer(pnpm_lock.read_text(encoding="utf-8")): |
| 175 | + _record_min(locks["npm"], m.group(1), m.group(2)) |
| 176 | + elif npm_lock.is_file(): |
| 177 | + ndata = json.loads(npm_lock.read_text(encoding="utf-8")) |
| 178 | + pkgs = ndata.get("packages", {}) |
| 179 | + if isinstance(pkgs, dict): |
| 180 | + for k, info in pkgs.items(): |
| 181 | + if ( |
| 182 | + k.startswith("node_modules/") |
| 183 | + and isinstance(info, dict) |
| 184 | + and "version" in info |
| 185 | + ): |
| 186 | + pkg_name = k.rsplit("node_modules/", 1)[-1] |
| 187 | + _record_min(locks["npm"], pkg_name, str(info["version"])) |
| 188 | + else: |
| 189 | + pkg_json = repo_root / "package.json" |
| 190 | + if pkg_json.is_file(): |
| 191 | + pdata = json.loads(pkg_json.read_text(encoding="utf-8")) |
| 192 | + for section in ("dependencies", "devDependencies"): |
| 193 | + deps = pdata.get(section, {}) |
| 194 | + if isinstance(deps, dict): |
| 195 | + for name, spec in deps.items(): |
| 196 | + spec_s = str(spec).strip() |
| 197 | + if EXACT_VER_RE.match(spec_s): |
| 198 | + _record_min(locks["npm"], str(name), spec_s) |
| 199 | + return locks |
| 200 | + |
| 201 | + |
| 202 | +def check_entries( |
| 203 | + entries: list[dict[str, object]], |
| 204 | + locks: dict[str, dict[str, str]], |
| 205 | + existing_paths: set[str] | None = None, |
| 206 | + file_texts: dict[str, str] | None = None, |
| 207 | +) -> list[dict[str, str]]: |
| 208 | + """Return violations for missing fields, decoy paths, or met predicates.""" |
| 209 | + problems: list[dict[str, str]] = [] |
| 210 | + for entry in entries: |
| 211 | + wid = str(entry.get("id") or "<unnamed>") |
| 212 | + rel_path = str(entry.get("path") or "") |
| 213 | + owner = str(entry.get("owner") or "") |
| 214 | + issue = str(entry.get("issue") or "") |
| 215 | + cond = str(entry.get("remove_when") or "") |
| 216 | + if not rel_path or not owner or not ISSUE_URL_RE.match(issue): |
| 217 | + problems.append( |
| 218 | + { |
| 219 | + "id": wid, |
| 220 | + "reason": ( |
| 221 | + "requires path, owner, and full " |
| 222 | + "https://<host>/<org>/<ref> issue URL" |
| 223 | + ), |
| 224 | + } |
| 225 | + ) |
| 226 | + continue |
| 227 | + if ( |
| 228 | + pathlib.Path(rel_path).suffix.lower() in DOC_SUFFIXES |
| 229 | + and entry.get("allow_doc_path") is not True |
| 230 | + ): |
| 231 | + problems.append( |
| 232 | + { |
| 233 | + "id": wid, |
| 234 | + "reason": ( |
| 235 | + f"path '{rel_path}' points to documentation " |
| 236 | + "rather than source code" |
| 237 | + ), |
| 238 | + } |
| 239 | + ) |
| 240 | + continue |
| 241 | + if existing_paths is not None and rel_path not in existing_paths: |
| 242 | + problems.append( |
| 243 | + { |
| 244 | + "id": wid, |
| 245 | + "reason": ( |
| 246 | + f"path '{rel_path}' does not exist as a regular " |
| 247 | + "file inside repository" |
| 248 | + ), |
| 249 | + } |
| 250 | + ) |
| 251 | + continue |
| 252 | + if file_texts is not None and rel_path in file_texts: |
| 253 | + src_txt = file_texts[rel_path] |
| 254 | + if wid not in src_txt and issue not in src_txt: |
| 255 | + problems.append( |
| 256 | + { |
| 257 | + "id": wid, |
| 258 | + "reason": ( |
| 259 | + f"path '{rel_path}' contains neither " |
| 260 | + f"workaround id '{wid}' nor issue URL" |
| 261 | + ), |
| 262 | + } |
| 263 | + ) |
| 264 | + continue |
| 265 | + if DATE_ONLY_RE.match(cond): |
| 266 | + problems.append( |
| 267 | + { |
| 268 | + "id": wid, |
| 269 | + "reason": ( |
| 270 | + "calendar dates are not allowed in remove_when; " |
| 271 | + "use a lockfile predicate or issue_only = true" |
| 272 | + ), |
| 273 | + } |
| 274 | + ) |
| 275 | + continue |
| 276 | + if not cond: |
| 277 | + in_locks = any( |
| 278 | + normalize_pkg(eco, owner) in locks.get(eco, {}) |
| 279 | + for eco in ("pypi", "cargo", "npm") |
| 280 | + ) |
| 281 | + if in_locks: |
| 282 | + problems.append( |
| 283 | + { |
| 284 | + "id": wid, |
| 285 | + "reason": ( |
| 286 | + f"owner '{owner}' is present in lockfiles; " |
| 287 | + "specify remove_when instead of issue_only" |
| 288 | + ), |
| 289 | + } |
| 290 | + ) |
| 291 | + continue |
| 292 | + if ( |
| 293 | + entry.get("issue_only") is True |
| 294 | + and str(entry.get("reason_no_lock") or "").strip() |
| 295 | + ): |
| 296 | + continue |
| 297 | + problems.append( |
| 298 | + { |
| 299 | + "id": wid, |
| 300 | + "reason": ( |
| 301 | + "missing remove_when (or issue_only = true with reason_no_lock)" |
| 302 | + ), |
| 303 | + } |
| 304 | + ) |
| 305 | + continue |
| 306 | + m = COND_RE.match(cond) |
| 307 | + if not m: |
| 308 | + problems.append( |
| 309 | + { |
| 310 | + "id": wid, |
| 311 | + "reason": ( |
| 312 | + f"invalid remove_when '{cond}'; " |
| 313 | + "expected '<pypi|cargo|npm>:<pkg>>=<version>'" |
| 314 | + ), |
| 315 | + } |
| 316 | + ) |
| 317 | + continue |
| 318 | + eco, pkg, target = m.group(1), m.group(2), m.group(3) |
| 319 | + norm_pkg = normalize_pkg(eco, pkg) |
| 320 | + locked = locks.get(eco, {}).get(norm_pkg) |
| 321 | + if locked is None: |
| 322 | + problems.append( |
| 323 | + { |
| 324 | + "id": wid, |
| 325 | + "reason": f"package '{pkg}' not found in {eco} lockfile", |
| 326 | + } |
| 327 | + ) |
| 328 | + continue |
| 329 | + if version_key(locked) >= version_key(target): |
| 330 | + problems.append( |
| 331 | + { |
| 332 | + "id": wid, |
| 333 | + "reason": ( |
| 334 | + f"condition met ({eco}:{pkg} is {locked} >= {target}); " |
| 335 | + "remove workaround" |
| 336 | + ), |
| 337 | + } |
| 338 | + ) |
| 339 | + return problems |
| 340 | + |
| 341 | + |
| 342 | +def main(argv: list[str] | None = None) -> int: |
| 343 | + """Run the CLI check against the repository root and manifest path.""" |
| 344 | + args = argv if argv is not None else sys.argv[1:] |
| 345 | + repo = pathlib.Path(args[0]).resolve() if args else pathlib.Path.cwd().resolve() |
| 346 | + manifest = ( |
| 347 | + pathlib.Path(args[1]).resolve() |
| 348 | + if len(args) > 1 |
| 349 | + else repo / ".github" / "workarounds.toml" |
| 350 | + ) |
| 351 | + if not manifest.is_file(): |
| 352 | + sys.stdout.write(f"{json.dumps({'ok': True, 'checked': 0, 'problems': []})}\n") |
| 353 | + return 0 |
| 354 | + entries = parse_workarounds(manifest.read_text(encoding="utf-8")) |
| 355 | + existing: set[str] = set() |
| 356 | + texts: dict[str, str] = {} |
| 357 | + for entry in entries: |
| 358 | + raw_p = str(entry.get("path") or "") |
| 359 | + if not raw_p: |
| 360 | + continue |
| 361 | + cand = (repo / raw_p).resolve() |
| 362 | + if cand.is_relative_to(repo) and cand.is_file(): |
| 363 | + existing.add(raw_p) |
| 364 | + texts[raw_p] = cand.read_text(encoding="utf-8", errors="replace") |
| 365 | + problems = check_entries( |
| 366 | + entries, |
| 367 | + load_locks(repo), |
| 368 | + existing_paths=existing, |
| 369 | + file_texts=texts, |
| 370 | + ) |
| 371 | + payload = {"ok": not problems, "checked": len(entries), "problems": problems} |
| 372 | + sys.stdout.write(f"{json.dumps(payload)}\n") |
| 373 | + return 0 if not problems else 1 |
| 374 | + |
| 375 | + |
| 376 | +if __name__ == "__main__": |
| 377 | + raise SystemExit(main()) |
0 commit comments