Answer architecture round 1: share one shell parser with reading-cost, move each pure step into rules.py and split the long units, build --help from RULES, log an override only once its call goes through and in the checkout it touched, list overrides by commit, return git failures as values with fsmonitor off, make the override review a pass with its own agent, record the decision, and restate in CLAUDE.md what the hook cannot see

This commit is contained in:
2026-10-12 23:45:36 +02:00
parent 7cf4f54c90
commit f3bfff1af4
17 changed files with 504 additions and 289 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
import re
CAP = 3
PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose")
PASSES = ("architecture", "full scan", "security", "overrides", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
+2 -1
View File
@@ -3,7 +3,8 @@ import dataclasses
import re
from claude_code.entries import assistant_parts, parse_entry, tool_call
from reading_cost.shell_reads import Reads, resolved, shell_reads
from reading_cost.shell_reads import Reads, shell_reads
from shell_command import resolved
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-C\s+\S+\s+)?commit\b")
+5 -46
View File
@@ -2,8 +2,8 @@
import dataclasses
import posixpath
import re
import shlex
import typing
from shell_command import resolved, simple_commands
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
# Their first operand is a pattern or a program, unless -e or -f gives it.
@@ -21,49 +21,12 @@ class Reads:
def shell_reads(command: str, cwd: str, home: str) -> Reads:
read: list[str] = []
added: list[str] = []
base = cwd
for tokens in shell_lines(command):
for words in segments(tokens):
if words[0] == "cd" and len(words) == 2:
base = resolved(base, words[1], home)
read += [resolved(base, word, home) for word in operands(words)]
added += [resolved(base, path, home) for path in worktree_added(words)]
for simple in simple_commands(command, cwd, home):
read += [resolved(simple.directory, word, home) for word in operands(simple.words)]
added += [resolved(simple.directory, path, home) for path in worktree_added(simple.words)]
return Reads(read, added)
def shell_lines(command: str) -> typing.Iterator[list[str]]:
"""Each line's tokens, skipping a heredoc's body, which feeds a program."""
ends = None
for line in command.splitlines():
if ends is not None:
ends = None if line.strip() == ends else ends
continue
try:
lexer = shlex.shlex(line, posix=True, punctuation_chars=True)
lexer.whitespace_split = True
tokens = list(lexer)
except ValueError:
continue
# The lexer splits <<-EOF into << and -EOF.
ends = next((tokens[index + 1].removeprefix("-") for index, token in enumerate(tokens[:-1]) if token == "<<"), None)
yield tokens
def segments(tokens: list[str]) -> list[list[str]]:
found: list[list[str]] = [[]]
target = False
for token in tokens:
if target:
target = False
elif all(char in "();<>|&" for char in token):
# A redirect's target is not an operand, so it does not count as a read.
target = "<" in token or ">" in token
found.append([])
else:
found[-1].append(token)
return [words for words in found if words]
def operands(words: list[str]) -> list[str]:
program = posixpath.basename(words[0])
if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)):
@@ -85,7 +48,3 @@ def worktree_added(words: list[str]) -> list[str]:
elif not word.startswith("-"):
return [word]
return []
def resolved(base: str, path: str, home: str) -> str:
return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path))
+1 -1
View File
@@ -15,5 +15,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+95 -89
View File
@@ -1,24 +1,14 @@
"""Block a Claude Code tool call that breaks a checkable rule, unless the call overrides the rule.
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
rule-hook overrides (prints this branch's overrides)
rule-hook overrides (prints this chunk's overrides)
settings.json runs it before each Bash, Edit, MultiEdit and Write call, in every session and
subagent. The rules:
action-pin a workflow's or action.yml's `uses:` names a semver tag, such as @v3 or @v3.1.2
commit-one-line git commit takes its message as one -m with no newline
ignorefile-sorted an edit leaves each block of a .*ignore file sorted, unless the block was
unsorted before; a blank line or comment ends a block
image-pin a Dockerfile FROM or COPY --from, or a compose or workflow `image:` or
`container:`, names a full patch version, a date stamp or a digest
no-ai-attribution no Claude or Anthropic co-author or generated-with line, in a file written or
in a git, gh or tea command
todo-rank-check a git commit while todo.md has changes, staged or not, needs
rank_todo.py --check to pass on it
{rules}
action-pin, ignorefile-sorted, image-pin and no-ai-attribution check only what an Edit, MultiEdit or
Write call writes, not a file a Bash command writes.
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
A call overrides a rule with `# rule-override <rule>: <reason>`:
@@ -26,14 +16,17 @@ A call overrides a rule with `# rule-override <rule>: <reason>`:
- in a file, as a comment line in the text the edit writes
- in Markdown, as `<!-- rule-override <rule>: <reason> -->`
Each override that let a call through is appended to
rule-overrides.tsv in the checkout's git directory: UTC time, branch, rule, reason, and the file
written or the command's first line. `rule-hook overrides` prints the lines for the current branch.
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 whose commit the current branch holds, from where it left
the default branch on.
Run with no arguments in a terminal, it prints this help.
Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call; 0 otherwise.
Exit 1, a non-blocking error to Claude Code, on input it cannot read.
Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call, or when an
override cannot be logged; 0 otherwise. Exit 1, a non-blocking error to Claude Code, on input it
cannot read.
"""
import json
import os
@@ -41,10 +34,11 @@ import pathlib
import subprocess
import sys
import time
import typing
from rule_hook.rules import Breach, command_breaches, commits, file_breaches, overrides, RULES
from rule_hook.rules import applied, Breach, command_breaches, commits, file_breaches, FILE_TOOLS, parsed_call, rules_help, text, verdict
from failure import Failure
import rank_todo
from shell_command import simple_commands
from utc_stamp import utc
LOG = "rule-overrides.tsv"
@@ -52,7 +46,7 @@ LOG = "rule-overrides.tsv"
def main(argv: list[str], stdin: str) -> int:
if argv in (["-h"], ["--help"]) or not argv and not stdin:
print(__doc__.strip())
print(__doc__.strip().replace("{rules}", rules_help()))
return 0
if argv == ["overrides"]:
return print_overrides(os.getcwd())
@@ -60,97 +54,109 @@ def main(argv: list[str], stdin: str) -> int:
print(f"unknown arguments: {' '.join(argv)}; see rule-hook --help", file=sys.stderr)
return 1
try:
call = json.loads(stdin)
tool, given, cwd = call["tool_name"], call["tool_input"], call["cwd"]
if not isinstance(given, dict):
raise TypeError("tool_input is no object")
except (json.JSONDecodeError, KeyError, TypeError) as failure:
print(f"rule-hook cannot read the hook input: {failure}", file=sys.stderr)
call = parsed_call(json.loads(stdin))
except json.JSONDecodeError as failure:
call = Failure(str(failure))
if isinstance(call, Failure):
print(f"rule-hook cannot read the hook input: {call.reason}", file=sys.stderr)
return 1
checked = checked_call(tool, given, cwd)
if checked is None:
return 0
text, directory, breaches = checked
what = text.split("\n", 1)[0] if tool == "Bash" else str(given.get("file_path"))
granted, malformed = overrides(text)
for breach in breaches:
if breach.rule in granted:
log_override(directory, breach.rule, granted[breach.rule], what)
blocking = [breach for breach in breaches if breach.rule not in granted]
if not blocking:
return 0
where = "the command" if tool == "Bash" else "the text you write, as a comment line"
markdown = tool != "Bash" and str(given.get("file_path")).endswith(".md")
for marker in malformed:
print(f"`{marker}` names no rule below, or gives no reason.", file=sys.stderr)
for rule in sorted({breach.rule for breach in blocking}):
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
print(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule]}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.", file=sys.stderr)
return 2
def checked_call(tool: str, given: dict[str, typing.Any], cwd: str) -> tuple[str, str, list[Breach]] | None:
"""The text that may carry an override, the directory whose checkout logs it, and the call's breaches."""
if tool == "Bash":
command = str(given.get("command") or "")
todo = [breach for commit in commits(command, cwd) for breach in todo_breaches(commit.directory)]
return command, cwd, command_breaches(command, cwd) + todo
path = str(given.get("file_path") or "")
if tool not in ("Edit", "MultiEdit", "Write") or not path:
return None
before = read(path)
edits = [given] if tool == "Edit" else [edit for edit in given.get("edits") or [] if isinstance(edit, dict)]
if tool == "Write":
added = after = str(given.get("content") or "")
home = os.path.expanduser("~")
bash = call.tool == "Bash"
path = text(call.given, "file_path")
if bash:
written = text(call.given, "command")
breaches = bash_breaches(written, call.cwd, home)
what = written.split("\n", 1)[0]
elif call.tool in FILE_TOOLS and path:
before = read(path)
written, after = applied(call, before)
breaches = file_breaches(path, before, written, after)
what = path
else:
after = before
for edit in edits:
old, new = str(edit.get("old_string") or ""), str(edit.get("new_string") or "")
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
added = "\n".join(str(edit.get("new_string") or "") for edit in edits)
return added, os.path.dirname(path), file_breaches(path, before, added, after)
return 0
judged = verdict(breaches, written, path.endswith(".md"), bash)
for message in judged.messages:
print(message, file=sys.stderr)
if judged.blocked:
return 2
for breach, reason in judged.overridden:
unlogged = log_override(breach, reason, what, time.time())
if unlogged:
print(f"rule-hook cannot log the override of {breach.rule}, so it would escape review: {unlogged.reason}", file=sys.stderr)
return 2
return 0
def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
simples = simple_commands(command, cwd, home)
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in todo_breaches(commit.directory)]
def todo_breaches(directory: str) -> list[Breach]:
top = git(directory, "rev-parse", "--show-toplevel")
if not top or not (pathlib.Path(top) / "todo.md").is_file():
if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file():
return []
# Any change, staged or not: the hook runs before a `git add` earlier in the same command.
if not git(top, "status", "--porcelain", "--", "todo.md"):
return []
return [Breach("todo-rank-check", line) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")]
changed = git(top, "status", "--porcelain", "--", "todo.md")
if isinstance(changed, Failure):
return [Breach("todo-rank-check", changed.reason, top)]
return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(pathlib.Path(top) / "todo.md")] if changed else []
def log_override(directory: str, rule: str, reason: str, what: str) -> None:
common = git(existing(directory), "rev-parse", "--path-format=absolute", "--git-common-dir")
if not common:
return
branch = git(existing(directory), "branch", "--show-current") or "HEAD"
with open(pathlib.Path(common) / LOG, "a", encoding="utf-8") as log:
log.write("\t".join([utc(time.time()), branch, rule, " ".join(reason.split()), " ".join(what.split())]) + "\n")
def log_override(breach: Breach, reason: str, what: str, now: float) -> Failure | None:
directory = existing(breach.directory)
if not any((parent / ".git").exists() for parent in [pathlib.Path(directory), *pathlib.Path(directory).parents]):
return None
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
branch = git(directory, "branch", "--show-current")
for found in (common, branch):
if isinstance(found, Failure):
return found
# Empty on a branch with no commit yet.
head = git(directory, "rev-parse", "--verify", "--quiet", "HEAD")
try:
with open(pathlib.Path(str(common)) / LOG, "a", encoding="utf-8") as log:
log.write("\t".join([utc(now), str(branch) or "HEAD", "" if isinstance(head, Failure) else head, breach.rule, " ".join(reason.split()), " ".join(what.split())]) + "\n")
except OSError as failure:
return Failure(str(failure))
return None
def print_overrides(directory: str) -> int:
common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir")
branch = git(directory, "branch", "--show-current")
if not common or not branch:
print("rule-hook overrides runs on a branch of a git checkout", file=sys.stderr)
if isinstance(common, Failure):
print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr)
return 1
start = branch_start(directory)
log = pathlib.Path(common) / LOG
lines = log.read_text(encoding="utf-8").splitlines() if log.is_file() else []
for line in lines:
if line.split("\t")[1:2] == [branch]:
commit = line.split("\t")[2:3]
if commit == [""] or commit and holds(directory, "HEAD", commit[0]) and (start is None or holds(directory, commit[0], start)):
print(line)
return 0
def git(directory: str, *args: str) -> str:
def branch_start(directory: str) -> str | None:
"""Where HEAD left the default branch, None when no default branch is known."""
for default in ("origin/HEAD", "main", "master"):
start = git(directory, "merge-base", "HEAD", default)
if not isinstance(start, Failure):
return start
return None
def holds(directory: str, descendant: str, ancestor: str) -> bool:
return not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)
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.
try:
ran = subprocess.run(["git", "-C", directory, *args], capture_output=True, text=True)
except OSError:
return ""
return ran.stdout.strip() if ran.returncode == 0 else ""
ran = subprocess.run(["git", "-c", "core.fsmonitor=false", "-C", directory, *args], capture_output=True, 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()}")
def existing(directory: str) -> str:
+176 -104
View File
@@ -1,15 +1,45 @@
import dataclasses
import os
import posixpath
import re
import shlex
import typing
RULES = {
"action-pin": "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never to a branch, and to a commit SHA only in a pipeline that tests our own specific builds",
"commit-one-line": "a commit message is one line, prefixed with the ticket ID when the work has one",
"ignorefile-sorted": "each block of an ignore file is sorted, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
"image-pin": "a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day. An image that publishes no three-part tag, such as postgres:16.4, takes an override",
"no-ai-attribution": "no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
"todo-rank-check": "while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it",
from failure import Failure
from shell_command import resolved, Simple
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]
@dataclasses.dataclass(frozen=True)
class Rule:
holds: str
checked: str
RULES: dict[RuleName, Rule] = {
"action-pin": Rule(
"a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never to a branch, and to a commit SHA only in a pipeline that tests our own specific builds",
"`uses:` in a .github or .gitea workflow, or in action.yml",
),
"commit-one-line": Rule(
"a commit message is one line, prefixed with the ticket ID when the work has one",
"git commit takes its message as one -m with no line break; -F, a second -m and a heredoc are blocked",
),
"ignorefile-sorted": Rule(
"each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment",
"a .*ignore file; a block already unsorted before the edit is left alone",
),
"image-pin": Rule(
"a container image is pinned to its full patch version, such as node:24.18.1-bookworm-slim, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; an image that publishes no three-part tag, such as postgres:16.4, takes an override",
"a Dockerfile's FROM and COPY --from, and `image:` and `container:` in a compose file or workflow",
),
"no-ai-attribution": Rule(
"no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
"a git, gh or tea command, and any file written",
),
"todo-rank-check": Rule(
"while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it",
"a git commit in a checkout whose todo.md has changes",
),
}
OVERRIDE = re.compile(r"(?:#|<!--)\s*rule-override ([a-z-]+):([^\n]*?)(?=[ \t]*(?:#|<!--)\s*rule-override |$)", re.MULTILINE)
# [-] keeps this file from matching itself.
@@ -20,142 +50,180 @@ PATCH = re.compile(r"v?\d+\.\d+\.\d+(?:[-+_.].*)?|.*\d{8}.*")
FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+))?", re.IGNORECASE | re.MULTILINE)
COPIED = re.compile(r"^[ \t]*COPY[ \t].*?--from=(\S+)", re.IGNORECASE | re.MULTILINE)
IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?(?:image|container):[ \t]*[\"']?([^\s\"'#{]+)", re.MULTILINE)
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
SEPARATING = set("\n();&|")
# git's global options that take a value as the next word.
GIT_VALUED = {"-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"}
GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"}
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
@dataclasses.dataclass(frozen=True)
class Call:
tool: str
given: dict[str, typing.Any]
cwd: str
@dataclasses.dataclass(frozen=True)
class Breach:
rule: str
rule: RuleName
detail: str
# The checkout whose log records an override of this breach.
directory: str
@dataclasses.dataclass(frozen=True)
class Commit:
"""A `git commit` in a command: the directory it runs in, and its messages."""
directory: str
messages: list[str]
from_file: bool
def overrides(text: str) -> tuple[dict[str, str], list[str]]:
@dataclasses.dataclass(frozen=True)
class Verdict:
messages: list[str]
blocked: bool
# Each breach an override let through, with its reason; logged only when the call goes through.
overridden: list[tuple[Breach, str]]
def parsed_call(hook_input: object) -> Call | Failure:
if not isinstance(hook_input, dict):
return Failure("the hook input is no object")
tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd")
if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str):
return Failure("the hook input has no string tool_name and cwd and object tool_input")
return Call(tool, given, cwd)
def text(given: dict[str, typing.Any], key: str) -> str:
value = given.get(key)
return value if isinstance(value, str) else ""
def overrides(written: str) -> tuple[dict[str, str], list[str]]:
"""The rules the text overrides with their reasons, and the markers that name no rule or give no reason."""
given = [(rule, reason.strip().removesuffix("-->").strip()) for rule, reason in OVERRIDE.findall(text)]
given = [(rule, reason.strip().removesuffix("-->").strip()) for rule, reason in OVERRIDE.findall(written)]
granted = {rule: reason for rule, reason in given if rule in RULES and reason}
return granted, [f"rule-override {rule}: {reason}" for rule, reason in given if rule not in granted]
def segments(command: str) -> list[list[str]] | None:
"""The command's simple commands as words, with each heredoc's body dropped, or None when it does not parse."""
lexer = shlex.shlex(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command), posix=True, punctuation_chars="();<>|&\n")
lexer.whitespace = " \t\r"
lexer.whitespace_split = True
# shlex also ends a word at a # inside it, as in fix#2, which bash does not; after lexing, a quoted # cannot be told apart.
try:
words = list(lexer)
except ValueError:
return None
split: list[list[str]] = [[]]
for word in words:
# Unquoted, a run such as "&&\n" lexes as one word.
if word and set(word) <= SEPARATING:
split.append([])
else:
split[-1].append(word)
return [segment for segment in split if segment]
def verdict(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Verdict:
granted, malformed = overrides(written)
blocking = [breach for breach in breaches if breach.rule not in granted]
messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
where = "the command" if bash else "the text you write, as a comment line"
for rule in sorted({breach.rule for breach in blocking}):
details = "; ".join(breach.detail for breach in blocking if breach.rule == rule)
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.")
return Verdict(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
def commits(command: str, cwd: str) -> list[Commit]:
directory = cwd
def commits(simples: list[Simple], home: str) -> list[Commit]:
found = []
for segment in segments(command) or []:
if segment[0] == "cd" and len(segment) > 1:
directory = os.path.join(directory, os.path.expanduser(segment[1]))
assignments = next((at for at, word in enumerate(segment) if not ASSIGNMENT.match(word)), len(segment))
words = segment[assignments:]
commit = git_commit(words[1:], directory) if words[:1] == ["git"] else None
if commit:
found.append(commit)
for simple in simples:
invoked = git_subcommand(simple.words, simple.directory, home)
if invoked and invoked[0] == "commit":
found.append(Commit(invoked[2], *commit_message(invoked[1])))
return found
def git_commit(args: list[str], directory: str) -> Commit | None:
at = 0
while at < len(args) and args[at].startswith("-"):
if args[at] == "-C" and at + 1 < len(args):
directory = os.path.join(directory, os.path.expanduser(args[at + 1]))
at += 2 if args[at] == "-C" or args[at] in GIT_VALUED else 1
if args[at:at + 1] != ["commit"]:
def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, list[str], str] | None:
"""A git command's subcommand, its arguments and the directory it runs in, after git's own options such as -C."""
if words[:1] != ["git"]:
return None
messages: list[str] = []
args = iter(words[1:])
for word in args:
if word in GIT_VALUED:
value = next(args, "")
directory = resolved(directory, value, home) if word == "-C" else directory
elif not word.startswith("-"):
return word, list(args), directory
return None
def commit_message(args: list[str]) -> tuple[list[str], bool]:
"""git commit's messages, and whether it reads one from a file."""
messages = []
from_file = False
rest = args[at + 1:]
at = 0
while at < len(rest):
word = rest[at]
words = iter(args)
for word in words:
if word == "--":
break
if word in ("--message", "--file") and at + 1 < len(rest):
messages += [rest[at + 1]] if word == "--message" else []
from_file = from_file or word == "--file"
at += 2
name, equals, value = word.partition("=")
if name in ("--message", "--file"):
given = value if equals else next(words, "")
elif word.startswith("-") and not word.startswith("--") and (flags := [flag for flag in word[1:] if flag in "mF"]):
# A cluster such as -am: the valued flag takes the rest of the word, or else the next word.
name = "--message" if flags[0] == "m" else "--file"
given = word[word.index(flags[0]) + 1:] or next(words, "")
else:
continue
if word.startswith("--message="):
messages.append(word.removeprefix("--message="))
elif word.startswith("--file="):
from_file = True
elif word.startswith("-") and not word.startswith("--"):
# A cluster such as -am: a valued flag takes the rest of the word, or else the next word.
for place, flag in enumerate(word[1:], 1):
if flag in "mF":
value = word[place + 1:]
if not value and at + 1 < len(rest):
at += 1
value = rest[at]
messages += [value] if flag == "m" else []
from_file = from_file or flag == "F"
break
at += 1
return Commit(directory, messages, from_file)
messages += [given] if name == "--message" else []
from_file = from_file or name == "--file"
return messages, from_file
def command_breaches(command: str, cwd: str) -> list[Breach]:
def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
breaches = []
parsed = segments(command) or []
if any(word in ("gh", "git", "tea") for segment in parsed for word in segment[:1]):
if ATTRIBUTION.search(command):
breaches.append(Breach("no-ai-attribution", "the command carries an attribution"))
for commit in commits(command, cwd):
found = commits(simples, home)
if simples and any(simple.words[0] in ("gh", "git", "tea") for simple in simples) and ATTRIBUTION.search(command):
directory = found[0].directory if found else simples[0].directory
breaches.append(Breach("no-ai-attribution", "the command carries an attribution", directory))
for commit in found:
if commit.from_file:
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file"))
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file", commit.directory))
elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages):
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline"))
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline", commit.directory))
return breaches
def applied(call: Call, before: str) -> tuple[str, str]:
"""The text a file call writes, and the whole file it leaves."""
if call.tool == "Write":
content = text(call.given, "content")
return content, content
edits = [call.given] if call.tool == "Edit" else [edit for edit in call.given.get("edits") or [] if isinstance(edit, dict)]
after = before
for edit in edits:
old, new = text(edit, "old_string"), text(edit, "new_string")
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
return "\n".join(text(edit, "new_string") for edit in edits), after
def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
"""Breaches in an edit of path: added is the text the edit writes, after the whole file it leaves."""
name = os.path.basename(path)
breaches = []
if ATTRIBUTION.search(added):
breaches.append(Breach("no-ai-attribution", f"{path} would carry an attribution"))
breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else []
return breaches + image_breaches(path, before, added, after) + action_breaches(path, added) + ignore_breaches(path, before, after)
def image_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
name = posixpath.basename(path)
if name.startswith(("Dockerfile", "Containerfile")) or name.endswith((".dockerfile", ".Dockerfile", ".containerfile")):
stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage}
images = [image for image, _ in FROM.findall(added)] + COPIED.findall(added)
breaches += [Breach("image-pin", f"{path}: {image}") for image in images if image.lower() not in stages | {"scratch"} and not image.isdigit() and not pinned(image)]
workflow = any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or name in ("action.yml", "action.yaml")
if "compose" in name and name.endswith((".yml", ".yaml")) or workflow:
breaches += [Breach("image-pin", f"{path}: {image}") for image in IMAGE.findall(added) if not pinned(image)]
if workflow:
breaches += [Breach("action-pin", f"{path}: uses: {action}") for action in USES.findall(added) if not tagged(action)]
if name.startswith(".") and name.endswith("ignore"):
already = [block for block in blocks(before) if block != sorted(block)]
breaches += [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} in code-point order, as LC_ALL=C sort does: {', '.join(sorted(block))}") for block in blocks(after) if block != sorted(block) and block not in already]
return breaches
stages = {stage.lower() for _, stage in FROM.findall(before + "\n" + after) if stage} | {"scratch"}
images = [image for image, _ in FROM.findall(added) if image.lower() not in stages] + [image for image in COPIED.findall(added) if image.lower() not in stages and not image.isdigit()]
elif "compose" in name and name.endswith((".yml", ".yaml")) or workflow(path):
images = IMAGE.findall(added)
else:
images = []
return [Breach("image-pin", f"{path}: {image}", posixpath.dirname(path)) for image in images if not pinned(image)]
def action_breaches(path: str, added: str) -> list[Breach]:
actions = USES.findall(added) if workflow(path) else []
return [Breach("action-pin", f"{path}: uses: {action}", posixpath.dirname(path)) for action in actions if not tagged(action)]
def ignore_breaches(path: str, before: str, after: str) -> list[Breach]:
name = posixpath.basename(path)
if not (name.startswith(".") and name.endswith("ignore")):
return []
already = [block for block in blocks(before) if block != sorted(block)]
return [Breach("ignorefile-sorted", f"{path}: sort the block {block[0]!r} through {block[-1]!r} as {', '.join(sorted(block))}", posixpath.dirname(path)) for block in blocks(after) if block != sorted(block) and block not in already]
def workflow(path: str) -> bool:
return any(folder in "/" + path for folder in ("/.github/workflows/", "/.gitea/workflows/")) or posixpath.basename(path) in ("action.yml", "action.yaml")
def pinned(image: str) -> bool:
@@ -171,12 +239,16 @@ def tagged(action: str) -> bool:
return "@" in action and SEMVER.fullmatch(action.rsplit("@", 1)[1]) is not None
def blocks(text: str) -> list[list[str]]:
def blocks(written: str) -> list[list[str]]:
"""An ignore file's runs of patterns, split at each blank line and comment."""
runs: list[list[str]] = [[]]
for line in text.splitlines():
for line in written.splitlines():
if line.strip() and not line.startswith("#"):
runs[-1].append(line)
elif runs[-1]:
runs.append([])
return [run for run in runs if run]
def rules_help() -> str:
return "\n".join(f" {name}\n The rule: {rule.holds}.\n Checked in: {rule.checked}." for name, rule in RULES.items())
+79 -39
View File
@@ -7,9 +7,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from rule_hook.rules import blocks, Breach, command_breaches, Commit, commits, file_breaches, overrides
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.
@@ -20,6 +21,14 @@ 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)
@@ -30,56 +39,54 @@ def git(cwd: str, *args: str) -> str:
class Commits(unittest.TestCase):
def test_cd_and_dash_capital_c_move_the_commit(self):
self.assertEqual(commits("cd a && git -C b commit -am 'x'", "/r"), [Commit("/r/a/b", ["x"], False)])
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(commits("git commit --message=a -m b=c --message c -mz", "/r")[0].messages, ["a", "b=c", "c", "z"])
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.assertTrue(commits("git commit -F - <<EOF\nx\nEOF", "/r")[0].from_file)
self.assertEqual(commit_message(["-F", "-"]), ([], True))
self.assertEqual(commit_message(["--file=x"]), ([], True))
def test_other_git_commands_are_no_commit(self):
self.assertEqual(commits("git log --grep commit; echo git commit", "/r"), [])
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(commits("cat <<EOF > notes\nhello\nEOF\ngit commit -m a", "/r")), 1)
self.assertEqual(len(commits("git status &&\n\ngit commit -m a", "/r")), 1)
def test_an_empty_argument_separates_nothing(self):
self.assertEqual(rules(command_breaches("git commit --author '' -m a -m b", "/r")), ["commit-one-line"])
self.assertEqual(len(committed("cat <<EOF > 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(commits("echo $((1<<2))\ngit commit -m a\n2", "/r")), 1)
self.assertEqual(len(committed("echo $((1<<2))\ngit commit -m a\n2")), 1)
def test_a_line_break_separates_commands(self):
self.assertEqual(commits("cd a\nGIT_EDITOR=true git commit -m x", "/r"), [Commit("/r/a", ["x"], False)])
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(command_breaches("git add . && git commit -m 'ABC-1 - Fix it'", "/r"), [])
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'\nTitle\nEOF\n)\"", "git commit -m a -m b", "git commit -F msg.txt"]:
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(rules(command_breaches(command, "/r")), ["commit-one-line"])
self.assertEqual(checked(command), ["commit-one-line"])
def test_an_attribution_breaks_only_in_a_git_gh_or_tea_command(self):
self.assertEqual(rules(command_breaches(f"tea pr create --description '{TRAILER}'", "/r")), ["no-ai-attribution"])
self.assertEqual(command_breaches(f"grep -rn '{TRAILER}' .", "/r"), [])
self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"])
self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), [])
def test_a_heredoc_body_is_no_shell_text(self):
self.assertEqual(rules(command_breaches("git commit -F - <<'EOF'\nTitle\n\nIt's the body\nEOF\necho done", "/r")), ["commit-one-line"])
self.assertEqual(rules(command_breaches("git commit -m \"$(cat <<'EOF'\nIt's one line\nEOF\n)\"", "/r")), ["commit-one-line"])
def test_a_command_that_does_not_parse_breaks_nothing(self):
self.assertEqual(command_breaches("git commit -m 'open", "/r"), [])
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_or_a_digest(self):
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("Dockerfile", "", added, added)], ["Dockerfile: node:24", "Dockerfile: python", "Dockerfile: alpine:3"])
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"), [])
@@ -111,15 +118,33 @@ 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("<!-- rule-override no-ai-attribution: quotes the banned line -->")[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("`<!-- rule-override no-ai-attribution: <reason> -->`", 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", "chunk")
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)
@@ -127,12 +152,26 @@ class Hook(unittest.TestCase):
self.assertIn("Blocked by rule image-pin: ", ran.stderr)
self.assertIn("`# rule-override image-pin: <reason>`", ran.stderr)
def test_an_override_passes_and_is_listed_for_its_branch(self):
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, ""))
listed = subprocess.run([str(HOOK), "overrides"], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout
self.assertRegex(listed, r"^\S+Z\tchunk\timage-pin\tthe vendor tags no patch versions\t\S+/sub/Dockerfile\n$")
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, past the chunk's start, holds no override")
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")
@@ -141,8 +180,8 @@ class Hook(unittest.TestCase):
def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self):
pathlib.Path(self.repo, "docs").mkdir()
for name, text in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]:
pathlib.Path(self.repo, name).write_text(text)
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"}
@@ -156,17 +195,18 @@ class Hook(unittest.TestCase):
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_markdown_file_is_told_the_html_comment(self):
ran = hook({"cwd": self.repo, "tool_input": {"content": TRAILER, "file_path": f"{self.repo}/a.md"}, "tool_name": "Write"}, self.repo)
self.assertIn("`<!-- rule-override no-ai-attribution: <reason> -->`", 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)
self.assertEqual(hook({"cwd": self.repo, "tool_input": None, "tool_name": "Bash"}, self.repo).returncode, 1)
def test_unreadable_input_does_not_block(self):
ran = subprocess.run([str(HOOK)], capture_output=True, env=isolated_env(), input="{", text=True)
self.assertEqual(ran.returncode, 1)
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)
+89
View File
@@ -0,0 +1,89 @@
"""A shell command's simple commands, each as its words and the directory it runs in."""
import dataclasses
import posixpath
import re
import shlex
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
OPERATOR = set("\n();&|<>")
@dataclasses.dataclass(frozen=True)
class Simple:
words: list[str]
directory: str
def simple_commands(command: str, cwd: str, home: str) -> list[Simple]:
"""Each simple command, without leading variable assignments or redirect targets, in the directory `cd` left it in."""
directory = cwd
found = []
for words in segments(command):
if words[0] == "cd" and len(words) == 2:
directory = resolved(directory, words[1], home)
found.append(Simple(words, directory))
return found
def segments(command: str) -> list[list[str]]:
text = uncommented(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command))
tokens = lexed(text)
if tokens is None:
# One unbalanced quote should not hide the other lines.
tokens = [token for line in text.splitlines() for token in (lexed(line) or []) + ["\n"]]
found: list[list[str]] = [[]]
target = False
for token in tokens:
if target:
target = False
elif set(token) <= OPERATOR and token:
# A redirect's target is not an operand.
target = "<" in token or ">" in token
found.append([])
elif found[-1] or not ASSIGNMENT.match(token):
found[-1].append(token)
return [words for words in found if words]
def lexed(text: str) -> list[str] | None:
lexer = shlex.shlex(text, posix=True, punctuation_chars="();<>|&\n")
lexer.commenters = ""
lexer.whitespace = " \t\r"
lexer.whitespace_split = True
try:
return list(lexer)
except ValueError:
return None
def uncommented(text: str) -> str:
"""The text without its comments; shlex's own would also swallow the line break that ends one, joining two commands."""
kept = []
quote = ""
at = 0
while at < len(text):
char = text[at]
if quote:
if char == "\\" and quote == '"':
kept.append(text[at:at + 2])
at += 2
continue
quote = "" if char == quote else quote
elif char == "\\":
kept.append(text[at:at + 2])
at += 2
continue
elif char in "'\"":
quote = char
elif char == "#" and (at == 0 or text[at - 1] in " \t\n;&|()"):
end = text.find("\n", at)
at = len(text) if end < 0 else end
continue
kept.append(char)
at += 1
return "".join(kept)
def resolved(base: str, path: str, home: str) -> str:
return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path))