Answer architecture round 3: list an override only when the current branch's reflog holds its commit, so no sibling or squash-merged branch's override returns, open the log without blocking on a FIFO, and unpack the call's breaches by name
This commit is contained in:
+21
-12
@@ -19,8 +19,8 @@ A call overrides a rule with `# rule-override <rule>: <reason>`:
|
||||
Each override that let a call through is appended to rule-overrides.tsv in the git directory of
|
||||
the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file
|
||||
written or the command's first line. An override outside any git checkout is not logged.
|
||||
`rule-hook overrides` prints the lines logged on the current branch, and those whose commit the
|
||||
default branch does not hold.
|
||||
`rule-hook overrides` prints the lines whose commit the current branch's reflog holds: those the
|
||||
default branch lacks, and those logged under the branch's own name.
|
||||
|
||||
Run with no arguments in a terminal, it prints this help.
|
||||
|
||||
@@ -65,7 +65,10 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr)
|
||||
return 1
|
||||
found = breaches_of(call, os.path.expanduser("~"))
|
||||
return answer(verdict(found[2], found[0], text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), found[1], time.time()) if found else 0
|
||||
if found is None:
|
||||
return 0
|
||||
written, what, breaches = found
|
||||
return answer(verdict(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time())
|
||||
|
||||
|
||||
def breaches_of(call: Call, home: str) -> tuple[str, str, list[Breach]] | None:
|
||||
@@ -89,9 +92,10 @@ def answer(judged: Verdict, what: str, now: float) -> int:
|
||||
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in judged.overridden]
|
||||
# Resolve every log before writing any, so a call that ends blocked has logged nothing.
|
||||
unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)]
|
||||
for breach, reason, log in logs if not unloggable else []:
|
||||
unwritten = write_override(log, breach, reason, what, now) if isinstance(log, Log) else None
|
||||
unloggable += [f"{breach.rule}: {unwritten.reason}"] if unwritten else []
|
||||
if not unloggable:
|
||||
for breach, reason, log in logs:
|
||||
unwritten = write_override(log, breach, reason, what, now) if isinstance(log, Log) else None
|
||||
unloggable += [f"{breach.rule}: {unwritten.reason}"] if unwritten else []
|
||||
for unlogged in unloggable:
|
||||
print(f"rule-hook cannot log the override of {unlogged}; unlogged, it would escape review.", file=sys.stderr)
|
||||
return 2 if unloggable else 0
|
||||
@@ -145,8 +149,8 @@ def log_path(directory: str) -> Log | Failure | None:
|
||||
def write_override(log: Log, breach: Breach, reason: str, what: str, now: float) -> Failure | None:
|
||||
line = "\t".join([utc(now), log.branch, log.head, breach.rule, " ".join(reason.split()), " ".join(what.split())]) + "\n"
|
||||
try:
|
||||
# No symlink: the checkout, and so its git directory, may come from anyone.
|
||||
descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
# No symlink, and no FIFO to hang on: the checkout, and so its git directory, may come from anyone.
|
||||
descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure))
|
||||
try:
|
||||
@@ -166,12 +170,17 @@ def print_overrides(directory: str) -> int:
|
||||
print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr)
|
||||
return 1
|
||||
branch = git(directory, "branch", "--show-current")
|
||||
ref = branch if isinstance(branch, str) and branch else "HEAD"
|
||||
# The branch's reflog keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit.
|
||||
reflog = git(directory, "reflog", "show", "--format=%H", ref)
|
||||
walked = set(reflog.split()) if isinstance(reflog, str) else set()
|
||||
default = default_branch(directory)
|
||||
log = pathlib.Path(common) / LOG
|
||||
for line in log.read_text(encoding="utf-8").splitlines() if log.is_file() else []:
|
||||
fields = line.split("\t")
|
||||
# Too many beats too few: the overrides pass skips a line whose breach the branch no longer holds, while an amend or a rebase leaves a line's commit off HEAD.
|
||||
if fields[1:2] == [branch] or default is None or not holds(directory, default, fields[2] if len(fields) > 2 else ""):
|
||||
commit = fields[2] if len(fields) > 2 else ""
|
||||
# A commit the default branch holds is this branch's only while no commit of its own came yet, so the line must name the branch too.
|
||||
if commit == "" or commit in walked and (fields[1] == ref or default is None or not holds(directory, default, commit)):
|
||||
print(line)
|
||||
return 0
|
||||
|
||||
@@ -185,9 +194,9 @@ def holds(directory: str, descendant: str, ancestor: str) -> bool:
|
||||
|
||||
|
||||
def git(directory: str, *args: str) -> str | Failure:
|
||||
# fsmonitor off: the hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program.
|
||||
# The hook runs git in a checkout the call has not yet been allowed to touch, whose config could name a program: no fsmonitor, and no fetch of a partial clone's missing objects through its transport.
|
||||
try:
|
||||
ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-C", directory, *args], capture_output=True, text=True)
|
||||
ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never", "-C", directory, *args], capture_output=True, env={**os.environ, "GIT_NO_LAZY_FETCH": "1"}, text=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"git could not start: {failure}")
|
||||
return ran.stdout.strip() if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
|
||||
@@ -167,8 +167,19 @@ class Hook(unittest.TestCase):
|
||||
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")
|
||||
git(self.repo, "branch", "-m", "renamed")
|
||||
self.assertIn("\timage-pin\t", self.listed(), "the reflog keeps the amended commit")
|
||||
|
||||
def test_a_sibling_branch_s_override_is_not_listed(self):
|
||||
git(self.repo, "checkout", "-q", "-b", "sibling")
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "sibling 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, "checkout", "-q", "chunk")
|
||||
self.assertEqual(self.listed(), "")
|
||||
git(self.repo, "merge", "-q", "--squash", "sibling")
|
||||
git(self.repo, "commit", "-q", "--allow-empty", "-m", "squashed")
|
||||
self.assertEqual(self.listed(), "", "a squash merge brings in none of the sibling's commits")
|
||||
|
||||
def test_a_blocked_call_logs_no_override(self):
|
||||
command = f"git commit -m a -m '{TRAILER}' # rule-override no-ai-attribution: quotes it"
|
||||
|
||||
Reference in New Issue
Block a user