Answer architecture round 1: 0 🔴, 3 🟡 (0 misread); move docker's parsing to bin/ for item 227's shim, read launchers once in shell_command.launched, and give the memory limit its own decision, sized to what the work needs

This commit is contained in:
2026-10-24 00:31:41 +02:00
parent 7b61fd5b4b
commit a292ec4cae
9 changed files with 89 additions and 67 deletions
+41
View File
@@ -0,0 +1,41 @@
"""What a docker command asks of docker: its subcommand, and whether a container it starts has a memory limit."""
import re
from shell_command import launched
# The options of docker, docker buildx and docker compose that take a value, so the value is not read as a subcommand.
DOCKER_VALUED = frozenset({"--ansi", "--builder", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "--tlscacert", "--tlscert", "--tlskey", "-c", "-f", "-H", "-l", "-p"})
# The subcommands that start a container, which takes the memory limit docker run's -m sets.
STARTS_CONTAINER = (["run"], ["create"], ["container", "run"], ["container", "create"])
# -m4g is -m with its value attached; --memory-swap alone sets no limit.
MEMORY_LIMIT = re.compile(r"-m.*|--memory(=.*)?")
def docker_subcommand(arguments: list[str]) -> list[str]:
"""The subcommand docker's arguments name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"]."""
positional: list[str] = []
skip = False
for word in arguments:
if skip:
skip = False
elif word.startswith("-"):
skip = word in DOCKER_VALUED
else:
positional.append(word)
if positional[0] not in ("buildx", "compose", "container") or len(positional) == 2:
break
return positional
def unlimited(arguments: list[str]) -> bool:
"""Whether docker's arguments start a container, with docker run or docker create, and set it no memory limit.
A --memory among the container's own arguments, past its image, reads as the limit too: telling it apart needs every value-taking option of docker run.
"""
return "--help" not in arguments and docker_subcommand(arguments) in STARTS_CONTAINER and not any(MEMORY_LIMIT.fullmatch(word) for word in arguments)
def unlimited_container(words: list[str]) -> bool:
"""Whether the simple command, directly or through a launcher, starts a container that has no memory limit."""
docker = launched(words, {"docker"})
return docker is not None and unlimited(docker.arguments)
-53
View File
@@ -1,53 +0,0 @@
"""What a simple command asks of docker, for rule-hook's rules: its subcommand, and whether a container it starts has a memory limit."""
import posixpath
import re
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run.
LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "uvx", "yarn"})
# The options of docker, docker buildx and docker compose that take a value, so the value is not read as a subcommand.
DOCKER_VALUED = frozenset({"--ansi", "--builder", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "--tlscacert", "--tlscert", "--tlskey", "-c", "-f", "-H", "-l", "-p"})
# The subcommands that start a container, which takes the memory limit docker run's -m sets.
STARTS_CONTAINER = (["run"], ["create"], ["container", "run"], ["container", "create"])
# -m4g is -m with its value attached; --memory-swap alone sets no limit.
MEMORY_LIMIT = re.compile(r"-m.*|--memory(=.*)?")
def tool_name(word: str) -> str:
"""The tool a word names, such as mutmut for `mutmut>=3,<4` or `.venv/bin/mutmut`; empty for a word that names none, such as a file name."""
named = re.fullmatch(r"([A-Za-z_-]+)(?:[<>=!~@].*)?", posixpath.basename(word))
return named.group(1) if named else ""
def docker_arguments(words: list[str]) -> list[str] | None:
"""The words after docker where the simple command runs it directly or through a launcher, as in nice -n 19 docker build .; None where it runs no docker."""
names = [tool_name(word) for word in words]
# Past a launcher, docker may follow the launcher's own options and assignments; without one, the command itself is the tool.
reachable = names if names[:1] and names[0] in LAUNCHERS else names[:1]
return words[reachable.index("docker") + 1:] if "docker" in reachable else None
def docker_subcommand(words: list[str]) -> list[str]:
"""The subcommand docker's words name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"]."""
positional: list[str] = []
skip = False
for word in words:
if skip:
skip = False
elif word.startswith("-"):
skip = word in DOCKER_VALUED
else:
positional.append(word)
if positional[0] not in ("buildx", "compose", "container") or len(positional) == 2:
break
return positional
def unlimited_container(words: list[str]) -> bool:
"""Whether the simple command starts a container through docker run or docker create, directly or through a launcher, and sets no memory limit.
A --memory among the container's own arguments, past its image, reads as the limit too: telling it apart needs every value-taking option of docker run.
"""
arguments = docker_arguments(words)
if arguments is None or "--help" in arguments:
return False
return docker_subcommand(arguments) in STARTS_CONTAINER and not any(MEMORY_LIMIT.fullmatch(word) for word in arguments)
+9 -9
View File
@@ -1,23 +1,23 @@
"""Whether a simple command is a heavy one, for the `run-heavy` rule: a docker build, or a run of a mutation tool."""
from rule_hook.docker_command import docker_arguments, docker_subcommand, LAUNCHERS, tool_name
from docker_command import docker_subcommand
from shell_command import launched, tool_name
# Each mutation tool, and the words that make its call a mutation run when one of them follows it within two words; where the set is empty, every call is one.
MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutmut": {"run"}, "stryker": {"run"}}
# Flags with which a tool only prints its help, version or list, so a call that carries one is light. Not -h, which docker run reads as the container's hostname.
LIGHT_FLAGS = frozenset({"--help", "--list", "--version"})
BUILDS = (["build"], ["buildx", "build"], ["compose", "build"])
def heavy(words: list[str]) -> bool:
"""Whether the simple command, run directly or through a launcher, is a docker build or a mutation run, or runs one in a container, and is not under run-heavy."""
names = [tool_name(word) for word in words]
if not names or "run-heavy" in names or LIGHT_FLAGS & set(words):
launch = launched(words, {"docker", *MUTATORS})
if launch is None or "run-heavy" in launch.launchers or LIGHT_FLAGS & set(words):
return False
docker = docker_arguments(words)
if docker is not None:
subcommand = docker_subcommand(docker)
return subcommand in (["build"], ["buildx", "build"], ["compose", "build"]) or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run(names[len(words) - len(docker):]))
# Past a launcher, the mutation tool may follow the launcher's own options, as in uvx --with pytest mutmut run.
return (names[0] in LAUNCHERS or names[0] in MUTATORS) and mutation_run(names)
if launch.tool == "docker":
subcommand = docker_subcommand(launch.arguments)
return subcommand in BUILDS or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run([tool_name(word) for word in launch.arguments]))
return mutation_run([launch.tool, *(tool_name(word) for word in launch.arguments)])
def mutation_run(names: list[str]) -> bool:
+3 -3
View File
@@ -8,7 +8,7 @@ from git_command import commits
from rule_hook.heavy_command import heavy
from review_folder import REPORTS
from shell_command import Simple
from rule_hook.docker_command import unlimited_container
from docker_command import unlimited_container
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
@@ -31,7 +31,7 @@ RULES: dict[RuleName, Rule] = {
"git commit takes its message as one -m with no line break; -F, a second -m and a heredoc are blocked",
),
"docker-run-memory": Rule(
"a container started with docker run or docker create has a memory limit, such as `--memory 4g --memory-swap 4g`, so one runaway container cannot starve the machine; --memory-swap equal to --memory keeps it out of swap",
"a container started with docker run or docker create has a memory limit, as large as its work needs, such as `--memory 4g --memory-swap 4g`, so one runaway container cannot starve the machine; --memory-swap equal to --memory keeps it out of swap",
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice. A container a script or docker compose starts is not checked",
),
"ignorefile-sorted": Rule(
@@ -138,7 +138,7 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre
if heavy(simple.words):
breaches.append(Breach("run-heavy", f"run `{' '.join(simple.words)[:80]}` under `~/.claude/bin/run-heavy`, in the background", simple.directory))
if unlimited_container(simple.words):
breaches.append(Breach("docker-run-memory", f"give `{' '.join(simple.words)[:80]}` a memory limit, such as `--memory 4g --memory-swap 4g`", simple.directory))
breaches.append(Breach("docker-run-memory", f"give `{' '.join(simple.words)[:80]}` a memory limit as large as its work needs, such as `--memory 4g --memory-swap 4g`", simple.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", commit.directory))
+28
View File
@@ -3,7 +3,10 @@ import dataclasses
import posixpath
import re
import shlex
import typing
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run.
LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "uvx", "yarn"})
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();&|<>")
@@ -13,6 +16,14 @@ REDIRECT = re.compile(r"&>>?|[<>]+[&|]?")
PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""", re.DOTALL)
@dataclasses.dataclass(frozen=True)
class Launch:
"""A tool a simple command runs: the launchers it runs through, such as nice and run-heavy, and the words it is given."""
launchers: frozenset[str]
tool: str
arguments: list[str]
@dataclasses.dataclass(frozen=True)
class Simple:
words: list[str]
@@ -80,3 +91,20 @@ def uncommented(text: str) -> str:
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))
def tool_name(word: str) -> str:
"""The tool a word names, such as mutmut for `mutmut>=3,<4` or `.venv/bin/mutmut`; empty for a word that names none, such as a file name."""
named = re.fullmatch(r"([A-Za-z_-]+)(?:[<>=!~@].*)?", posixpath.basename(word))
return named.group(1) if named else ""
def launched(words: list[str], tools: typing.Collection[str]) -> Launch | None:
"""The first of tools that the simple command runs, directly or through launchers; None where it runs none of them."""
names = [tool_name(word) for word in words]
# Past a launcher, the tool may follow the launcher's own options and assignments, as in nice -n 19 docker build; without one, the command itself is the tool.
reachable = names if names[:1] and names[0] in LAUNCHERS else names[:1]
at = next((i for i, name in enumerate(reachable) if name in tools), None)
if at is None:
return None
return Launch(frozenset(LAUNCHERS.intersection(names[:at])), names[at], words[at + 1:])