"""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. 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.python_units import measured, python_units 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 given = pathlib.Path(argv[0]).resolve() if argv else None found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None) if isinstance(found, Failure): return failed(found) top = found.strip() history = given or pathlib.Path(top, "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): scores = run_scores(run, top) if isinstance(scores, Failure): return failed(scores) if scores: 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 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 = [] for path in filter(measured, tracked): source = git(["show", f"{run.commit}:{path}"], top) if isinstance(source, Failure): return source units += python_units(path, source) log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top) if isinstance(log, Failure): return log return bench(units, resolved(run.places, tracked), 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