Skip to content

The agent that grows with you

fix(code-health): parse ENFORCEMENT with ast and read it from the main tip locally

Tekniuma6274687fde7
diff --git a/scripts/check b/scripts/check
index 906bb24552b..5538b7aba4b 100755
--- a/scripts/check
+++ b/scripts/check
@@ -133,14 +133,15 @@ def _run_jobs(jobs: dict[str, _Job]) -> dict[str, tuple[int, str]]:
def _run_all(args: argparse.Namespace) -> dict[str, tuple[int, str]]:
if not (args.staged or args.commit):
return _run_jobs(_jobs(args.only, args.base, None))
- # Hooks judge the bytes being committed or pushed, never the working tree.
+ # Hooks judge the bytes being committed or pushed, never the working tree. Without --base the
+ # ratchet derives the base from the head (a commit's own merge-base) and the switch from main.
if args.staged:
- tree, base = gitio.git(REPO, "write-tree").strip(), args.base
+ tree = head = gitio.git(REPO, "write-tree").strip()
else:
- commit = gitio.resolve_rev(REPO, args.commit)
- tree, base = gitio.resolve_tree(REPO, commit), args.base or gitio.default_base(REPO, commit)
+ head = gitio.resolve_rev(REPO, args.commit)
+ tree = gitio.resolve_tree(REPO, head)
with _tree_snapshot(tree) as (root, env):
- return _run_jobs(_jobs(args.only, base, tree, root, env))
+ return _run_jobs(_jobs(args.only, args.base, head, root, env))
def _hooks_dir() -> Path:
diff --git a/scripts/code_health/cli.py b/scripts/code_health/cli.py
index 8d1fbae07b7..7f7e53a1446 100644
--- a/scripts/code_health/cli.py
+++ b/scripts/code_health/cli.py
@@ -3,8 +3,8 @@
from __future__ import annotations
import argparse
+import ast
import json
-import re
import subprocess
import sys
import time
@@ -32,13 +32,32 @@ Reproduce locally: python scripts/check --only health (every lint check: python
on every push: python scripts/check --install-hook pre-push)."""
_SWITCH_FILE = "scripts/code_health/config.py"
-_SWITCH = re.compile(r"^ENFORCEMENT\s*=\s*[\"'](blocking|advisory|off)[\"']", re.MULTILINE)
+_MODES = ("blocking", "advisory", "off")
-def enforcement(repo: Path, base: str) -> str:
- """The master switch as committed on the base revision; a base without one is blocking."""
- found = _SWITCH.search(gitio.read_file(repo, base, _SWITCH_FILE) or "")
- return found.group(1) if found else "blocking"
+def parse_switch(text: str) -> str:
+ """The module-level ``ENFORCEMENT`` value (plain or annotated assignment, the last one wins,
+ as at runtime). Missing, unparseable or unknown is "blocking": no edit relaxes it by accident."""
+ try:
+ body = ast.parse(text).body
+ except SyntaxError:
+ return "blocking"
+ found = None
+ for node in body:
+ if isinstance(node, ast.Assign):
+ targets = node.targets
+ elif isinstance(node, ast.AnnAssign):
+ targets = [node.target]
+ else:
+ continue
+ if any(isinstance(t, ast.Name) and t.id == "ENFORCEMENT" for t in targets):
+ found = node.value.value if isinstance(node.value, ast.Constant) else None
+ return found if found in _MODES else "blocking"
+
+
+def enforcement(repo: Path, rev: str) -> str:
+ """The master switch as committed on ``rev``; a revision without one is blocking."""
+ return parse_switch(gitio.read_file(repo, rev, _SWITCH_FILE) or "")
def _parser() -> argparse.ArgumentParser:
@@ -66,11 +85,15 @@ def _skipped(why: str, as_json: bool) -> None:
print(why, file=sys.stderr if as_json else sys.stdout)
-def run(repo: Path, base: str, head: str | None, as_json: bool = False) -> int:
+def run(repo: Path, base: str, head: str | None, as_json: bool = False,
+ switch_rev: str | None = None) -> int:
+ """Judge ``head`` against ``base``; the ENFORCEMENT switch is read from ``switch_rev``
+ (default: the base), never from the head under test."""
started = time.monotonic()
- mode = enforcement(repo, base)
+ switch_rev = switch_rev or base
+ mode = enforcement(repo, switch_rev)
if mode == "off":
- _skipped(f"code health: off (ENFORCEMENT in {_SWITCH_FILE} on {base[:12]})", as_json)
+ _skipped(f"code health: off (ENFORCEMENT in {_SWITCH_FILE} on {switch_rev[:12]})", as_json)
return 0
changes = gitio.changed_files(repo, base, head)
head_paths = sorted({c.new for c in changes if c.new and in_scope(c.new)})
@@ -110,12 +133,18 @@ def main(argv: list[str] | None = None) -> int:
if args.print_pins:
print(f"ruff=={pinned_version(repo)}")
return 0
- head = gitio.resolve_tree(repo, args.head) if args.head else None
try:
+ head = gitio.resolve_tree(repo, args.head) if args.head else None
if args.report:
return _report(repo, head)
- base = gitio.resolve_rev(repo, args.base) if args.base else gitio.default_base(repo)
- return run(repo, base, head, as_json=args.json)
+ if args.base: # CI: the base is the target branch tip, which also holds the switch
+ return run(repo, gitio.resolve_rev(repo, args.base), head, as_json=args.json)
+ # Locally the base is the merge-base, which lags main; the switch comes from the main tip
+ # so a flip on main reaches a branch without a rebase. The head never supplies it.
+ tip = gitio.commit_or_none(repo, args.head) if args.head else None
+ base = gitio.default_base(repo, tip or "HEAD")
+ switch_rev = gitio.commit_or_none(repo, "origin/main") or base
+ return run(repo, base, head, as_json=args.json, switch_rev=switch_rev)
except RuntimeError as exc:
print(f"code health: {exc}", file=sys.stderr)
return 2
diff --git a/scripts/code_health/gitio.py b/scripts/code_health/gitio.py
index d7a1db4cfea..726c6ac51cb 100644
--- a/scripts/code_health/gitio.py
+++ b/scripts/code_health/gitio.py
@@ -41,6 +41,11 @@ def resolve_tree(repo: Path, rev: str) -> str:
return git(repo, "rev-parse", "--verify", f"{rev}^{{tree}}").strip()
+def commit_or_none(repo: Path, rev: str) -> str | None:
+ """``rev`` as a commit sha, or None when it does not name a commit (a tree, a missing ref)."""
+ return git(repo, "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}", check=False).strip() or None
+
+
def default_base(repo: Path, tip: str = "HEAD") -> str:
"""Merge-base of ``tip`` with origin/main (local runs); CI passes ``--base`` explicitly."""
for ref in ("origin/main", "main"):
diff --git a/tests/scripts/test_code_health_cli.py b/tests/scripts/test_code_health_cli.py
index 1df1b2f9ea1..3454cb01613 100644
--- a/tests/scripts/test_code_health_cli.py
+++ b/tests/scripts/test_code_health_cli.py
@@ -153,6 +153,56 @@ def test_json_stdout_is_json_on_every_path(tmp_path, capsys, case, switch, files
assert "code health:" in err # the human explanation moves to stderr
+# --- m3: the ENFORCEMENT switch ---------------------------------------------------------------
+
+
[email protected]("switch, code", [
+ ('ENFORCEMENT: str = "off"\n', 0),
+ ('ENFORCEMENT: str = "advisory"\n', 0),
+ ('ENFORCEMENT = "warn"\n', 1), # an unknown value is not a way to relax the check
+ ('ENFORCEMENT = "off" # until the burn-down lands\n', 0),
+])
+def test_enforcement_switch_parses_annotated_and_unknown_values(tmp_path, capsys, switch, code):
+ repo, base = _ratchet_repo(tmp_path, switch)
+ head = _commit(repo, {"pkg/a.py": _GROWN})
+ assert cli.run(repo, base, head) == code, capsys.readouterr().out
+
+
+def test_enforcement_reads_this_trees_own_switch():
+ assert cli.enforcement(REPO, "HEAD") == ENFORCEMENT
+ text = (REPO / _SWITCH).read_text(encoding="utf-8")
+ assert cli.parse_switch(text) == ENFORCEMENT
+
+
+def _branch_behind_main(tmp_path: Path, main_switch: str, branch_files: dict[str, str]) -> Path:
+ repo, base = _ratchet_repo(tmp_path, 'ENFORCEMENT = "blocking"\n')
+ _git(repo, "checkout", "-q", "-b", "feature")
+ _commit(repo, branch_files)
+ _git(repo, "checkout", "-q", "main")
+ tip = _commit(repo, {_SWITCH: main_switch, "NEWS.md": "main moved on\n"})
+ _git(repo, "update-ref", "refs/remotes/origin/main", tip)
+ _git(repo, "reset", "-q", "--hard", base) # local main is stale; only origin/main moved
+ _git(repo, "checkout", "-q", "feature")
+ return repo
+
+
+def test_local_runs_take_the_switch_from_the_main_tip(tmp_path, monkeypatch, capsys):
+ repo = _branch_behind_main(tmp_path, 'ENFORCEMENT = "advisory"\n', {"pkg/a.py": _GROWN})
+ monkeypatch.chdir(repo)
+ assert cli.main([]) == 0, capsys.readouterr().out # the flip on main reaches the branch
+ head = _git(repo, "rev-parse", "HEAD")
+ assert cli.main(["--head", head]) == 0
+ out = capsys.readouterr().out
+ assert "CC 23 > 22" in out and "advisory mode" in out
+
+
+def test_a_branch_cannot_relax_its_own_switch(tmp_path, monkeypatch, capsys):
+ grown_and_off = {"pkg/a.py": _GROWN, _SWITCH: 'ENFORCEMENT = "off"\n'}
+ repo = _branch_behind_main(tmp_path, 'ENFORCEMENT = "blocking"\n', grown_and_off)
+ monkeypatch.chdir(repo)
+ assert cli.main([]) == 1, capsys.readouterr().out
+
+
# --- F21: profile regex rules see executable code, not prose -----------------------------------