163 lines
7.9 KiB
Python
163 lines
7.9 KiB
Python
"""Each chunk on a default branch, with the later chunks that fixed code it 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 answering a 🔴 that a reviewer marked `[misread]`. Chunks are cut as score-outcomes cuts them, and each counts at most once against each earlier chunk."""
|
|
import dataclasses
|
|
import re
|
|
import typing
|
|
|
|
from failure import Failure
|
|
from git_repo import file_at, git
|
|
from round_titles import title_counts
|
|
from score_outcomes.results import chunk_log, label, NOT_WORK, shipped
|
|
from utc_stamp import utc
|
|
|
|
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
|
|
FIXES = ("defect", "security")
|
|
# A todo.md row that may hold one of FIXES, as the extended regex `git log -G` takes; shipped confirms it.
|
|
FIX_ROW = r"[|] *(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]+")
|
|
# Runs git with the given arguments, in the checkout's top.
|
|
Run = typing.Callable[..., str | Failure]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Landed:
|
|
"""A chunk: its label as score-outcomes names it, its commit time, the titles of every commit it brought to the default branch, and the labels of the later chunks that fixed code it shipped, newest first."""
|
|
label: str
|
|
landed: str
|
|
titles: frozenset[str]
|
|
fixed_by: tuple[str, ...]
|
|
|
|
|
|
def later_fixes(default: str, cwd: str | None = None, guarded: bool = False, timeout: float | None = None) -> list[Landed] | Failure:
|
|
"""Each chunk on default's first-parent line, newest first, read in the checkout holding cwd, else the current directory, each git call run as `git` runs it with timeout and guarded."""
|
|
top = git("rev-parse", "--show-toplevel", cwd=cwd, timeout=timeout, guarded=guarded)
|
|
if isinstance(top, Failure):
|
|
return top
|
|
# Blame and a pathspec read a path from the current directory, and the diff names each from the top.
|
|
root = top.strip()
|
|
|
|
def run(*args: str) -> str | Failure:
|
|
return git(*args, cwd=root, timeout=timeout, guarded=guarded)
|
|
log = run("log", "--format=%x1e%H %h %ct %at %P%x1f%s", default)
|
|
if isinstance(log, Failure):
|
|
return log
|
|
shorts: dict[str, str] = {}
|
|
parents: dict[str, list[str]] = {}
|
|
titles: dict[str, str] = {}
|
|
headers: dict[str, str] = {}
|
|
for record in log.split("\x1e")[1:]:
|
|
header, _, title = record.rstrip("\n").partition("\x1f")
|
|
full, short, committed, authored, *above = header.split()
|
|
shorts[full], parents[full], titles[full] = short, above, title
|
|
headers[full] = " ".join([full, committed, authored, *above])
|
|
# git log prints the commit it starts from first.
|
|
line = [next(iter(parents))]
|
|
while parents[line[-1]]:
|
|
line.append(parents[line[-1]][0])
|
|
chunks = chunk_log([headers[commit] for commit in line])
|
|
owner = owners(chunks, line, parents)
|
|
changes = fixing_changes(chunks, owner, parents, titles, run, lambda revision: file_at(revision, "todo.md", root, timeout, guarded), default)
|
|
if isinstance(changes, Failure):
|
|
return changes
|
|
fixed: dict[int, set[int]] = {}
|
|
for index, before, tip in changes:
|
|
traced = traced_to(before, tip, run)
|
|
if isinstance(traced, Failure):
|
|
return traced
|
|
for commit in traced:
|
|
# A commit no chunk owns cannot be one before can reach; take it as the fixing chunk's own.
|
|
if owner.get(commit, index) > index:
|
|
fixed.setdefault(owner[commit], set()).add(index)
|
|
owned: dict[int, set[str]] = {}
|
|
for commit, index in owner.items():
|
|
owned.setdefault(index, set()).add(titles[commit])
|
|
names = [label(shorts[first], shorts[last]) for first, last, _, _ in chunks]
|
|
return [Landed(names[index], utc(time), frozenset(owned[index]), tuple(names[later] for later in sorted(fixed.get(index, ())))) for index, (_, _, time, _) in enumerate(chunks)]
|
|
|
|
|
|
def owners(chunks: list, line: list[str], parents: dict[str, list[str]]) -> dict[str, int]:
|
|
"""Each commit's chunk, as its index in chunks, newest first: the oldest chunk on the first-parent line whose commits reach it."""
|
|
at = {commit: place for place, commit in enumerate(line)}
|
|
owner: dict[str, int] = {}
|
|
for index in reversed(range(len(chunks))):
|
|
first, last, _, _ = chunks[index]
|
|
for commit in reversed(line[at[last]:at[first] + 1]):
|
|
unowned = [commit]
|
|
while unowned:
|
|
found = unowned.pop()
|
|
if found not in owner:
|
|
owner[found] = index
|
|
unowned += parents[found]
|
|
return owner
|
|
|
|
|
|
def fixing_changes(chunks: list, owner: dict[str, int], parents: dict[str, list[str]], titles: dict[str, str], run: Run, plan_at: typing.Callable[[str], str | Failure], default: str) -> list[tuple[int, str, str]] | Failure:
|
|
"""Each change that fixes a defect, as its chunk's index, the commit before it and its tip: the whole change of each chunk that ships a FIXES item, and each round commit answering a 🔴 a reviewer marked `[misread]`."""
|
|
touched = run("log", "--first-parent", f"-G{FIX_ROW}", "--format=%H", default, "--", "todo.md")
|
|
if isinstance(touched, Failure):
|
|
return touched
|
|
changes = []
|
|
for index in sorted({owner[commit] for commit in touched.split()}):
|
|
first, last, _, _ = chunks[index]
|
|
if not parents[first]:
|
|
continue
|
|
before = parents[first][0]
|
|
planned, after = plan_at(before), plan_at(last)
|
|
if isinstance(planned, Failure):
|
|
return planned
|
|
if isinstance(after, Failure):
|
|
return after
|
|
if any(item.exempt in FIXES for item in shipped(planned, after)):
|
|
changes.append((index, before, last))
|
|
for commit, title in titles.items():
|
|
counts = title_counts(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 parents[commit]:
|
|
changes.append((owner[commit], parents[commit][0], commit))
|
|
return changes
|
|
|
|
|
|
def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure:
|
|
"""The commits that last changed each line the change from before to tip removes or rewrites, outside the plan and the records."""
|
|
# The prefixes and options keep the checkout's diff config out of the output.
|
|
diff = run("diff", "-U0", "-M", "--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules", "--src-prefix=a/", "--dst-prefix=b/", before, tip)
|
|
if isinstance(diff, Failure):
|
|
return diff
|
|
traced: set[str] = set()
|
|
for path, spans in removed(diff).items():
|
|
if path in NOT_WORK:
|
|
continue
|
|
# An empty --ignore-revs-file drops a configured one, which blame fails on where the file is missing.
|
|
blame = run("blame", "--porcelain", "--no-textconv", "--ignore-revs-file=", *(f"-L{start},+{count}" for start, count in spans), before, "--", path)
|
|
if isinstance(blame, Failure):
|
|
return blame
|
|
traced |= blamed(blame)
|
|
return traced
|
|
|
|
|
|
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))}
|