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

100 lines
4.3 KiB
Python

"""Bench cheap static metrics against the places a project's comprehension panel named as hardest.
usage: metric-bench [history]
Run it inside a project checkout. history defaults to docs/comprehension-history.md there. 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. Places that name no Python function or method, such as a section of a markdown file, are
counted as unmeasured.
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the
history cannot be read, a run's commit is missing, or no scoring run names a measured unit.
"""
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.places import resolved, scoring_runs
from metric_bench.python_units import python_units, Unit
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
top = git(["rev-parse", "--show-toplevel"], None)
if isinstance(top, Failure):
return failed(top)
history = pathlib.Path(argv[0]) if argv else pathlib.Path(top.strip(), "docs", "comprehension-history.md")
try:
text = history.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
return failed(Failure(f"could not read {history}: {failure}"))
rows = []
for run in scoring_runs(text):
tracked = git(["ls-tree", "-r", "--name-only", run.commit], top.strip())
if isinstance(tracked, Failure):
return failed(tracked)
units = commit_units(run.commit, tracked.split("\n"), top.strip())
if isinstance(units, Failure):
return failed(units)
log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top.strip())
if isinstance(log, Failure):
return failed(log)
if scores := bench(units, resolved(run.places, tracked.split("\n")), co_changed(log)):
rows.append((run.heading, scores))
if not rows:
return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures"))
print(table(rows))
return 0
def commit_units(commit: str, tracked: list[str], top: str) -> list[Unit] | Failure:
units = []
for path in tracked:
name = path.rsplit("/", 1)[-1]
if path.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in path.split("/")[:-1]:
source = git(["show", f"{commit}:{path}"], top)
if isinstance(source, Failure):
return source
units += python_units(path, source)
return units
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