Answer stability round 1: 3 🔴, 3 🟡 (0 misread); list files with diff-index, check the index blob, take override markers from the added lines

This commit is contained in:
2026-11-11 14:19:48 +01:00
parent 47c10c4565
commit 21bd753c5b
2 changed files with 79 additions and 20 deletions
+35 -18
View File
@@ -1,37 +1,54 @@
import dataclasses
import posixpath
from failure import Failure
from rule_hook.file_text import read
from rule_hook.git import guarded_git
from rule_hook.rules import Breach, file_breaches
from failure import Failure
from git_cli import git_repo
from rule_hook.git import guarded_git
from rule_hook.file_text import read
# settings.json gives rule-hook 30 seconds; a file past this size is no source file, and reading it would eat them.
# settings.json gives rule-hook 30 seconds; a file past this size is not source code, and reading it would use them up.
MAX_BYTES = 1_000_000
def committed_file_breaches(directory: str) -> list[Breach]:
"""The breaches of file_breaches in the files a commit in directory's checkout would commit.
A file a Bash command wrote reaches no Edit or Write check, so the commit stands in for it. The files are those that differ from HEAD in the index or the work tree, or that are untracked and not ignored: the hook runs before a `git add` earlier in the same command, so the index alone would miss them. Deleted files and files that are no UTF-8 text have no added text. A breach carries its file's text, so a marker in the file overrides it, as in an Edit."""
A file a Bash command wrote reaches no Edit or Write check, so the commit checks the file instead. The files are those that differ from HEAD in the index or the work tree, or that are untracked and not ignored: the hook runs before a `git add` earlier in the same command, so the index alone would miss those files. A tracked file is checked as the index holds it and as the work tree does, since the commit takes the index. A deleted file, or one that is not UTF-8 text, has no added text. A breach carries the lines its file adds, so a marker among them overrides it, as in a Write; a marker the file already held doesn't."""
top = guarded_git(directory, "rev-parse", "--show-toplevel")
if isinstance(top, Failure):
return []
changed = guarded_git(top, "diff", "-z", "--name-only", "--no-renames", "--diff-filter=d", "HEAD")
# A checkout with no commit has no HEAD: its index is what differs.
changed = guarded_git(top, "diff", "-z", "--name-only", "--cached", "--no-renames", "--diff-filter=d") if isinstance(changed, Failure) else changed
tracked = tracked_names(top)
untracked = guarded_git(top, "ls-files", "-z", "--others", "--exclude-standard")
names = sorted({name for listing in (changed, untracked) if not isinstance(listing, Failure) for name in listing.split("\0") if name})
breaches = []
for name in names:
breaches: list[Breach] = []
for name in sorted(tracked | (set() if isinstance(untracked, Failure) else names_in(untracked))):
path = posixpath.join(top, name)
after = read(path) if size(path) <= MAX_BYTES else ""
before = guarded_git(top, "show", f"HEAD:{name}")
before = "" if isinstance(before, Failure) else before
known = set(before.splitlines())
added = "\n".join(line for line in after.splitlines() if line not in known)
breaches += [dataclasses.replace(breach, marked=after) for breach in file_breaches(path, before, added, after)] if added else []
return breaches
before = blob(top, "HEAD" if name in tracked else "", name)
for after in dict.fromkeys([read(path) if size(path) <= MAX_BYTES else "", blob(top, "", name) if name in tracked else ""]):
known = set(before.splitlines())
added = "\n".join(line for line in after.splitlines() if line not in known)
breaches += [dataclasses.replace(breach, marked=added) for breach in file_breaches(path, before, added, after)]
return list(dict.fromkeys(breaches))
def tracked_names(top: str) -> set[str]:
"""The tracked files that differ from HEAD in the index or the work tree, deleted ones left out. It lists with diff-index, which neither hashes the work tree nor enters a submodule: either would run a clean filter that the checkout's config names, before the call is allowed."""
listings = [guarded_git(top, "diff-index", "-z", "--name-only", "--no-renames", "--diff-filter=d", "--ignore-submodules", *cached, "HEAD") for cached in ([], ["--cached"])]
if any(isinstance(listing, Failure) for listing in listings):
# A checkout with no commit has no HEAD: every file in its index is new.
listing = guarded_git(top, "ls-files", "-z")
return set() if isinstance(listing, Failure) else names_in(listing)
return {name for listing in listings if not isinstance(listing, Failure) for name in names_in(listing)}
def names_in(listing: str) -> set[str]:
return {name for name in listing.split("\0") if name}
def blob(top: str, commit: str, name: str) -> str:
"""name's text in the commit, or in the index where commit is empty; "" where there is none."""
shown = git_repo.git("show", f"{commit}:{name}", cwd=top, guarded=True)
return "" if isinstance(shown, Failure) else shown
def size(path: str) -> int:
+44 -2
View File
@@ -965,12 +965,54 @@ class CommittedFiles(unittest.TestCase):
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n")
self.assertEqual(self.commit().returncode, 0)
def test_a_marker_in_another_file_overrides_nothing(self):
def test_a_staged_breach_blocks_the_commit_after_the_work_tree_is_fixed(self):
self.write("Dockerfile", "FROM node:24\n")
git(self.repo, "add", "Dockerfile")
self.write("Dockerfile", "FROM node:24.18.1\n")
self.assertIn("image-pin: ", self.commit("git commit -m x").stderr)
def test_a_stat_dirty_file_runs_no_clean_filter(self):
self.write("a.txt", "a\n")
self.write(".gitattributes", "a.txt filter=planted\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
git(self.repo, "config", "filter.planted.clean", f"touch {self.repo}/ran; cat")
pathlib.Path(self.repo, "ran").unlink(missing_ok=True)
os.utime(pathlib.Path(self.repo, "a.txt"), (1, 1))
self.assertEqual(self.commit("git commit -m x").returncode, 0)
self.assertFalse(pathlib.Path(self.repo, "ran").exists())
def test_a_checkout_with_no_commit_checks_its_index_and_untracked_files(self):
fresh = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", fresh])
git(fresh, "init", "-q", "-b", "main")
pathlib.Path(fresh, "Dockerfile").write_text("FROM node:24\n")
git(fresh, "add", "Dockerfile")
pathlib.Path(fresh, "NOTES.md").write_text(TRAILER + "\n")
ran = hook({"cwd": fresh, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, fresh)
for rule in ["image-pin", "no-ai-attribution"]:
self.assertIn(f"Blocked by rule {rule}: ", ran.stderr)
def test_a_change_that_only_reorders_an_ignore_file_is_checked(self):
self.write(".gitignore", "a\nb\nc\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write(".gitignore", "c\nb\na\n")
self.assertIn("ignorefile-sorted: ", self.commit().stderr)
def test_a_marker_the_head_already_holds_does_not_override_a_new_breach(self):
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\nFROM node:24\n")
self.assertIn("image-pin: ", self.commit().stderr)
def test_a_marker_in_another_file_does_not_override_a_breach(self):
self.write("Dockerfile", "FROM vendor/tool:2\n")
self.write("NOTES.md", "# rule-override image-pin: quoted in a note\n")
self.assertIn("Blocked by rule image-pin: ", self.commit().stderr)
def test_an_untracked_ignored_or_binary_file_breaks_nothing(self):
def test_an_ignored_or_binary_file_is_left_alone(self):
self.write(".gitignore", "build/\n")
self.write("build/Dockerfile", "FROM node:24\n")
pathlib.Path(self.repo, "image.png").write_bytes(b"\xff\xfe\x00FROM node:24\n")