Files
claude-config/bin/metric_bench/main.py
T

133 lines
5.6 KiB
Python

"""Bench cheap static metrics against the places a project's comprehension panel named as hardest.
usage: metric-bench [history]
history defaults to docs/comprehension-history.md in the checkout it runs in, and the bench reads
the checkout that holds the history. For each scoring run in it, at the commit the seats read, it
measures every Python function and method git
tracks, test files left out: cognitive complexity (SonarSource's white paper, read for Python),
length in lines, shared state (attributes on self another method of the class also writes, plus
names declared global or nonlocal), and change spread (how many other files changed in a commit with
the unit's file, up to that commit). It then prints, for each metric, how well it ranks the units
the seats named above the rest: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share
of the metric's k highest units the seats named, k being how many they named). A last row gives the
medians. Unmeasured counts the distinct places that name no Python function or method, such as a
section of a markdown file, or no single tracked file.
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the
history cannot be read, a measured file does not parse, or no scoring run names a measured unit. A
run whose commit the checkout lacks, such as a deleted branch's, is skipped and named below the
table.
"""
import pathlib
import subprocess
import sys
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score
from failure import Failure
from metric_bench.python_units import measured, python_units, Unit
from metric_bench.places import resolved, scoring_runs, ScoringRun
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) > 1 or argv[:1] and argv[0].startswith("-"):
print(f"unknown arguments {' '.join(argv)}; usage: metric-bench [history]", file=sys.stderr)
return 1
read = read_history(pathlib.Path(argv[0]).resolve() if argv else None)
if isinstance(read, Failure):
return failed(read)
top, history, text = read
benched = bench_runs(text, top)
if isinstance(benched, Failure):
return failed(benched)
rows, gone = benched
if not rows:
return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md → \"History\"{skipped(gone, top)}"))
print(table(rows) + skipped(gone, top))
return 0
def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | Failure:
"""The checkout that holds the history, the history's path and its text."""
found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None)
if isinstance(found, Failure):
return found
history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md")
try:
return found.strip(), history, history.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {history}: {failure}")
def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[str]] | Failure:
"""Each scored run's heading and scores, and the headings of the runs whose commit the checkout lacks."""
rows = []
gone = []
for run in scoring_runs(text):
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
gone.append(f"{run.heading} ({missing.reason})")
continue
scores = run_scores(run, top)
if isinstance(scores, Failure):
return scores
if scores:
rows.append((run.heading, scores))
return rows, gone
def skipped(gone: list[str], top: str) -> str:
lines = [f"Skipped, its commit is not in {top}: {run}" for run in gone]
return "\n\n" + "\n".join(lines) if lines else ""
def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure:
listed = git(["ls-tree", "-r", "--name-only", run.commit], top)
if isinstance(listed, Failure):
return listed
tracked = listed.split("\n")
units: list[Unit] = []
for path in filter(measured, tracked):
source = git(["show", f"{run.commit}:{path}"], top)
if isinstance(source, Failure):
return source
found = python_units(path, source)
if isinstance(found, Failure):
return found
units += found
log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top)
if isinstance(log, Failure):
return log
named = list(dict.fromkeys(run.places))
places = resolved(named, tracked)
return bench(units, places, len(named) - len(places), co_changed(log))
def table(rows: list[tuple[str, RunScores]]) -> str:
head = ["Scoring run", "Units", "Named", "Unmeasured", *METRICS]
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
for heading, run in rows:
lines.append("| " + " | ".join([heading, str(run.units), str(run.named), str(run.unmeasured), *(cell(run.scores[metric]) for metric in METRICS)]) + " |")
medianed = medians([run for _, run in rows])
lines.append("| " + " | ".join(["Median", "", "", "", *(cell(medianed[metric]) for metric in METRICS)]) + " |")
return "\n".join(lines)
def cell(score: Score) -> str:
return f"AUC {score.auc:.2f}, top k {score.top_k:.2f}"
def git(args: list[str], cwd: str | None) -> str | Failure:
try:
ran = subprocess.run(["git", *args], capture_output=True, cwd=cwd, encoding="utf-8", errors="replace")
except OSError as failure:
return Failure(f"could not start git: {failure.strerror}")
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
def failed(failure: Failure) -> int:
print(failure.reason, file=sys.stderr)
return 1