diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 7ec6b678..4a4ee363 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -77,7 +77,28 @@ one mistake that silently removes a test, are in [WRITING.md](WRITING.md#documented-examples-that-run). Use the [test bite gate](../REVIEW.md#4-test-bite) to prove a regression -fails for the reason it claims to catch. +fails for the reason it claims to catch. For bug fixes and behavioral +changes, verify new or updated `pytest` regressions fail inside the real +owner call when modified production files are restored to `` and +newly added production files are removed temporarily: + +```console +$ mapfile -t mod_py < <( + git diff --name-only -M --diff-filter=MDR ..HEAD -- '*.py' | + rg -v '(^|/)tests?/|(^|/)conftest\.py$|(^|/)test_[^/]*\.py$|_test\.py$' + ) && + mapfile -t add_py < <( + git diff --name-only -M --diff-filter=A ..HEAD -- '*.py' | + rg -v '(^|/)tests?/|(^|/)conftest\.py$|(^|/)test_[^/]*\.py$|_test\.py$' + ) && + test $(( ${#mod_py[@]} + ${#add_py[@]} )) -gt 0 && + { [ "${#mod_py[@]}" -eq 0 ] || + git restore --source= --worktree -- "${mod_py[@]}"; } && + { [ "${#add_py[@]}" -eq 0 ] || rm -f -- "${add_py[@]}"; } && + ! uv run pytest -x && + git restore --source=HEAD --worktree -- "${mod_py[@]}" "${add_py[@]}" && + uv run pytest +``` ### Clean-room provenance diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..b224b7b2 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,26 @@ + + +Closes # + +### 1. Owner and boundary + +- Rule changed and module that owns it: +- Sibling entry points checked (`sync`/`async`, CLI/API, single/batch, or `N/A`): +- Why this belongs here (owner fix, boundary adapter, or single-PR ownership transfer): + +### 2. Failure before the fix (`N/A` for docs, lockfile bumps, or pure refactors) + +- Baseline (`` commit, or `` SHA if fixing a defect introduced in this PR): +- Failing input or command and observed failure before the fix: + +### 3. Verification and tool disclosure + +- Gates run (plus production-only revert check for behavioral fixes, or `N/A`): +- `.github/workarounds.toml` updates (`None` if none): +- Tool use: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b0ef49c0..90caf1ff 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -35,6 +35,8 @@ jobs: run: uv run ruff format --check . - name: Check types with ty run: uv run ty check --python-version ${{ matrix.python-version }} --output-format github + - name: Check declared workarounds + run: PYTHONDONTWRITEBYTECODE=1 uv run python -B scripts/check_workarounds.py - name: Tests (pytest) if: matrix.python-version != '3.14' run: uv run pytest -m "" diff --git a/pyproject.toml b/pyproject.toml index b8f9441e..f6b83898 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -218,6 +218,8 @@ extend-select = [ "PT", # flake8-pytest-style "RET", # flake8-return "FURB", # refurb + "PGH003", # specific type-ignore codes + "PGH004", # specific noqa codes ] ignore = [ "COM812", # missing trailing comma, ruff format conflict diff --git a/scripts/check_workarounds.py b/scripts/check_workarounds.py new file mode 100755 index 00000000..f7cdd148 --- /dev/null +++ b/scripts/check_workarounds.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Verify declared workaround removal conditions against lockfiles. + +Checks `.github/workarounds.toml` against `uv.lock`, `Cargo.lock`, +`package-lock.json`, and `pnpm-lock.yaml`. + +Each entry in `.github/workarounds.toml` declares: +- `id`: stable kebab-case identifier cited in the target source file +- `path`: repository-relative code path containing the workaround +- `owner`: upstream package or external tool that owns the root cause +- `issue`: pinned upstream issue, pull request, commit, or specification URL +- `remove_when` (optional only when `issue_only = true` for a non-lockfile tool): + `":>="` where `` is `pypi`, `cargo`, + or `npm`. The check fails once every locked copy of `` meets or + exceeds ``, proving the workaround is ready to delete. + +Examples +-------- +>>> sample_toml = ''' +... [[workaround]] +... id = "vcspull-daemon-url-schemes" +... path = "src/vcspull/validator.py" +... owner = "libvcs" +... issue = "https://github.com/vcs-python/libvcs/issues/546" +... remove_when = "pypi:libvcs>=0.49.0" +... ''' +>>> locks = {"pypi": {"libvcs": "0.48.0"}, "cargo": {}, "npm": {}} +>>> check_entries( +... parse_workarounds(sample_toml), +... locks, +... existing_paths={"src/vcspull/validator.py"}, +... ) +[] +>>> version_key("0.49.0-rc.1") < version_key("0.49.0") < version_key("0.49.1a1") +True +>>> version_key("0.49") == version_key("0.49.0") +True +>>> locks_bumped = {"pypi": {"libvcs": "0.49.0"}, "cargo": {}, "npm": {}} +>>> [ +... e["reason"] +... for e in check_entries( +... parse_workarounds(sample_toml), +... locks_bumped, +... existing_paths={"src/vcspull/validator.py"}, +... ) +... ] +['condition met (pypi:libvcs is 0.49.0 >= 0.49.0); remove workaround'] +""" + +from __future__ import annotations + +import json +import pathlib +import re +import sys +import tomllib + +COND_RE = re.compile(r"^(pypi|cargo|npm):([A-Za-z0-9_./@-]+)>=([0-9][0-9A-Za-z._-]*)$") +DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +ISSUE_URL_RE = re.compile(r"^https://[^/\s]+/[^/\s]+/\S+$") +PRE_SEG_RE = re.compile(r"^(\d+)([A-Za-z]+)(\d*)$") +EXACT_VER_RE = re.compile(r"^\d+(?:\.\d+)*(?:[-.][0-9A-Za-z.-]+)?$") +PNPM_PKG_RE = re.compile( + r"""(?m)^\s{2,4}['"]?/?(@?[^'"@\s:]+)@(\d[^'"(\s:]*)(?:\([^)]*\))*['"]?:""" +) +DOC_SUFFIXES = {".md", ".rst", ".txt", ".adoc"} + + +def normalize_pkg(eco: str, name: str) -> str: + """Normalize package names per ecosystem rules (PEP 503 for PyPI).""" + if eco == "pypi": + return re.sub(r"[-_.]+", "-", name).lower() + if eco == "cargo": + return name.lower() + return name + + +def _tag_stage(tag: str) -> int: + if tag.startswith("post"): + return 1 + if tag.startswith("dev"): + return -4 + if tag in {"a", "alpha"}: + return -3 + if tag in {"b", "beta"}: + return -2 + return -1 + + +def version_key( + ver: str, +) -> tuple[tuple[int, ...], int, tuple[tuple[int, int, str], ...]]: + """Order dev < alpha < beta < rc < final < post releases.""" + base = ver.split("+", 1)[0] + nums: list[int] = [] + tail: list[tuple[int, int, str]] = [] + stage = 0 + in_tail = False + for tok in re.split(r"[.-]", base): + if not tok: + continue + if not in_tail and tok.isdigit(): + nums.append(int(tok)) + continue + m = PRE_SEG_RE.match(tok) if not in_tail else None + if m: + nums.append(int(m.group(1))) + tag = m.group(2).lower() + in_tail = True + stage = _tag_stage(tag) + tail.append((0, 0, tag)) + if m.group(3): + tail.append((1, int(m.group(3)), "")) + continue + low = tok.lower() + if not in_tail: + m2 = re.match(r"^([a-z]+)(\d+)$", low) + if m2: + stage = _tag_stage(m2.group(1)) + in_tail = True + tail.append((0, 0, m2.group(1))) + tail.append((1, int(m2.group(2)), "")) + continue + stage = _tag_stage(low) + in_tail = True + tail.append((1, int(tok), "") if tok.isdigit() else (0, 0, low)) + while len(nums) > 1 and nums[-1] == 0: + nums.pop() + return (tuple(nums), stage, tuple(tail)) + + +def _record_min(bucket: dict[str, str], name: str, ver: str) -> None: + prev = bucket.get(name) + if prev is None or version_key(ver) < version_key(prev): + bucket[name] = ver + + +def parse_workarounds(toml_text: str) -> list[dict[str, object]]: + """Parse ``[[workaround]]`` tables from TOML text.""" + data = tomllib.loads(toml_text) + raw = data.get("workaround", []) + if not isinstance(raw, list): + msg = "'workaround' must be an array of tables" + raise TypeError(msg) + return [dict(item) for item in raw if isinstance(item, dict)] + + +def load_locks(repo_root: pathlib.Path) -> dict[str, dict[str, str]]: + """Read minimum locked versions from uv, Cargo, pnpm, or npm lockfiles.""" + locks: dict[str, dict[str, str]] = {"pypi": {}, "cargo": {}, "npm": {}} + uv_lock = repo_root / "uv.lock" + if uv_lock.is_file(): + data = tomllib.loads(uv_lock.read_text(encoding="utf-8")) + for pkg in data.get("package", []): + if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: + _record_min( + locks["pypi"], + normalize_pkg("pypi", str(pkg["name"])), + str(pkg["version"]), + ) + cargo_lock = repo_root / "Cargo.lock" + if cargo_lock.is_file(): + data = tomllib.loads(cargo_lock.read_text(encoding="utf-8")) + for pkg in data.get("package", []): + if isinstance(pkg, dict) and "name" in pkg and "version" in pkg: + _record_min( + locks["cargo"], + normalize_pkg("cargo", str(pkg["name"])), + str(pkg["version"]), + ) + pnpm_lock = repo_root / "pnpm-lock.yaml" + npm_lock = repo_root / "package-lock.json" + if pnpm_lock.is_file(): + for m in PNPM_PKG_RE.finditer(pnpm_lock.read_text(encoding="utf-8")): + _record_min(locks["npm"], m.group(1), m.group(2)) + elif npm_lock.is_file(): + ndata = json.loads(npm_lock.read_text(encoding="utf-8")) + pkgs = ndata.get("packages", {}) + if isinstance(pkgs, dict): + for k, info in pkgs.items(): + if ( + k.startswith("node_modules/") + and isinstance(info, dict) + and "version" in info + ): + pkg_name = k.rsplit("node_modules/", 1)[-1] + _record_min(locks["npm"], pkg_name, str(info["version"])) + else: + pkg_json = repo_root / "package.json" + if pkg_json.is_file(): + pdata = json.loads(pkg_json.read_text(encoding="utf-8")) + for section in ("dependencies", "devDependencies"): + deps = pdata.get(section, {}) + if isinstance(deps, dict): + for name, spec in deps.items(): + spec_s = str(spec).strip() + if EXACT_VER_RE.match(spec_s): + _record_min(locks["npm"], str(name), spec_s) + return locks + + +def check_entries( + entries: list[dict[str, object]], + locks: dict[str, dict[str, str]], + existing_paths: set[str] | None = None, + file_texts: dict[str, str] | None = None, +) -> list[dict[str, str]]: + """Return violations for missing fields, decoy paths, or met predicates.""" + problems: list[dict[str, str]] = [] + for entry in entries: + wid = str(entry.get("id") or "") + rel_path = str(entry.get("path") or "") + owner = str(entry.get("owner") or "") + issue = str(entry.get("issue") or "") + cond = str(entry.get("remove_when") or "") + if not rel_path or not owner or not ISSUE_URL_RE.match(issue): + problems.append( + { + "id": wid, + "reason": ( + "requires path, owner, and full " + "https://// issue URL" + ), + } + ) + continue + if ( + pathlib.Path(rel_path).suffix.lower() in DOC_SUFFIXES + and entry.get("allow_doc_path") is not True + ): + problems.append( + { + "id": wid, + "reason": ( + f"path '{rel_path}' points to documentation " + "rather than source code" + ), + } + ) + continue + if existing_paths is not None and rel_path not in existing_paths: + problems.append( + { + "id": wid, + "reason": ( + f"path '{rel_path}' does not exist as a regular " + "file inside repository" + ), + } + ) + continue + if file_texts is not None and rel_path in file_texts: + src_txt = file_texts[rel_path] + if wid not in src_txt and issue not in src_txt: + problems.append( + { + "id": wid, + "reason": ( + f"path '{rel_path}' contains neither " + f"workaround id '{wid}' nor issue URL" + ), + } + ) + continue + if DATE_ONLY_RE.match(cond): + problems.append( + { + "id": wid, + "reason": ( + "calendar dates are not allowed in remove_when; " + "use a lockfile predicate or issue_only = true" + ), + } + ) + continue + if not cond: + in_locks = any( + normalize_pkg(eco, owner) in locks.get(eco, {}) + for eco in ("pypi", "cargo", "npm") + ) + if in_locks: + problems.append( + { + "id": wid, + "reason": ( + f"owner '{owner}' is present in lockfiles; " + "specify remove_when instead of issue_only" + ), + } + ) + continue + if ( + entry.get("issue_only") is True + and str(entry.get("reason_no_lock") or "").strip() + ): + continue + problems.append( + { + "id": wid, + "reason": ( + "missing remove_when (or issue_only = true with reason_no_lock)" + ), + } + ) + continue + m = COND_RE.match(cond) + if not m: + problems.append( + { + "id": wid, + "reason": ( + f"invalid remove_when '{cond}'; " + "expected ':>='" + ), + } + ) + continue + eco, pkg, target = m.group(1), m.group(2), m.group(3) + norm_pkg = normalize_pkg(eco, pkg) + locked = locks.get(eco, {}).get(norm_pkg) + if locked is None: + problems.append( + { + "id": wid, + "reason": f"package '{pkg}' not found in {eco} lockfile", + } + ) + continue + if version_key(locked) >= version_key(target): + problems.append( + { + "id": wid, + "reason": ( + f"condition met ({eco}:{pkg} is {locked} >= {target}); " + "remove workaround" + ), + } + ) + return problems + + +def main(argv: list[str] | None = None) -> int: + """Run the CLI check against the repository root and manifest path.""" + args = argv if argv is not None else sys.argv[1:] + repo = pathlib.Path(args[0]).resolve() if args else pathlib.Path.cwd().resolve() + manifest = ( + pathlib.Path(args[1]).resolve() + if len(args) > 1 + else repo / ".github" / "workarounds.toml" + ) + if not manifest.is_file(): + sys.stdout.write(f"{json.dumps({'ok': True, 'checked': 0, 'problems': []})}\n") + return 0 + entries = parse_workarounds(manifest.read_text(encoding="utf-8")) + existing: set[str] = set() + texts: dict[str, str] = {} + for entry in entries: + raw_p = str(entry.get("path") or "") + if not raw_p: + continue + cand = (repo / raw_p).resolve() + if cand.is_relative_to(repo) and cand.is_file(): + existing.add(raw_p) + texts[raw_p] = cand.read_text(encoding="utf-8", errors="replace") + problems = check_entries( + entries, + load_locks(repo), + existing_paths=existing, + file_texts=texts, + ) + payload = {"ok": not problems, "checked": len(entries), "problems": problems} + sys.stdout.write(f"{json.dumps(payload)}\n") + return 0 if not problems else 1 + + +if __name__ == "__main__": + raise SystemExit(main())