diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e32213c..f486738 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -281,7 +281,7 @@ repos: # patch target statically so a stale path fails the commit instead. - id: patch-targets name: test patch targets resolve - entry: python3 scripts/check_patch_targets.py + entry: python3 scripts/check_patch_targets.py diet_guard language: system pass_filenames: false files: ^diet_guard/ diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 759ebc3..02924b2 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -2,7 +2,7 @@ name: diet_guard_app description: "Companion phone app for diet_guard: log meals on the go." publish_to: 'none' -version: 1.0.184+1 +version: 1.0.185+1 environment: sdk: ^3.12.2 diff --git a/diet_guard/tests/test_check_patch_targets_cli.py b/diet_guard/tests/test_check_patch_targets_cli.py new file mode 100644 index 0000000..7323d74 --- /dev/null +++ b/diet_guard/tests/test_check_patch_targets_cli.py @@ -0,0 +1,103 @@ +"""CLI contract of ``scripts/check_patch_targets.py``: the package is an argument. + +Other guard repos adopt the script by copying it into their own ``scripts/``, +so each case copies it into a scratch repo next to a scratch package and runs +it there as a subprocess -- the same shape an adopter gets. ``scripts/`` sits +outside coverage ``source``, so the subprocess run is the whole check. +""" + +from __future__ import annotations + +from pathlib import Path +import shutil +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts" / "check_patch_targets.py" + +GOOD = 'from unittest import mock\nmock.patch("pkg_a.mod.VALUE", 1)\n' +STALE = 'from unittest import mock\nmock.patch("pkg_a.mod.GONE", 1)\n' + + +def _run(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]: + """Run the script with ``args`` from ``cwd``, as the pre-commit hook does.""" + return subprocess.run( + [sys.executable, str(cwd / "scripts" / SCRIPT.name), *args], + cwd=cwd, + capture_output=True, + text=True, + check=False, + timeout=30, + ) + + +def _scratch_repo(tmp_path: Path, test_source: str, tests_dir: str) -> Path: + """A repo with ``scripts/``, package ``pkg_a`` and one test file.""" + (tmp_path / "scripts").mkdir() + shutil.copy(SCRIPT, tmp_path / "scripts" / SCRIPT.name) + pkg = tmp_path / "pkg_a" + pkg.mkdir() + (pkg / "__init__.py").write_text("") + (pkg / "mod.py").write_text("VALUE = 0\n") + tests = tmp_path / tests_dir + tests.mkdir(parents=True, exist_ok=True) + (tests / "test_x.py").write_text(test_source) + return tmp_path + + +def test_missing_package_argument_is_a_usage_error(tmp_path: Path) -> None: + """No silent default: a bare run fails loudly instead of checking nothing.""" + repo = _scratch_repo(tmp_path, GOOD, "pkg_a/tests") + result = _run(repo) + assert result.returncode == 2 + assert "usage:" in result.stderr + assert "package" in result.stderr + + +def test_good_target_in_named_package_passes(tmp_path: Path) -> None: + """A resolvable target in ``/tests`` exits 0 silently.""" + repo = _scratch_repo(tmp_path, GOOD, "pkg_a/tests") + result = _run(repo, "pkg_a") + assert (result.returncode, result.stderr) == (0, "") + + +def test_stale_target_in_named_package_fails(tmp_path: Path) -> None: + """A target that no longer resolves names its file and line, and exits 1.""" + repo = _scratch_repo(tmp_path, STALE, "pkg_a/tests") + result = _run(repo, "pkg_a") + assert result.returncode == 1 + assert ( + "pkg_a/tests/test_x.py:2: patch target does not resolve: pkg_a.mod.GONE" + in result.stderr + ) + + +def test_tests_root_override_is_the_directory_checked(tmp_path: Path) -> None: + """``--tests-root`` replaces ``/tests``, which may then not exist.""" + repo = _scratch_repo(tmp_path, STALE, "elsewhere") + assert _run(repo, "pkg_a").returncode == 1 # default root is missing + result = _run(repo, "pkg_a", "--tests-root", "elsewhere") + assert result.returncode == 1 + assert "elsewhere/test_x.py:2:" in result.stderr + + +def test_real_tree_passes_with_diet_guard_argument() -> None: + """The hook's own invocation is green on this repo.""" + result = subprocess.run( + [sys.executable, str(SCRIPT), "diet_guard"], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + timeout=60, + ) + assert (result.returncode, result.stderr) == (0, "") + + +def test_sibling_prefix_package_is_not_checked(tmp_path: Path) -> None: + """``pkg_a`` does not own ``pkg_ab``: a bare string prefix is not a package.""" + other = 'from unittest import mock\nmock.patch("pkg_ab.mod.GONE", 1)\n' + repo = _scratch_repo(tmp_path, other, "pkg_a/tests") + result = _run(repo, "pkg_a") + assert (result.returncode, result.stderr) == (0, "") diff --git a/docs/DOCS-patch-targets.md b/docs/DOCS-patch-targets.md new file mode 100644 index 0000000..3dea48b --- /dev/null +++ b/docs/DOCS-patch-targets.md @@ -0,0 +1,45 @@ +# Patch-target gate (`scripts/check_patch_targets.py`) + +`mock.patch("pkg.module.NAME", ...)` fails open. When a refactor moves `NAME`, the old path still +imports, the patch redirects nothing, and the test stays green while it writes to real user state. +The script reads every test file, finds each literal `patch("....")` target, and exits 1 +when a target no longer resolves. + +## Usage + +Run it from the repo root: + +```bash +python3 scripts/check_patch_targets.py PACKAGE [--tests-root DIR] +``` + +- `PACKAGE` is required. The script checks only targets inside it (`pkg` or `pkg.*`; `pkg_other` + is not `pkg`). It has no default, because a silent default would check the wrong package and + pass, which is the fail-open shape the gate exists to catch. +- `--tests-root` defaults to `PACKAGE/tests`. +- The package must be a flat package at the repo root (`./PACKAGE/__init__.py`). There is no + `src/` layout support yet. +- Exit codes: `0` clean, `1` stale targets (each printed as `file:line: patch target does not + resolve: ...`), a package that will not import or a missing tests root, `2` usage error. + +## Adopting it in another guard repo + +Copy `scripts/check_patch_targets.py` into the repo's `scripts/`, then add this hook to +`.pre-commit-config.yaml` under a `repo: local` block: + +```yaml + - id: patch-targets + name: test patch targets resolve + entry: python3 scripts/check_patch_targets.py + language: system + pass_filenames: false + files: ^/ +``` + +The script puts the repo root on `sys.path` itself, so the hook works on a CI runner that never +installed the package. + +## Follow-up: a shared copy + +Each adopter copies the script today. Moving it to a shared `~/src/utils/patch_targets/` package +is a separate follow-up, done once a second repo actually adopts it. diff --git a/scripts/check_patch_targets.py b/scripts/check_patch_targets.py index 8349ee7..33855e2 100755 --- a/scripts/check_patch_targets.py +++ b/scripts/check_patch_targets.py @@ -10,12 +10,20 @@ suite writes to the real ``~/.local/share/diet_guard``, which That is why this gate exists rather than a note in CLAUDE.md: the failure it guards against is silent and green, so only a static check catches it. -Usage: - python3 scripts/check_patch_targets.py +Usage (from the repo root): + python3 scripts/check_patch_targets.py PACKAGE [--tests-root DIR] + +``PACKAGE`` is required: only patch targets starting with it are checked, and +a silent default would be the same fail-open shape this script guards +against. ``--tests-root`` defaults to ``PACKAGE/tests``. Only flat packages +at the repo root are supported. Adopting it in another repo: +docs/DOCS-patch-targets.md. A shared ``~/src/utils/patch_targets/`` package is +a separate follow-up, once a second repo actually adopts this script. """ from __future__ import annotations +import argparse import ast import importlib import pathlib @@ -25,12 +33,6 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterator -#: Only paths into this package are checked; a patch of `requests` or `tk` is -#: not ours to validate. -PACKAGE = "diet_guard" - -TESTS_ROOT = pathlib.Path(PACKAGE) / "tests" - # Running this as `python3 scripts/check_patch_targets.py` puts *scripts/* on # sys.path, not the repo root -- so `import diet_guard` fails unless the # package happens to be installed. It is not, on a CI runner that only @@ -40,8 +42,19 @@ TESTS_ROOT = pathlib.Path(PACKAGE) / "tests" sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) -def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]]: - """Yield ``(file, lineno, dotted_target)`` for every literal patch target.""" +def _in_package(dotted: str, package: str) -> bool: + """Whether ``dotted`` is ``package`` or inside it (``pkg`` is not ``pkg_a``).""" + return dotted == package or dotted.startswith(f"{package}.") + + +def patch_targets( + root: pathlib.Path, package: str +) -> Iterator[tuple[pathlib.Path, int, str]]: + """Yield ``(file, lineno, dotted_target)`` for each literal target in ``package``. + + Only paths into ``package`` are checked; a patch of ``requests`` or ``tk`` + is not ours to validate. + """ for path in sorted(root.rglob("*.py")): tree = ast.parse(path.read_text(), str(path)) for node in ast.walk(tree): @@ -54,15 +67,15 @@ def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]] if ( isinstance(first, ast.Constant) and isinstance(first.value, str) - and first.value.startswith(PACKAGE) + and _in_package(first.value, package) ): yield path, node.lineno, first.value -def _third_party_missing(exc: ImportError) -> bool: - """Whether ``exc`` is a missing dependency, not a missing diet_guard module.""" +def _third_party_missing(exc: ImportError, package: str) -> bool: + """Whether ``exc`` is a missing dependency, not a missing ``package`` module.""" missing = getattr(exc, "name", None) or "" - return isinstance(exc, ModuleNotFoundError) and not missing.startswith(PACKAGE) + return isinstance(exc, ModuleNotFoundError) and not _in_package(missing, package) def _lazy_names(value: ast.expr | None) -> list[str]: @@ -107,7 +120,7 @@ def defined_statically(parts: list[str], split: int) -> bool: return False -def resolves(dotted: str) -> bool: +def resolves(dotted: str, package: str) -> bool: """Whether ``dotted`` names a real attribute reachable from a real module. Tries the longest importable module prefix first, then walks the remaining @@ -122,7 +135,7 @@ def resolves(dotted: str) -> bool: # worker's `rtdb_relay`, absent from the system python this hook # runs under) still has a source file: check the name statically # rather than call a present target stale. - if _third_party_missing(exc) and defined_statically(parts, split): + if _third_party_missing(exc, package) and defined_statically(parts, split): return True continue obj: object = module @@ -134,10 +147,25 @@ def resolves(dotted: str) -> bool: return False -def main() -> int: +def _parse_args(argv: list[str] | None) -> argparse.Namespace: + """``package`` (required, no default) and ``--tests-root``.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("package", help="top-level package whose targets to check") + parser.add_argument( + "--tests-root", + type=pathlib.Path, + help="directory of tests to scan (default: PACKAGE/tests)", + ) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: """Report every unresolvable patch target; return 1 if any were found.""" - if not TESTS_ROOT.is_dir(): - sys.stderr.write(f"Error: {TESTS_ROOT} not found; run from the repo root.\n") + args = _parse_args(argv) + package: str = args.package + tests_root: pathlib.Path = args.tests_root or pathlib.Path(package) / "tests" + if not tests_root.is_dir(): + sys.stderr.write(f"Error: {tests_root} not found; run from the repo root.\n") return 1 # Distinguish "this target moved" from "the package will not import at @@ -145,10 +173,10 @@ def main() -> int: # target reports stale at once, which reads like a catastrophic refactor # and hides the real error (a missing dependency, a syntax error). try: - importlib.import_module(PACKAGE) + importlib.import_module(package) except ImportError as exc: sys.stderr.write( - f"Error: cannot import {PACKAGE} ({exc}); every patch target would " + f"Error: cannot import {package} ({exc}); every patch target would " f"be reported stale. Fix the import first -- this is an environment " f"problem, not a stale patch target.\n", ) @@ -156,8 +184,8 @@ def main() -> int: stale = [ (path, lineno, target) - for path, lineno, target in patch_targets(TESTS_ROOT) - if not resolves(target) + for path, lineno, target in patch_targets(tests_root, package) + if not resolves(target, package) ] for path, lineno, target in stale: sys.stderr.write(f"{path}:{lineno}: patch target does not resolve: {target}\n")