mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-26 22:47:20 +01:00
check_patch_targets: package as a CLI argument
Some checks failed
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
dependency freshness / dependencies on newest stable (push) Has been cancelled
Some checks failed
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
dependency freshness / dependencies on newest stable (push) Has been cancelled
The script hard-coded PACKAGE='diet_guard', so other guard repos could not run it (build-background-service R3). PACKAGE is now a required positional (no silent default: that is the fail-open shape the gate guards against); --tests-root defaults to PACKAGE/tests. Targets match PACKAGE or PACKAGE.*, so pkg_a no longer claims pkg_ab. Adoption snippet in docs/DOCS-patch-targets.md. A shared ~/src/utils/patch_targets/ package is a separate follow-up, once a second repo adopts the script. Todo: 6d0ec573 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d56edbc413
commit
abd8793e60
@ -281,7 +281,7 @@ repos:
|
|||||||
# patch target statically so a stale path fails the commit instead.
|
# patch target statically so a stale path fails the commit instead.
|
||||||
- id: patch-targets
|
- id: patch-targets
|
||||||
name: test patch targets resolve
|
name: test patch targets resolve
|
||||||
entry: python3 scripts/check_patch_targets.py
|
entry: python3 scripts/check_patch_targets.py diet_guard
|
||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
files: ^diet_guard/
|
files: ^diet_guard/
|
||||||
|
|||||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
|||||||
description: "Companion phone app for diet_guard: log meals on the go."
|
description: "Companion phone app for diet_guard: log meals on the go."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 1.0.184+1
|
version: 1.0.185+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
|
|||||||
103
diet_guard/tests/test_check_patch_targets_cli.py
Normal file
103
diet_guard/tests/test_check_patch_targets_cli.py
Normal file
@ -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 ``<package>/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 ``<package>/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, "")
|
||||||
45
docs/DOCS-patch-targets.md
Normal file
45
docs/DOCS-patch-targets.md
Normal file
@ -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("<package>....")` 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 <your_package>
|
||||||
|
language: system
|
||||||
|
pass_filenames: false
|
||||||
|
files: ^<your_package>/
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
@ -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
|
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.
|
guards against is silent and green, so only a static check catches it.
|
||||||
|
|
||||||
Usage:
|
Usage (from the repo root):
|
||||||
python3 scripts/check_patch_targets.py
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
import ast
|
import ast
|
||||||
import importlib
|
import importlib
|
||||||
import pathlib
|
import pathlib
|
||||||
@ -25,12 +33,6 @@ from typing import TYPE_CHECKING
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Iterator
|
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
|
# 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
|
# 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
|
# 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))
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
|
||||||
def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]]:
|
def _in_package(dotted: str, package: str) -> bool:
|
||||||
"""Yield ``(file, lineno, dotted_target)`` for every literal patch target."""
|
"""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")):
|
for path in sorted(root.rglob("*.py")):
|
||||||
tree = ast.parse(path.read_text(), str(path))
|
tree = ast.parse(path.read_text(), str(path))
|
||||||
for node in ast.walk(tree):
|
for node in ast.walk(tree):
|
||||||
@ -54,15 +67,15 @@ def patch_targets(root: pathlib.Path) -> Iterator[tuple[pathlib.Path, int, str]]
|
|||||||
if (
|
if (
|
||||||
isinstance(first, ast.Constant)
|
isinstance(first, ast.Constant)
|
||||||
and isinstance(first.value, str)
|
and isinstance(first.value, str)
|
||||||
and first.value.startswith(PACKAGE)
|
and _in_package(first.value, package)
|
||||||
):
|
):
|
||||||
yield path, node.lineno, first.value
|
yield path, node.lineno, first.value
|
||||||
|
|
||||||
|
|
||||||
def _third_party_missing(exc: ImportError) -> bool:
|
def _third_party_missing(exc: ImportError, package: str) -> bool:
|
||||||
"""Whether ``exc`` is a missing dependency, not a missing diet_guard module."""
|
"""Whether ``exc`` is a missing dependency, not a missing ``package`` module."""
|
||||||
missing = getattr(exc, "name", None) or ""
|
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]:
|
def _lazy_names(value: ast.expr | None) -> list[str]:
|
||||||
@ -107,7 +120,7 @@ def defined_statically(parts: list[str], split: int) -> bool:
|
|||||||
return False
|
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.
|
"""Whether ``dotted`` names a real attribute reachable from a real module.
|
||||||
|
|
||||||
Tries the longest importable module prefix first, then walks the remaining
|
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
|
# worker's `rtdb_relay`, absent from the system python this hook
|
||||||
# runs under) still has a source file: check the name statically
|
# runs under) still has a source file: check the name statically
|
||||||
# rather than call a present target stale.
|
# 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
|
return True
|
||||||
continue
|
continue
|
||||||
obj: object = module
|
obj: object = module
|
||||||
@ -134,10 +147,25 @@ def resolves(dotted: str) -> bool:
|
|||||||
return False
|
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."""
|
"""Report every unresolvable patch target; return 1 if any were found."""
|
||||||
if not TESTS_ROOT.is_dir():
|
args = _parse_args(argv)
|
||||||
sys.stderr.write(f"Error: {TESTS_ROOT} not found; run from the repo root.\n")
|
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
|
return 1
|
||||||
|
|
||||||
# Distinguish "this target moved" from "the package will not import at
|
# 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
|
# target reports stale at once, which reads like a catastrophic refactor
|
||||||
# and hides the real error (a missing dependency, a syntax error).
|
# and hides the real error (a missing dependency, a syntax error).
|
||||||
try:
|
try:
|
||||||
importlib.import_module(PACKAGE)
|
importlib.import_module(package)
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
sys.stderr.write(
|
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"be reported stale. Fix the import first -- this is an environment "
|
||||||
f"problem, not a stale patch target.\n",
|
f"problem, not a stale patch target.\n",
|
||||||
)
|
)
|
||||||
@ -156,8 +184,8 @@ def main() -> int:
|
|||||||
|
|
||||||
stale = [
|
stale = [
|
||||||
(path, lineno, target)
|
(path, lineno, target)
|
||||||
for path, lineno, target in patch_targets(TESTS_ROOT)
|
for path, lineno, target in patch_targets(tests_root, package)
|
||||||
if not resolves(target)
|
if not resolves(target, package)
|
||||||
]
|
]
|
||||||
for path, lineno, target in stale:
|
for path, lineno, target in stale:
|
||||||
sys.stderr.write(f"{path}:{lineno}: patch target does not resolve: {target}\n")
|
sys.stderr.write(f"{path}:{lineno}: patch target does not resolve: {target}\n")
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user