import dataclasses import os import re import shlex # Each rule's why, which the block message gives. RULES = { "action-pin": "a GitHub or Gitea Action is pinned to a semver tag, such as @v3 or @v3.1.2, never a commit SHA or a branch; SHA-pin 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, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs", "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": "a committed todo.md passes ~/.claude/bin/rank_todo.py --check; run rank_todo.py on it", } OVERRIDE = re.compile(r"#\s*rule-override ([a-z-]+):[ \t]*(\S[^\n]*)") # [-] keeps this file from matching itself. ATTRIBUTION = re.compile(r"co-authored[-]by:[^\n]*\b(?:claude|anthropic)\b|generated with \[?claude code", re.IGNORECASE) SEMVER = re.compile(r"v?\d+(?:\.\d+){0,2}") PATCH = re.compile(r"v?\d+\.\d+\.\d+(?:[-+_.].*)?") FROM = re.compile(r"^[ \t]*FROM[ \t]+(?:--\S+[ \t]+)*(\S+)(?:[ \t]+AS[ \t]+(\S+))?", re.IGNORECASE | re.MULTILINE) IMAGE = re.compile(r"^[ \t]*(?:-[ \t]+)?image:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE) USES = re.compile(r"^[ \t]*(?:-[ \t]+)?uses:[ \t]*[\"']?([^\s\"'#]+)", re.MULTILINE) ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=") SEPARATORS = {"\n", "&&", "||", ";", "|", "&", "(", ")", ";;", "|&"} # git's global options that take a value as the next word. GIT_VALUED = {"-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"} @dataclasses.dataclass(frozen=True) class Breach: rule: str detail: str @dataclasses.dataclass(frozen=True) class Commit: """A `git commit` in a command: the directory it runs in, its messages and whether it stages tracked changes.""" directory: str messages: list[str] from_file: bool all: bool def overrides(text: str) -> dict[str, str]: return {rule: reason.strip() for rule, reason in OVERRIDE.findall(text) if rule in RULES} def segments(command: str) -> list[list[str]] | None: """The command's simple commands as words, or None when it does not parse.""" lexer = shlex.shlex(command, posix=True, punctuation_chars="();<>|&\n") lexer.whitespace = " \t\r" lexer.whitespace_split = True try: words = list(lexer) except ValueError: return None split: list[list[str]] = [[]] for word in words: if word in SEPARATORS: split.append([]) else: split[-1].append(word) return [segment for segment in split if segment] def commits(command: str, cwd: str) -> list[Commit]: directory = cwd 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) 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"]: return None messages: list[str] = [] from_file = staged_all = False rest = args[at + 1:] at = 0 while at < len(rest): word = rest[at] 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 continue if word.startswith("--message="): messages.append(word.removeprefix("--message=")) elif word.startswith("--file="): from_file = True elif word == "--all": staged_all = 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 staged_all = staged_all or flag == "a" at += 1 return Commit(directory, messages, from_file, staged_all) def command_breaches(command: str, cwd: 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): if commit.from_file: breaches.append(Breach("commit-one-line", "pass the message as one -m '', not from a file")) 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 '', with no heredoc, second -m or newline")) return breaches 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")) 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) if image.lower() not in stages | {"scratch"}] breaches += [Breach("image-pin", f"{path}: FROM {image}") for image in images if not pinned(image)] if name.endswith((".yml", ".yaml")): breaches += [Breach("image-pin", f"{path}: image: {image}") for image in IMAGE.findall(added) if not pinned(image)] 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"): breaches += [Breach("ignorefile-sorted", f"{path}: {block[0]!r} through {block[-1]!r} are out of order") for block in blocks(after) if block != sorted(block)] return breaches def pinned(image: str) -> bool: if "$" in image or "{{" in image or "@sha256:" in image: return True tail = image.rsplit("/", 1)[-1] return ":" in tail and PATCH.fullmatch(tail.split(":", 1)[1]) is not None def tagged(action: str) -> bool: if action.startswith(("./", "docker://")) or "$" in action or "{{" in action: return True return "@" in action and SEMVER.fullmatch(action.rsplit("@", 1)[1]) is not None def blocks(text: 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(): if line.strip() and not line.startswith("#"): runs[-1].append(line) elif runs[-1]: runs.append([]) return [run for run in runs if run]