import json import os import pathlib import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from rule_hook.rules import blocks, Breach, command_breaches, Commit, commit_message, commits, file_breaches, overrides, verdict from test_rank_todo import DECISIONS, README, TODO from test_env import isolated_env from shell_command import simple_commands HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook" # Built from parts, so this file carries no attribution of its own. TRAILER = "Co-Authored-" + "By: Claude " def rules(breaches: list[Breach]) -> list[str]: return [breach.rule for breach in breaches] def committed(command: str, cwd: str = "/r") -> list[Commit]: return commits(simple_commands(command, cwd, "/h"), "/h") def checked(command: str) -> list[str]: return rules(command_breaches(command, simple_commands(command, "/r", "/h"), "/h")) def hook(call: dict, cwd: str) -> subprocess.CompletedProcess: return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env(), input=json.dumps(call), text=True) def git(cwd: str, *args: str) -> str: return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=cwd, env=isolated_env(), text=True).stdout class Commits(unittest.TestCase): def test_cd_and_dash_capital_c_move_the_commit(self): self.assertEqual(committed("cd a && git -C ~/b commit -am 'x'"), [Commit("/h/b", ["x"], False)]) self.assertEqual(committed("cd a && git -c x=y -C b commit -m x")[0].directory, "/r/a/b") def test_each_message_spelling_is_read(self): self.assertEqual(commit_message(["--message=a", "-m", "b=c", "--message", "c", "-mz", "-am", "d"]), (["a", "b=c", "c", "z", "d"], False)) def test_a_file_message_is_seen(self): self.assertEqual(commit_message(["-F", "-"]), ([], True)) self.assertEqual(commit_message(["--file=x"]), ([], True)) def test_other_git_commands_are_no_commit(self): self.assertEqual(committed("git log --grep commit; echo git commit"), []) def test_a_line_break_or_a_comment_separates_commands(self): self.assertEqual(committed("cd a # go there\nGIT_EDITOR=true git commit -m x"), [Commit("/r/a", ["x"], False)]) def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self): self.assertEqual(len(committed("cat < notes\nhello\nEOF\ngit commit -m a")), 1) self.assertEqual(len(committed("git status &&\n\ngit commit -m a")), 1) def test_an_arithmetic_shift_is_no_heredoc(self): self.assertEqual(len(committed("echo $((1<<2))\ngit commit -m a\n2")), 1) def test_a_line_that_does_not_parse_hides_only_itself(self): self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1) class CommandBreaches(unittest.TestCase): def test_one_line_passes(self): self.assertEqual(checked("git add . && git commit -m 'ABC-1 - Fix #2'"), []) def test_a_heredoc_a_second_message_or_a_file_breaks_commit_one_line(self): for command in ["git commit -m \"$(cat <<'EOF'\nIt's one line\nEOF\n)\"", "git commit -m a -m b", "git commit -F - <<'EOF'\nTitle\n\nIt's the body\nEOF\necho done", "git commit --author '' -m a -m b"]: with self.subTest(command): self.assertEqual(checked(command), ["commit-one-line"]) def test_an_attribution_breaks_only_in_a_git_gh_or_tea_command(self): self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"]) self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), []) def test_a_commit_breach_names_the_commit_s_checkout(self): self.assertEqual(command_breaches("cd w && git commit -m a -m b", simple_commands("cd w && git commit -m a -m b", "/r", "/h"), "/h")[0].directory, "/r/w") class FileBreaches(unittest.TestCase): def test_an_image_needs_a_patch_version_a_date_or_a_digest(self): added = "FROM node:24 AS build\nFROM node:24.18.1-bookworm-slim\nFROM alpine@sha256:ab\nFROM debian:bookworm-20240926-slim\nFROM build\nFROM scratch\nFROM ${BASE}\nFROM python\nCOPY --from=build /a /a\nCOPY --from=0 /b /b\nCOPY --chown=1 --from=alpine:3 /c /c\n" self.assertEqual([breach.detail for breach in file_breaches("/r/Dockerfile", "", added, added)], ["/r/Dockerfile: node:24", "/r/Dockerfile: python", "/r/Dockerfile: alpine:3"]) def test_a_stage_named_outside_the_edit_is_no_image(self): self.assertEqual(file_breaches("app.dockerfile", "FROM node:24.1.0 AS base\n", "FROM base\n", "FROM node:24.1.0 AS base\nFROM base\n"), []) def test_a_workflow_checks_its_images_and_actions(self): added = " container: node:24\n image: mysql:8.4\n - image: 'mysql:8.4.7'\n - uses: actions/checkout@v4\n - uses: a/b@0123456789abcdef0123456789abcdef01234567\n - uses: ./local\n" self.assertEqual(rules(file_breaches("/r/.gitea/workflows/ci.yml", "", added, added)), ["image-pin", "image-pin", "action-pin"]) def test_a_compose_file_checks_its_images(self): self.assertEqual(rules(file_breaches("compose.yaml", "", " image: redis\n", " image: redis\n")), ["image-pin"]) def test_other_yaml_is_not_checked(self): added = "image: /assets/og.png\nimage: { type: string }\nuses: a/b@main\n" self.assertEqual(file_breaches("_config.yml", "", added, added), []) def test_an_ignore_file_sorts_each_block_split_by_blank_lines_and_comments(self): self.assertEqual(blocks("b\na\n\n# c\nd\n# e\nf\n"), [["b", "a"], ["d"], ["f"]]) self.assertEqual(rules(file_breaches(".dockerignore", "", "x", "b\na\n")), ["ignorefile-sorted"]) self.assertEqual(file_breaches(".gitignore", "", "x", "*\n\n!a\n!b\n"), []) def test_a_block_unsorted_before_the_edit_is_left_alone(self): self.assertEqual(file_breaches(".gitignore", "node_modules\n.env\n\ndist\n", "out", "node_modules\n.env\n\ndist\nout\n"), []) def test_an_attribution_in_any_file_breaks(self): self.assertEqual(rules(file_breaches("notes.md", "", TRAILER, TRAILER)), ["no-ai-attribution"]) class Overrides(unittest.TestCase): def test_a_marker_names_a_known_rule_and_a_reason(self): self.assertEqual(overrides("x # rule-override image-pin: vendor ships floating tags only\n# rule-override nope: x\n# rule-override action-pin:"), ({"image-pin": "vendor ships floating tags only"}, ["rule-override nope: x", "rule-override action-pin: "])) def test_two_markers_on_a_line_are_read_apart(self): self.assertEqual(overrides("git x # rule-override image-pin: a # rule-override nope: b")[1], ["rule-override nope: b"]) def test_markdown_takes_an_html_comment(self): self.assertEqual(overrides("")[0], {"no-ai-attribution": "quotes the banned line"}) def test_a_blocked_call_overrides_nothing_yet(self): breaches = [Breach("image-pin", "x", "/r"), Breach("action-pin", "y", "/r")] judged = verdict(breaches, "# rule-override image-pin: a", False, False) self.assertTrue(judged.blocked) passed = verdict(breaches[:1], "# rule-override image-pin: a", False, False) self.assertEqual((passed.blocked, passed.overridden), (False, [(breaches[0], "a")])) def test_a_markdown_file_is_told_the_html_comment(self): self.assertIn("``", verdict([Breach("no-ai-attribution", "x", "/r")], "", True, False).messages[0]) class Hook(unittest.TestCase): def setUp(self): self.repo = tempfile.mkdtemp() self.addCleanup(subprocess.run, ["rm", "-rf", self.repo]) git(self.repo, "init", "-q", "-b", "main") git(self.repo, "commit", "-q", "--allow-empty", "-m", "base") git(self.repo, "checkout", "-q", "-b", "chunk") def listed(self) -> str: return subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout def test_a_breach_exits_2_naming_the_rule_and_the_override(self): ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": "FROM node:24\n"}, "tool_name": "Write"}, self.repo) self.assertEqual(ran.returncode, 2) self.assertIn("Blocked by rule image-pin: ", ran.stderr) self.assertIn("`# rule-override image-pin: `", ran.stderr) def test_an_override_passes_and_is_listed_for_the_chunk(self): content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n" ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/sub/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo) self.assertEqual((ran.returncode, ran.stderr), (0, "")) self.assertRegex(self.listed(), r"^\S+Z\tchunk\t[0-9a-f]{40}\timage-pin\tthe vendor tags no patch versions\t\S+/sub/Dockerfile\n$") git(self.repo, "checkout", "-q", "main") git(self.repo, "commit", "-q", "--allow-empty", "-m", "elsewhere") self.assertEqual(self.listed(), "", "the default branch holds no override of its own") def test_an_override_outlives_an_amend(self): git(self.repo, "commit", "-q", "--allow-empty", "-m", "work") content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n" hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo) git(self.repo, "commit", "-q", "--amend", "--allow-empty", "-m", "reworded") git(self.repo, "checkout", "-q", "-b", "renamed") self.assertIn("\timage-pin\t", self.listed(), "the default branch does not hold the commit") def test_a_blocked_call_logs_no_override(self): command = f"git commit -m a -m '{TRAILER}' # rule-override no-ai-attribution: quotes it" self.assertEqual(hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo).returncode, 2) self.assertEqual(self.listed(), "") def test_a_commit_override_is_logged_in_the_commit_s_checkout(self): outside = tempfile.mkdtemp() self.addCleanup(subprocess.run, ["rm", "-rf", outside]) ran = hook({"cwd": outside, "tool_input": {"command": f"git -C {self.repo} commit -m a -m b # rule-override commit-one-line: a body is needed"}, "tool_name": "Bash"}, outside) self.assertEqual(ran.returncode, 0) self.assertIn("\tcommit-one-line\ta body is needed\t", self.listed()) def test_an_edit_is_judged_on_the_file_it_leaves(self): pathlib.Path(self.repo, ".gitignore").write_text("a\nc\n") call = {"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/.gitignore", "new_string": "d", "old_string": "a"}, "tool_name": "Edit"} self.assertEqual(hook(call, self.repo).returncode, 2) def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self): pathlib.Path(self.repo, "docs").mkdir() for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]: pathlib.Path(self.repo, name).write_text(content) git(self.repo, "add", "README.md", "docs", "todo.md") git(self.repo, "commit", "-qm", "x", "--no-verify") call = {"cwd": self.repo, "tool_input": {"command": "git add -A && git commit -m x"}, "tool_name": "Bash"} self.assertEqual(hook(call, self.repo).returncode, 0, "todo.md is unchanged") pathlib.Path(self.repo, "todo.md").write_text(TODO + "\n") ran = hook(call, self.repo) self.assertEqual(ran.returncode, 2) self.assertIn("todo.md: not ranked", ran.stderr) def test_a_staged_todo_change_is_checked_and_no_clean_filter_runs(self): pathlib.Path(self.repo, "docs").mkdir() for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO), (".gitattributes", "todo.md filter=planted\n")]: pathlib.Path(self.repo, name).write_text(content) git(self.repo, "add", "-A") git(self.repo, "config", "filter.planted.clean", f"touch {self.repo}/ran; cat") pathlib.Path(self.repo, "ran").unlink(missing_ok=True) # A stat-dirty index entry, as extracting an archive leaves, is what makes `git status` re-run the filter. os.utime(pathlib.Path(self.repo, "todo.md"), (1, 1)) ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, self.repo) self.assertEqual(ran.returncode, 2, ran.stderr) self.assertFalse(pathlib.Path(self.repo, "ran").exists()) def test_a_symlinked_log_is_refused(self): target = pathlib.Path(self.repo, "elsewhere") pathlib.Path(self.repo, ".git", "rule-overrides.tsv").symlink_to(target) content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n" ran = hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo) self.assertEqual(ran.returncode, 2) self.assertFalse(target.exists()) def test_a_malformed_override_is_named(self): ran = hook({"cwd": self.repo, "tool_input": {"command": f"git commit -m a -m b -m '{TRAILER}' # rule-override no-ai-attribution: quotes it # rule-override commit-oneline: x"}, "tool_name": "Bash"}, self.repo) self.assertIn("`rule-override commit-oneline: x` names no rule below", ran.stderr) def test_a_missing_field_breaks_nothing(self): for given in [{"command": None}, {"content": None, "file_path": f"{self.repo}/a.md"}, {"edits": [None], "file_path": f"{self.repo}/a.md"}]: with self.subTest(given): tool = "Bash" if "command" in given else "Write" if "content" in given else "MultiEdit" self.assertEqual(hook({"cwd": self.repo, "tool_input": given, "tool_name": tool}, self.repo).returncode, 0) def test_unreadable_input_does_not_block(self): for given in ["{", json.dumps({"cwd": ".", "tool_input": None, "tool_name": "Bash"})]: with self.subTest(given): self.assertEqual(subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input=given, text=True).returncode, 1) def test_help_lists_every_rule(self): helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]: self.assertIn(f" {rule}\n The rule: ", helped)