182 lines
8.5 KiB
Python
182 lines
8.5 KiB
Python
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, or to a date-stamped tag or an @sha256: digest, so the same commit builds the same image on every day; a bot such as Renovate raises the bumps as reviewable PRs. 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": "a committed todo.md passes ~/.claude/bin/rank_todo.py --check",
|
|
}
|
|
OVERRIDE = re.compile(r"(?:#|<!--)\s*rule-override ([a-z-]+):([^\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}")
|
|
# Two-part tags such as postgres:16.4 stay blocked: the rule bans node:24.18, which reads the same, so such an image takes an override.
|
|
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"}
|
|
|
|
|
|
@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, and its messages."""
|
|
directory: str
|
|
messages: list[str]
|
|
from_file: bool
|
|
|
|
|
|
def overrides(text: str) -> dict[str, str]:
|
|
given = {rule: reason.strip().removesuffix("-->").strip() for rule, reason in OVERRIDE.findall(text)}
|
|
return {rule: reason for rule, reason in given.items() if rule in RULES and reason}
|
|
|
|
|
|
def segments(command: str) -> list[list[str]] | None:
|
|
"""The command's simple commands as words, each heredoc's body cut to a line break, 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 set(word) <= SEPARATING:
|
|
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 = 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.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)
|
|
|
|
|
|
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 '<line>', 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 '<line>', 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)] + 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
|
|
|
|
|
|
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]
|