Files
claude-config/bin/branch_chunks/fixes.py
T

87 lines
4.5 KiB
Python

"""The later chunks that fixed code each chunk on a default branch shipped: its escaped defects.
A later chunk fixed code an earlier chunk shipped where one of its changes removes or rewrites lines that `git blame` traces to a commit the earlier chunk brought. Two kinds of change count: the chunk's whole change, where it ships a todo.md item marked `defect` or `security`; and a round commit of the chunk whose title counts both a 🔴 and a misread finding. Each later chunk counts at most once against each earlier chunk."""
import re
import typing
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
from plan.todo_table import Exempt, Item
from review_rules.round_titles import title_counts
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
FIXES: tuple[Exempt, ...] = ("defect", "security")
HUNK = re.compile(r"@@ -([0-9]+)(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@")
BLAME_HEADER = re.compile(r"([0-9a-f]{40}|[0-9a-f]{64}) [0-9]+ [0-9]+")
class FixingChange(typing.NamedTuple):
"""A change that fixes a defect: the index of its chunk, the commit before it and its tip."""
chunk: int
before: str
tip: str
class Traced(typing.NamedTuple):
"""The commits that last changed the lines a fixing change removes, with the index of the change's chunk."""
chunk: int
commits: set[str]
def fixing_changes(branch: Branch, shipped: list[tuple[Item, ...]]) -> list[FixingChange]:
"""Each change that fixes a defect: the whole change of each chunk that ships a FIXES item, as shipped_by lists them, and each round commit whose title counts both a 🔴 and a misread finding."""
changes = []
for index, (chunk, items) in enumerate(zip(branch.chunks, shipped)):
if chunk.before is not None and any(item.exempt in FIXES for item in items):
changes.append(FixingChange(index, chunk.before, chunk.tip))
for commit in branch.commits.values():
counts = title_counts(commit.title)
# A title counts misread 🔴 and 🟡 findings together, so it takes one with both a 🔴 and a misread finding to answer a misread 🔴.
if counts and counts.red and counts.misread and commit.parents:
changes.append(FixingChange(branch.owner[commit.hash], commit.parents[0], commit.hash))
return changes
def with_fixes(branch: Branch, shipped: list[tuple[Item, ...]], traced: list[Traced]) -> list[BranchChunk]:
"""The branch's chunks, each with the items it shipped, as shipped_by lists them, and the later chunks that fixed code it shipped, from the commits each fixing change traced to."""
fixed: dict[int, set[int]] = {}
for change in traced:
for commit in change.commits:
# Blame at a commit on the branch should name only commits its log holds; any other counts against no chunk. Chunks run newest first, so > keeps the chunks older than the fixing one.
if commit in branch.owner and branch.owner[commit] > change.chunk:
fixed.setdefault(branch.owner[commit], set()).add(change.chunk)
chunks = []
for index, (span, items) in enumerate(zip(branch.chunks, shipped)):
fixed_by = tuple(branch.chunks[later].label for later in sorted(fixed.get(index, ())))
chunks.append(BranchChunk(**vars(span), shipped=items, fixed_by=fixed_by))
return chunks
def removed_work(diff: str) -> dict[str, list[tuple[int, int]]]:
"""What removed reads from a `git diff -U0`, less the paths in NOT_WORK: the plan and the records."""
return {path: spans for path, spans in removed(diff).items() if path not in NOT_WORK}
def removed(diff: str) -> dict[str, list[tuple[int, int]]]:
"""The old lines each hunk of a `git diff -U0` removes or rewrites, as its first line and count, by the path the file had before; none for a path git quotes, as it does one holding a byte it cannot print."""
spans: dict[str, list[tuple[int, int]]] = {}
path, left = None, 0
for row in diff.splitlines():
if left and row[:1] in ("-", "+", " "):
left -= 1
elif row.startswith("diff --git "):
path, left = None, 0
elif row.startswith("--- "):
# Git ends a path holding a space with a tab.
path = row[len("--- a/"):].removesuffix("\t") if row.startswith("--- a/") else None
elif hunk := HUNK.match(row):
start, count = int(hunk.group(1)), int(hunk.group(2) or 1)
left = count + int(hunk.group(3) or 1)
if path and count:
spans.setdefault(path, []).append((start, count))
return spans
def blamed(porcelain: str) -> set[str]:
"""The commit each line of `git blame --porcelain` output comes from."""
return {header.group(1) for row in porcelain.splitlines() if (header := BLAME_HEADER.match(row))}