From 6e5b5d1c3ae5e10cc2bc9eeecfd657ca04d455c5 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Fri, 27 Nov 2026 12:18:05 +0100 Subject: [PATCH] Add devstats: kuhy vs the 100x article MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `python -m devstats compare` walks ~/src, counts kuhy's default-branch commits once per piece of work (worktrees, clones and filter-repo copies folded in), drops lockfiles/generated/vendored/data via excludes.py, and prints 30/90/300-day net LoC/day, per-active-day vs 194, commits and tags beside the article's Cmdr figures. --write regenerates devstats/DOCS-comparison.md (aggregates only); --by-repo is terminal-only. Read-only: only rev-parse, for-each-ref and log, GIT_OPTIONAL_LOCKS=0. Bug-class-check: none — new tool, not a bug fix Co-Authored-By: Claude Opus 5.5 --- .github/workflows/shared-gates-tests.yml | 8 ++ CLAUDE.md | 8 +- README.md | 9 ++ devstats/DOCS-comparison.md | 53 +++++++++++ devstats/__init__.py | 1 + devstats/__main__.py | 5 + devstats/aggregate.py | 116 +++++++++++++++++++++++ devstats/article.py | 21 ++++ devstats/cli.py | 81 ++++++++++++++++ devstats/discover.py | 47 +++++++++ devstats/excludes.py | 83 ++++++++++++++++ devstats/gitcmd.py | 26 +++++ devstats/numstat.py | 91 ++++++++++++++++++ devstats/refs.py | 69 ++++++++++++++ devstats/render.py | 111 ++++++++++++++++++++++ devstats/tests/__init__.py | 0 devstats/tests/conftest.py | 110 +++++++++++++++++++++ devstats/tests/test_aggregate.py | 59 ++++++++++++ devstats/tests/test_cli.py | 109 +++++++++++++++++++++ devstats/tests/test_discover.py | 31 ++++++ devstats/tests/test_excludes.py | 68 +++++++++++++ devstats/tests/test_numstat.py | 81 ++++++++++++++++ devstats/tests/test_refs.py | 64 +++++++++++++ 23 files changed, 1247 insertions(+), 4 deletions(-) create mode 100644 devstats/DOCS-comparison.md create mode 100644 devstats/__init__.py create mode 100644 devstats/__main__.py create mode 100644 devstats/aggregate.py create mode 100644 devstats/article.py create mode 100644 devstats/cli.py create mode 100644 devstats/discover.py create mode 100644 devstats/excludes.py create mode 100644 devstats/gitcmd.py create mode 100644 devstats/numstat.py create mode 100644 devstats/refs.py create mode 100644 devstats/render.py create mode 100644 devstats/tests/__init__.py create mode 100644 devstats/tests/conftest.py create mode 100644 devstats/tests/test_aggregate.py create mode 100644 devstats/tests/test_cli.py create mode 100644 devstats/tests/test_discover.py create mode 100644 devstats/tests/test_excludes.py create mode 100644 devstats/tests/test_numstat.py create mode 100644 devstats/tests/test_refs.py diff --git a/.github/workflows/shared-gates-tests.yml b/.github/workflows/shared-gates-tests.yml index d1b9bce..7f3731b 100644 --- a/.github/workflows/shared-gates-tests.yml +++ b/.github/workflows/shared-gates-tests.yml @@ -72,6 +72,14 @@ jobs: --cov-report=term-missing \ --cov-fail-under=100 + # Its tests build throwaway repos with git, which the runner has. + - name: devstats — 100% branch coverage + run: | + PYTHONPATH=. python -m pytest devstats/tests -q \ + --cov=devstats --cov-branch \ + --cov-report=term-missing \ + --cov-fail-under=100 + # gate_stamp.sh is the pre-push gate in every repo. Its tests drive real # pre-commit in throwaway repos, and the hook-id helper runs under # /usr/bin/python3 (the deployment interpreter), hence apt's PyYAML. diff --git a/CLAUDE.md b/CLAUDE.md index c4f10e5..af8076d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,7 +1,7 @@ # utils Monorepo of shared gates and libraries (app_errors, dep_freshness, file_length, md_naming, -repo_contract, coverage_gaps, crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory, game_recording, +repo_contract, coverage_gaps, devstats, crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory, game_recording, flutter_web_drive (headless Flutter-web E2E driver + MCP), ...). `godot_dev_tools/` is a Godot addon (GDScript): `godot_dev_tools/test.sh` runs its GUT tests. `kuhy_credit/` is the shared "Created by kuhy" credit, one implementation per stack (web, Flutter, @@ -15,9 +15,9 @@ overwrite it with `repo_contract/templates/check_repo_contract.shim.sh`. ## Commands - run: n/a: collection of gates and libraries, no single entry point -- test: `PYTHONPATH=. python -m pytest -q agent_ready/tests coverage_gaps/tests dep_freshness/tests file_length/tests flutter_web_drive/tests home_paths/tests md_naming/tests repo_contract/tests scripts/tests unified-design-system/tests` +- test: `PYTHONPATH=. python -m pytest -q agent_ready/tests coverage_gaps/tests dep_freshness/tests devstats/tests file_length/tests flutter_web_drive/tests home_paths/tests md_naming/tests repo_contract/tests scripts/tests unified-design-system/tests` - test-changed: `scripts/test_changed.sh` -- lint: `ruff check agent_ready coverage_gaps flutter_web_drive repo_contract` -- coverage: `PYTHONPATH=. python -m pytest -q agent_ready/tests flutter_web_drive/tests repo_contract/tests unified-design-system/tests --cov=agent_ready --cov=flutter_web_drive --cov=repo_contract --cov=conformance --cov=conformance_diff --cov-branch --cov-report=xml --cov-fail-under=100` +- lint: `ruff check agent_ready coverage_gaps devstats flutter_web_drive repo_contract` +- coverage: `PYTHONPATH=. python -m pytest -q agent_ready/tests devstats/tests flutter_web_drive/tests repo_contract/tests unified-design-system/tests --cov=agent_ready --cov=devstats --cov=flutter_web_drive --cov=repo_contract --cov=conformance --cov=conformance_diff --cov-branch --cov-report=xml --cov-fail-under=100` - coverage-gaps: `coverage-gaps coverage.xml` - deploy: `git -C ~/src/utils pull --ff-only && ~/src/utils/scripts/deploy.sh` (installs the sickdays CLI + launcher from the live checkout, then exits 1 unless every released library's version tag is on origin and matches HEAD and the live `sickdays` runs the text-free checkout; `--verify-only` for the health check alone) diff --git a/README.md b/README.md index a7673e4..1babdee 100644 --- a/README.md +++ b/README.md @@ -176,3 +176,12 @@ Consume via a shallow fetch of the tag, then mount the addon folder: git clone --depth 1 --branch godot-dev-tools-v0.1.1 https://github.com/kuhyx/utils # link or copy godot_dev_tools/addons/dev_tools to res://addons/dev_tools ``` + +## devstats/ + +`python -m devstats compare` (from the repo root, `PYTHONPATH=.`): kuhy's net +LoC/day, commits and tags over 30/90/300 days across every repo in ~/src +(worktrees and rewritten copies counted once, lockfiles/generated/vendored/data +dropped by `devstats/excludes.py`), printed beside the figures from +https://veszelovszki.com/a/tpe/. `--by-repo [N]` adds a top-N table (terminal +only); `--write` regenerates [`devstats/DOCS-comparison.md`](devstats/DOCS-comparison.md). diff --git a/devstats/DOCS-comparison.md b/devstats/DOCS-comparison.md new file mode 100644 index 0000000..b5f8425 --- /dev/null +++ b/devstats/DOCS-comparison.md @@ -0,0 +1,53 @@ +# devstats: kuhy vs "the 100x programmer" article + +Generated 2026-11-27 by `python -m devstats compare --write` (utils/devstats). +Article: https://veszelovszki.com/a/tpe/ (Cmdr, posted 2026-10-24). + +- kuhy: every repo under ~/src, each piece of work once (worktrees, clones + and rewritten copies folded in), commits on the default branch (local and + origin tips), `--no-merges`, authored by kuhy's address (agent-made commits + included). Committer date, local time. +- Net LoC = insertions − deletions of code paths. Docs/translations are left + out of the headline like the article's; the "+docs" row adds them back. +- Cmdr's figures are per calendar day; the baseline (194) is per day with a + push, so kuhy's per-active-day column divides by days with ≥1 counted commit. +- ×0.67 is the article's "Discount it by 33% to compensate for the AI bloat". + +## LoC per calendar day vs Cmdr + +| window | row | kuhy net LoC/day | ins/day | del/day | Cmdr LoC/day | +|---|---|---|---|---|---| +| 30 d | raw | 25,808 | 35,818 | 10,010 | 12,000 | +| 30 d | ×0.67 | 17,291 | 23,998 | 6,707 | 8,040 | +| 30 d | +docs | 26,220 | 37,070 | 10,850 | — | +| 90 d | raw | 19,533 | 24,524 | 4,992 | 9,700 | +| 90 d | ×0.67 | 13,087 | 16,431 | 3,344 | 6,499 | +| 90 d | +docs | 19,955 | 25,384 | 5,429 | — | +| 300 d ≈ lifetime (10 mo) | raw | 7,579 | 11,075 | 3,497 | 4,500 | +| 300 d ≈ lifetime (10 mo) | ×0.67 | 5,078 | 7,421 | 2,343 | 3,015 | +| 300 d ≈ lifetime (10 mo) | +docs | 7,923 | 11,795 | 3,871 | — | + +## Per active day vs the 194 LoC/workday baseline + +| window | active days | row | kuhy net LoC/active day | baseline LoC/workday | kuhy ÷ 194 | kuhy commits/active day | Cmdr commits/workday | +|---|---|---|---|---|---|---|---| +| 30 d | 24 | raw | 32,260 | 194 | 166.3× | 146 | 160 | +| 30 d | 24 | ×0.67 | 21,614 | 194 | 111.4× | | | +| 90 d | 77 | raw | 22,830 | 194 | 117.7× | 82 | — | +| 90 d | 77 | ×0.67 | 15,296 | 194 | 78.8× | | | +| 300 d ≈ lifetime (10 mo) | 181 | raw | 12,561 | 194 | 64.7× | 47 | 55 | +| 300 d ≈ lifetime (10 mo) | 181 | ×0.67 | 8,416 | 194 | 43.4× | | | + +## Totals + +| window | net code LoC | insertions | deletions | net +docs | excluded share | commits | tags | tags/week | Cmdr releases/week | repos with ≥1 tag | +|---|---|---|---|---|---|---|---|---|---|---| +| 30 d | 774,242 | 1,074,555 | 300,313 | 786,589 | 23% | 3,511 | 725 | 169.2 | ~2 | 26 | +| 90 d | 1,757,944 | 2,207,196 | 449,252 | 1,795,922 | 23% | 6,340 | 1226 | 95.4 | ~2 | 28 | +| 300 d ≈ lifetime (10 mo) | 2,273,591 | 3,322,648 | 1,049,057 | 2,376,996 | 33% | 8,562 | 1661 | 38.8 | ~2 | 31 | + +## Exclude list (first match wins) + +- excluded: `node_modules/`, `vendor/`, `third_party/`, `addons/`, `.venv/`, `.dart_tool/`, `dist/`, `build/`, `generated/`, `htmlcov/`, `coverage/`, `__snapshots__/`, `data/`, `assets/`, `fixtures/`, `*.lock`, `*.lockb`, `package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `go.sum`, `*.g.dart`, `*.freezed.dart`, `*.mocks.dart`, `*.gr.dart`, `*.pb.go`, `*_pb2.py`, `*.min.js`, `*.min.css`, `*.map`, `coverage.xml`, `lcov.info`, `*.lcov`, `*.import`, `*.uid`, `*.snap`, `*.json`, `*.jsonl`, `*.ndjson`, `*.geojson`, `*.csv`, `*.tsv`, `*.txt`, `*.tcx`, `*.gpx`, `*.tres`, `*.svg`, `*.log` +- docs: `docs/`, `doc/`, `l10n/`, `locales/`, `i18n/`, `translations/`, `*.md`, `*.mdx`, `*.rst`, `*.adoc`, `*.arb`, `*.po`, `*.pot`, `LICENSE*`, `COPYING*` +- code: `godot_dev_tools/`, `package.json`, `tsconfig*.json`, `jsconfig.json`, `deno.json`, `requirements*.txt`, `CMakeLists.txt` diff --git a/devstats/__init__.py b/devstats/__init__.py new file mode 100644 index 0000000..6886ce8 --- /dev/null +++ b/devstats/__init__.py @@ -0,0 +1 @@ +"""devstats: kuhy's git output (net LoC/day, commits, tags) vs the 100x article.""" diff --git a/devstats/__main__.py b/devstats/__main__.py new file mode 100644 index 0000000..3d191a6 --- /dev/null +++ b/devstats/__main__.py @@ -0,0 +1,5 @@ +"""`python -m devstats compare` entry point.""" + +from devstats.cli import main + +raise SystemExit(main()) diff --git a/devstats/aggregate.py b/devstats/aggregate.py new file mode 100644 index 0000000..9b1b536 --- /dev/null +++ b/devstats/aggregate.py @@ -0,0 +1,116 @@ +"""Per-window totals over every repo's commits and tags.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, replace +from datetime import datetime + +from devstats.excludes import classify +from devstats.numstat import Commit + +DAY = 86_400 + + +@dataclass(frozen=True) +class RepoData: + """Counted commits (already filtered to the chosen emails) and (sha, ts) tags of one repo.""" + + name: str + commits: tuple[Commit, ...] + tags: tuple[tuple[str, int], ...] + + +@dataclass(frozen=True) +class Window: + """Totals for the last `days` days.""" + + days: int + code_ins: int + code_del: int + docs_ins: int + docs_del: int + excluded_lines: int + all_lines: int + commits: int + active_days: int + tags: int + repos_with_tags: int + + @property + def net(self) -> int: + """Headline: code insertions minus deletions (docs and excluded paths left out).""" + return self.code_ins - self.code_del + + @property + def net_with_docs(self) -> int: + """Net including markdown/translations ("+docs").""" + return self.net + self.docs_ins - self.docs_del + + @property + def excluded_share(self) -> float: + """Share of all changed lines (ins+del) the exclude list dropped.""" + return self.excluded_lines / self.all_lines if self.all_lines else 0.0 + + +def dedup(repos: Sequence[RepoData]) -> list[RepoData]: + """Count each piece of work once across repos. + + A filter-repo split (testsAndMisc -> testsAndMisc-archive) or a fork + (kuhytrack -> leisure-watch) carries the same commits, rewritten or not. + Copies share email + author time + subject; the copy with the larger diff + is kept (the earlier repo on a tie), the others are dropped. A tag object + seen in an earlier repo (a clone) is dropped too. + """ + best: dict[tuple[str, int, str], tuple[int, Commit]] = {} + for i, repo in enumerate(repos): + for c in repo.commits: + seen = best.get(c.identity) + if seen is None or c.churn > seen[1].churn: + best[c.identity] = (i, c) + keep = {(i, c.sha) for i, c in best.values()} + seen_tags: set[str] = set() + out = [] + for i, repo in enumerate(repos): + tags = tuple(t for t in repo.tags if t[0] not in seen_tags) + seen_tags.update(sha for sha, _ in repo.tags) + out.append(replace(repo, commits=tuple(c for c in repo.commits if (i, c.sha) in keep), + tags=tags)) + return out + + +def window_totals(repos: Sequence[RepoData], days: int, now: float) -> Window: + """Aggregate `repos` over the `days` days before `now`.""" + cutoff = now - days * DAY + sums = {"code": [0, 0], "docs": [0, 0], "excluded": [0, 0]} + commits = 0 + dates: set[object] = set() + tags = repos_with_tags = 0 + for repo in repos: + for c in repo.commits: + if c.ts < cutoff: + continue + commits += 1 + dates.add(datetime.fromtimestamp(c.ts).date()) + for f in c.files: + if not f.binary: + bucket = sums[classify(f.path)] + bucket[0] += f.ins + bucket[1] += f.dels + n = sum(1 for _, t in repo.tags if cutoff <= t <= now) + tags += n + repos_with_tags += n > 0 + excluded = sum(sums["excluded"]) + return Window( + days=days, + code_ins=sums["code"][0], + code_del=sums["code"][1], + docs_ins=sums["docs"][0], + docs_del=sums["docs"][1], + excluded_lines=excluded, + all_lines=excluded + sum(sums["code"]) + sum(sums["docs"]), + commits=commits, + active_days=len(dates), + tags=tags, + repos_with_tags=repos_with_tags, + ) diff --git a/devstats/article.py b/devstats/article.py new file mode 100644 index 0000000..386ca29 --- /dev/null +++ b/devstats/article.py @@ -0,0 +1,21 @@ +"""Figures from https://veszelovszki.com/a/tpe/ (post dated 2026-10-24). + +Cmdr's LoC/day are per calendar day, weekends included, and exclude +"generated code, libraries, docs, etc." (docs and translations are a separate +"+800k"). The windows are the article's: last 30 days ~12,000, last 90 days +~9,700, lifetime (~10 months) 4,500. The 194 baseline is Sourcegraph LoC per +day "when I pushed code", i.e. per active day. Commits: ~160/workday in +October, ~55/workday lifetime, no 90-day figure. Releases: ~2/week. +"Discount it by 33%" (x0.67) applies to Cmdr's rates, not to the baseline. +""" + +from __future__ import annotations + +URL = "https://veszelovszki.com/a/tpe/" +WINDOWS: tuple[int, ...] = (30, 90, 300) +LABELS = {30: "30 d", 90: "90 d", 300: "300 d ≈ lifetime (10 mo)"} +CMDR_LOC_PER_DAY = {30: 12_000, 90: 9_700, 300: 4_500} +CMDR_COMMITS_PER_WORKDAY: dict[int, int | None] = {30: 160, 90: None, 300: 55} +BASELINE_LOC_PER_WORKDAY = 194 +RELEASES_PER_WEEK = 2 +AI_DISCOUNT = 0.67 diff --git a/devstats/cli.py b/devstats/cli.py new file mode 100644 index 0000000..e1d9a93 --- /dev/null +++ b/devstats/cli.py @@ -0,0 +1,81 @@ +"""`python -m devstats compare [--root DIR]... [--email ADDR]... [--by-repo [N]] [--write]`.""" + +from __future__ import annotations + +import argparse +import sys +import time +from collections.abc import Sequence +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime +from pathlib import Path +from typing import TextIO + +from devstats import article as A +from devstats.aggregate import DAY, RepoData, Window, dedup, window_totals +from devstats.discover import Repo, discover +from devstats.numstat import read_commits +from devstats.refs import list_refs, resolve, tag_times +from devstats.render import by_repo, document, report + +DEFAULT_EMAIL = "krzysztofrudnicki0@gmail.com" +DOC_PATH = Path(__file__).resolve().parent / "DOCS-comparison.md" +EXIT_NO_REPOS = 2 + + +def build_parser() -> argparse.ArgumentParser: + """Argument parser with the single `compare` subcommand.""" + parser = argparse.ArgumentParser(prog="devstats", description="kuhy's git output vs the 100x article") + sub = parser.add_subparsers(dest="cmd", required=True) + cmp = sub.add_parser("compare", help="print kuhy's 30/90/300-day numbers beside the article's") + cmp.add_argument("--root", action="append", type=Path, default=[], + help="directory whose child repos are walked (repeatable; default ~/src)") + cmp.add_argument("--email", action="append", default=[], + help=f"extra author email to count (repeatable; {DEFAULT_EMAIL} always counts)") + cmp.add_argument("--by-repo", nargs="?", type=int, const=10, default=0, metavar="N", + help="also print the top N repos (terminal only, default N=10)") + cmp.add_argument("--write", action="store_true", help="rewrite devstats/DOCS-comparison.md") + return parser + + +def _collect(repo: Repo, emails: frozenset[str], since: int) -> tuple[RepoData, list[str]]: + """Commits by `emails` on the repo's default branch since `since`, its tags, warnings.""" + refs = list_refs(repo.path) + default = resolve(refs) + tags = tuple(tag_times(refs)) + if default.branch is None: + return RepoData(repo.name, (), tags), [f"{repo.name}: no main/master/origin HEAD branch, skipped"] + warnings = [] + if default.behind_days is not None: + warnings.append(f"{repo.name} ({default.branch}): default ref is {default.behind_days} days " + "behind its upstream tracking ref") + commits = tuple(c for c in read_commits(repo.path, default.log_refs, since) if c.email in emails) + return RepoData(repo.name, commits, tags), warnings + + +def main(argv: Sequence[str] | None = None, *, now: float | None = None, out: TextIO = sys.stdout, + err: TextIO = sys.stderr, doc_path: Path = DOC_PATH) -> int: + """Run the CLI; returns the exit code (2 when no repo was found).""" + args = build_parser().parse_args(argv) + now = time.time() if now is None else now + roots = args.root or [Path.home() / "src"] + emails = frozenset(e.lower() for e in (DEFAULT_EMAIL, *args.email)) + repos, warnings = discover(roots) + if not repos: + print(f"devstats: no git repos under {', '.join(map(str, roots))}", file=err) + return EXIT_NO_REPOS + since = int(now - max(A.WINDOWS) * DAY) + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(lambda r: _collect(r, emails, since), repos)) + data = dedup([d for d, _ in results]) + for w in (*warnings, *(w for _, ws in results for w in ws)): + print(f"warning: {w}", file=err) + windows: list[Window] = [window_totals(data, d, now) for d in A.WINDOWS] + print(report(windows), file=out) + if args.by_repo: + per_repo = [(d.name, [window_totals([d], days, now) for days in A.WINDOWS]) for d in data] + print(by_repo(per_repo, args.by_repo), file=out) + if args.write: + doc_path.write_text(document(windows, datetime.fromtimestamp(now).date().isoformat())) + print(f"wrote {doc_path}", file=out) + return 0 diff --git a/devstats/discover.py b/devstats/discover.py new file mode 100644 index 0000000..5ef5c51 --- /dev/null +++ b/devstats/discover.py @@ -0,0 +1,47 @@ +"""Find repos one level under each root and fold worktrees into their repo. + +Worktrees (e.g. the sb-wt-* signal-bot checkouts) share one git common dir +with their main repo, so deduplicating on it counts every repo once, named +after the common dir's parent whichever checkout was walked first. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path + +from devstats.gitcmd import GitError, git + + +@dataclass(frozen=True) +class Repo: + """One repository: display name and a checkout path to run git in.""" + + name: str + path: Path + + +def _candidates(root: Path) -> list[Path]: + """The root itself if it is a checkout, else its direct children that are.""" + if (root / ".git").exists(): + return [root] + if not root.is_dir(): + return [] + return sorted(p for p in root.iterdir() if p.is_dir() and (p / ".git").exists()) + + +def discover(roots: Sequence[Path]) -> tuple[list[Repo], list[str]]: + """Repos under `roots`, one per git common dir, plus warnings for broken ones.""" + seen: dict[Path, Repo] = {} + warnings: list[str] = [] + for root in roots: + for path in _candidates(root): + try: + out = git(path, "rev-parse", "--path-format=absolute", "--git-common-dir") + except GitError: + warnings.append(f"{path.name}: not a readable git repo, skipped") + continue + common = Path(out.decode().strip()) + seen.setdefault(common, Repo(name=common.parent.name, path=path)) + return sorted(seen.values(), key=lambda r: r.name), warnings diff --git a/devstats/excludes.py b/devstats/excludes.py new file mode 100644 index 0000000..0ae3fd8 --- /dev/null +++ b/devstats/excludes.py @@ -0,0 +1,83 @@ +"""THE exclude list: which changed paths count as code, docs or dropped churn. + +One ordered constant, first match wins. A pattern ending in "/" matches any +directory component of the path; any other pattern is a glob on the file name. +Excluded directories come first so nothing inside node_modules/ or addons/ is +rescued by a later rule; the code keeps come before the file excludes so +package.json survives `*.json`; translation dirs come before `*.json` so +locales/en.json counts as docs, like the article's "+800k translations and docs". + +Judgment calls, calibrated on the 30-day top-40 churn list (2026-11-27): +- `*.txt` is data (one word list was ~10% of all churn) except requirements/CMake. +- `*.json` is data (eval dumps, fixtures, baselines) except a few config names. +- Godot `addons/` is vendored (GUT, copies of dev_tools) except the source of + kuhy's own addon under `godot_dev_tools/`; `*.tres` is data; `*.import`/`*.uid` are + generated; `*.tscn` scenes stay code (authored structure). +- `fixtures/` is test data; test code itself stays. +""" + +from __future__ import annotations + +from fnmatch import fnmatchcase +from typing import Literal + +Bucket = Literal["code", "docs", "excluded"] + +RULES: tuple[tuple[Bucket, str], ...] = ( + # kuhy's own Godot addon source (utils/godot_dev_tools); games carry vendored copies + ("code", "godot_dev_tools/"), + # vendored, generated and data directories (any depth) + *( + ("excluded", d) + for d in ( + "node_modules/", "vendor/", "third_party/", "addons/", ".venv/", ".dart_tool/", + "dist/", "build/", "generated/", "htmlcov/", "coverage/", "__snapshots__/", + "data/", "assets/", "fixtures/", + ) + ), + # config files that would otherwise fall under a data glob below + *( + ("code", f) + for f in ("package.json", "tsconfig*.json", "jsconfig.json", "deno.json", + "requirements*.txt", "CMakeLists.txt") + ), + # translations and docs directories + *(("docs", d) for d in ("docs/", "doc/", "l10n/", "locales/", "i18n/", "translations/")), + # lockfiles + *( + ("excluded", f) + for f in ("*.lock", "*.lockb", "package-lock.json", "npm-shrinkwrap.json", + "pnpm-lock.yaml", "go.sum") + ), + # generated files + *( + ("excluded", f) + for f in ("*.g.dart", "*.freezed.dart", "*.mocks.dart", "*.gr.dart", "*.pb.go", + "*_pb2.py", "*.min.js", "*.min.css", "*.map", "coverage.xml", "lcov.info", + "*.lcov", "*.import", "*.uid", "*.snap") + ), + # data and assets + *( + ("excluded", f) + for f in ("*.json", "*.jsonl", "*.ndjson", "*.geojson", "*.csv", "*.tsv", "*.txt", + "*.tcx", "*.gpx", "*.tres", "*.svg", "*.log") + ), + # docs and translations + *( + ("docs", f) + for f in ("*.md", "*.mdx", "*.rst", "*.adoc", "*.arb", "*.po", "*.pot", + "LICENSE*", "COPYING*") + ), +) + + +def classify(path: str) -> Bucket: + """Bucket for one repo-relative path (binaries are handled by the caller).""" + *dirs, name = path.split("/") + for bucket, pattern in RULES: + if pattern.endswith("/"): + if any(fnmatchcase(d, pattern[:-1]) for d in dirs): + return bucket + elif fnmatchcase(name, pattern): + return bucket + return "code" diff --git a/devstats/gitcmd.py b/devstats/gitcmd.py new file mode 100644 index 0000000..044a8d6 --- /dev/null +++ b/devstats/gitcmd.py @@ -0,0 +1,26 @@ +"""Read-only git subprocess wrapper. + +GIT_OPTIONAL_LOCKS=0 stops even read commands from refreshing the index of a +walked repo, so a run never changes anything in kuhy's checkouts. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + + +class GitError(RuntimeError): + """git exited non-zero.""" + + +def git(repo: Path, *args: str) -> bytes: + """Run `git -C repo args...` and return raw stdout, raising GitError on failure.""" + env = {**os.environ, "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C"} + proc = subprocess.run( + ["git", "-C", str(repo), *args], env=env, capture_output=True, check=False + ) + if proc.returncode != 0: + raise GitError(proc.stderr.decode(errors="replace").strip()) + return proc.stdout diff --git a/devstats/numstat.py b/devstats/numstat.py new file mode 100644 index 0000000..a74c404 --- /dev/null +++ b/devstats/numstat.py @@ -0,0 +1,91 @@ +"""One `git log --numstat -z` pass per repo, parsed into commits and file changes. + +Record layout (git 2.x): `\\x1e\\x1f\\x1f\\x1f\\x1f\\0`, +then a newline before the first entry, then per file either +`ins\\tdel\\tpath\\0` or, for a rename, `ins\\tdel\\t\\0old\\0new\\0`. +Binaries report `-` for both counts. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path + +from devstats.gitcmd import git + +FORMAT = "%x1e%H%x1f%ct%x1f%ae%x1f%at%x1f%s" + + +@dataclass(frozen=True) +class FileChange: + """Line counts for one path in one commit.""" + + path: str + ins: int + dels: int + binary: bool + + +@dataclass(frozen=True) +class Commit: + """One non-merge commit: committer timestamp, lowercased author email, files. + + `author_ts` + `subject` survive history rewrites (filter-repo splits, forks), + so together with the email they identify the same work across repos. + """ + + sha: str + ts: int + email: str + files: tuple[FileChange, ...] + author_ts: int = 0 + subject: str = "" + + @property + def identity(self) -> tuple[str, int, str]: + """Key that is equal for a commit and its rewritten copy in another repo.""" + return (self.email, self.author_ts, self.subject) + + @property + def churn(self) -> int: + """Changed lines (ins+del) over all files.""" + return sum(f.ins + f.dels for f in self.files) + + +def _parse_files(tokens: list[str]) -> tuple[FileChange, ...]: + """Turn the NUL-split numstat tokens of one commit into FileChanges.""" + files: list[FileChange] = [] + i = 0 + while i < len(tokens): + tok = tokens[i].lstrip("\n") + i += 1 + if not tok: + continue + ins, dels, path = tok.split("\t", 2) + if not path: # rename: old and new path follow as their own tokens + path = tokens[i + 1] + i += 2 + binary = ins == "-" + files.append(FileChange(path, 0 if binary else int(ins), 0 if binary else int(dels), binary)) + return tuple(files) + + +def parse_log(raw: bytes) -> list[Commit]: + """Parse the output of `git log --numstat -z --format=FORMAT`.""" + commits: list[Commit] = [] + for record in raw.decode(errors="replace").split("\x1e")[1:]: + header, _, body = record.partition("\0") + sha, ts, email, author_ts, subject = header.split("\x1f", 4) + files = _parse_files(body.split("\0")) + commits.append(Commit(sha, int(ts), email.lower(), files, int(author_ts), subject)) + return commits + + +def read_commits(repo: Path, refs: Sequence[str], since_ts: int) -> list[Commit]: + """Non-merge commits reachable from any of `refs`, committed at or after `since_ts`.""" + since = datetime.fromtimestamp(since_ts, UTC).isoformat() + raw = git(repo, "log", *refs, "--no-merges", f"--since={since}", "--numstat", "-z", + f"--format={FORMAT}", "--") + return [c for c in parse_log(raw) if c.ts >= since_ts] diff --git a/devstats/refs.py b/devstats/refs.py new file mode 100644 index 0000000..e2d6945 --- /dev/null +++ b/devstats/refs.py @@ -0,0 +1,69 @@ +"""Default-branch resolution from refs on disk (never fetches). + +The commits counted are the union of the local default branch and its +`origin/` remote-tracking ref: work landed with `git push origin HEAD:main` +from a worktree only moves the remote-tracking ref, while unpushed local work +only moves the local one, and both are kuhy's output. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from devstats.gitcmd import git + +_FORMAT = "%(refname)%09%(symref)%09%(objectname)%09%(committerdate:unix)%09%(creatordate:unix)" +_ORIGIN = "refs/remotes/origin/" + + +@dataclass(frozen=True) +class Ref: + """One ref: tip sha, tip committer ts (0 for tag objects), symref target, creator ts.""" + + sha: str + ts: int + symref: str + created: int + + +@dataclass(frozen=True) +class DefaultRefs: + """The default branch name, the refs to log, and how stale the local tip is.""" + + branch: str | None + log_refs: tuple[str, ...] + behind_days: float | None + + +def list_refs(repo: Path) -> dict[str, Ref]: + """Every local branch, origin remote-tracking ref and tag, in one git call.""" + out = git(repo, "for-each-ref", f"--format={_FORMAT}", "refs/heads", "refs/remotes/origin", + "refs/tags").decode(errors="replace") + refs: dict[str, Ref] = {} + for line in out.splitlines(): + name, symref, sha, ts, created = line.split("\t") + refs[name] = Ref(sha=sha, ts=int(ts or 0), symref=symref, created=int(created or 0)) + return refs + + +def tag_times(refs: dict[str, Ref]) -> list[tuple[str, int]]: + """(object sha, creator ts) of every tag: tagger date, or the commit date if lightweight.""" + return [(r.sha, r.created) for name, r in refs.items() if name.startswith("refs/tags/")] + + +def resolve(refs: dict[str, Ref]) -> DefaultRefs: + """origin/HEAD's branch, else main, else master; local and origin tips of it.""" + head = refs.get(_ORIGIN + "HEAD") + candidates = [head.symref.removeprefix(_ORIGIN)] if head and head.symref else [] + for branch in (*candidates, "main", "master"): + local, remote = refs.get("refs/heads/" + branch), refs.get(_ORIGIN + branch) + if local or remote: + log_refs = tuple( + n for n, r in (("refs/heads/" + branch, local), (_ORIGIN + branch, remote)) if r + ) + behind = None + if local and remote and local.sha != remote.sha and remote.ts > local.ts: + behind = round((remote.ts - local.ts) / 86_400, 1) + return DefaultRefs(branch, log_refs, behind) + return DefaultRefs(None, (), None) diff --git a/devstats/render.py b/devstats/render.py new file mode 100644 index 0000000..8826a3b --- /dev/null +++ b/devstats/render.py @@ -0,0 +1,111 @@ +"""Markdown tables: kuhy beside the article, plus the optional per-repo breakdown.""" + +from __future__ import annotations + +from collections.abc import Sequence + +from devstats import article as A +from devstats.aggregate import Window +from devstats.excludes import RULES + +DASH = "—" + + +def _n(x: float) -> str: + return f"{x:,.0f}" + + +def _table(head: Sequence[str], rows: Sequence[Sequence[str]]) -> list[str]: + out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)] + out += ["| " + " | ".join(r) + " |" for r in rows] + return out + + +def per_calendar_day(windows: Sequence[Window]) -> list[str]: + """kuhy raw / ×0.67 / +docs LoC per calendar day beside Cmdr raw / ×0.67.""" + rows = [] + for w in windows: + d, cmdr, label = w.days, A.CMDR_LOC_PER_DAY[w.days], A.LABELS[w.days] + for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)): + rows.append([label, row, _n(w.net * k / d), _n(w.code_ins * k / d), + _n(w.code_del * k / d), _n(cmdr * k)]) + rows.append([label, "+docs", _n(w.net_with_docs / d), _n((w.code_ins + w.docs_ins) / d), + _n((w.code_del + w.docs_del) / d), DASH]) + head = ("window", "row", "kuhy net LoC/day", "ins/day", "del/day", "Cmdr LoC/day") + return _table(head, rows) + + +def per_active_day(windows: Sequence[Window]) -> list[str]: + """kuhy per active day beside the 194 baseline, plus commits beside Cmdr's.""" + rows = [] + base = A.BASELINE_LOC_PER_WORKDAY + for w in windows: + active = max(w.active_days, 1) + cmdr_commits = A.CMDR_COMMITS_PER_WORKDAY[w.days] + for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)): + per = w.net * k / active + commits = [_n(w.commits / active), DASH if cmdr_commits is None else _n(cmdr_commits)] + rows.append([A.LABELS[w.days], str(w.active_days), row, _n(per), str(base), + f"{per / base:.1f}×", *(commits if row == "raw" else ["", ""])]) + head = ("window", "active days", "row", "kuhy net LoC/active day", "baseline LoC/workday", + "kuhy ÷ 194", "kuhy commits/active day", "Cmdr commits/workday") + return _table(head, rows) + + +def totals(windows: Sequence[Window]) -> list[str]: + """Raw totals, the share the exclude list removed, and tags.""" + rows = [ + [A.LABELS[w.days], _n(w.net), _n(w.code_ins), _n(w.code_del), _n(w.net_with_docs), + f"{w.excluded_share:.0%}", _n(w.commits), str(w.tags), f"{w.tags / (w.days / 7):.1f}", + f"~{A.RELEASES_PER_WEEK}", str(w.repos_with_tags)] + for w in windows + ] + head = ("window", "net code LoC", "insertions", "deletions", "net +docs", "excluded share", + "commits", "tags", "tags/week", "Cmdr releases/week", "repos with ≥1 tag") + return _table(head, rows) + + +def report(windows: Sequence[Window]) -> str: + """The comparison tables, as printed and as written to DOCS-comparison.md.""" + parts = ["## LoC per calendar day vs Cmdr", "", *per_calendar_day(windows), "", + "## Per active day vs the 194 LoC/workday baseline", "", *per_active_day(windows), "", + "## Totals", "", *totals(windows)] + return "\n".join(parts) + "\n" + + +def by_repo(per_repo: Sequence[tuple[str, Sequence[Window]]], top: int) -> str: + """Top-`top` repos by 300-day net code LoC (terminal only, never written).""" + ranked = sorted(per_repo, key=lambda item: -item[1][-1].net)[:top] + head = ("repo", *(f"net {A.LABELS[d].split(' ≈')[0]}" for d in A.WINDOWS), "commits 300 d") + rows = [[name, *(_n(w.net) for w in ws), _n(ws[-1].commits)] for name, ws in ranked] + return "\n".join(["## Top repos", "", *_table(head, rows)]) + "\n" + + +def exclude_list() -> str: + """The exclude list grouped by bucket, for the doc.""" + lines = [] + for bucket in ("excluded", "docs", "code"): + pats = ", ".join(f"`{p}`" for b, p in RULES if b == bucket) + lines.append(f"- {bucket}: {pats}") + return "\n".join(lines) + "\n" + + +def document(windows: Sequence[Window], date: str) -> str: + """Full DOCS-comparison.md body: aggregates only, no repo names.""" + intro = f"""# devstats: kuhy vs "the 100x programmer" article + +Generated {date} by `python -m devstats compare --write` (utils/devstats). +Article: {A.URL} (Cmdr, posted 2026-10-24). + +- kuhy: every repo under ~/src, each piece of work once (worktrees, clones + and rewritten copies folded in), commits on the default branch (local and + origin tips), `--no-merges`, authored by kuhy's address (agent-made commits + included). Committer date, local time. +- Net LoC = insertions − deletions of code paths. Docs/translations are left + out of the headline like the article's; the "+docs" row adds them back. +- Cmdr's figures are per calendar day; the baseline (194) is per day with a + push, so kuhy's per-active-day column divides by days with ≥1 counted commit. +- ×0.67 is the article's "Discount it by 33% to compensate for the AI bloat". + +""" + return intro + report(windows) + "\n## Exclude list (first match wins)\n\n" + exclude_list() diff --git a/devstats/tests/__init__.py b/devstats/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/devstats/tests/conftest.py b/devstats/tests/conftest.py new file mode 100644 index 0000000..8c36c27 --- /dev/null +++ b/devstats/tests/conftest.py @@ -0,0 +1,110 @@ +"""Throwaway git repos with pinned dates, under a redirected HOME/git config. + +Every test that runs git goes through `isolated_git`, so neither the real +~/.gitconfig nor any hook from it can leak in, and dates are explicit so the +window maths is deterministic. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +ME = "krzysztofrudnicki0@gmail.com" +DAY = 86_400 +# 2026-11-18 12:00 UTC: far from midnight in any timezone the tests run in. +NOW = 1_795_003_200 + + +@pytest.fixture(autouse=True) +def isolated_git(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch) -> None: + """Point HOME and the global git config at an empty scratch dir.""" + home = tmp_path_factory.mktemp("home") + cfg = home / "gitconfig" + cfg.write_text("[user]\n\tname = T\n\temail = t@example.com\n[init]\n\tdefaultBranch = main\n") + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(cfg)) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + monkeypatch.setenv("TZ", "UTC") + + +def run(cwd: Path, *args: str, env: dict[str, str] | None = None) -> str: + """Run git in `cwd` and return stdout.""" + full = {**os.environ, **(env or {})} + return subprocess.run( + ["git", *args], cwd=cwd, env=full, check=True, capture_output=True, text=True + ).stdout.strip() + + +@dataclass +class Repo: + """A scratch repository with helpers that pin author/committer dates.""" + + path: Path + + def _env(self, ts: int, email: str) -> dict[str, str]: + date = f"@{ts} +0000" + return { + "GIT_AUTHOR_DATE": date, + "GIT_COMMITTER_DATE": date, + "GIT_AUTHOR_EMAIL": email, + "GIT_COMMITTER_EMAIL": email, + "GIT_AUTHOR_NAME": "A", + "GIT_COMMITTER_NAME": "A", + } + + def commit(self, files: dict[str, str | bytes | None], ts: int, email: str = ME) -> str: + """Write/delete `files` (None deletes) and commit them at `ts`.""" + for name, content in files.items(): + target = self.path / name + if content is None: + run(self.path, "rm", "-q", name) + continue + target.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, bytes): + target.write_bytes(content) + else: + target.write_text(content) + run(self.path, "add", name) + run(self.path, "commit", "-q", "--allow-empty", "-m", "c", env=self._env(ts, email)) + return run(self.path, "rev-parse", "HEAD") + + def rename(self, old: str, new: str, ts: int, extra: str = "") -> str: + """`git mv old new`, optionally appending a line, committed at `ts`.""" + run(self.path, "mv", old, new) + if extra: + with (self.path / new).open("a") as fh: + fh.write(extra) + run(self.path, "add", new) + run(self.path, "commit", "-q", "-m", "mv", env=self._env(ts, ME)) + return run(self.path, "rev-parse", "HEAD") + + def tag(self, name: str, ts: int, annotated: bool = False) -> None: + """Create a lightweight or annotated tag dated `ts`.""" + args = ["tag", "-a", "-m", name, name] if annotated else ["tag", name] + run(self.path, *args, env=self._env(ts, ME)) + + +def lines(n: int, prefix: str = "x") -> str: + """`n` distinct lines of text.""" + return "".join(f"{prefix}{i}\n" for i in range(n)) + + +@pytest.fixture +def make_repo(tmp_path: Path): + """Factory: `make_repo("name", branch="main")` -> initialised Repo.""" + + def _make(name: str, branch: str = "main", root: Path | None = None) -> Repo: + path = (root or tmp_path / "src") / name + path.mkdir(parents=True) + run(path, "init", "-q", "-b", branch) + return Repo(path) + + return _make diff --git a/devstats/tests/test_aggregate.py b/devstats/tests/test_aggregate.py new file mode 100644 index 0000000..c83a27d --- /dev/null +++ b/devstats/tests/test_aggregate.py @@ -0,0 +1,59 @@ +"""Window totals: buckets, active days, excluded share, tags.""" + +from __future__ import annotations + +from devstats.aggregate import RepoData, dedup, window_totals +from devstats.numstat import Commit, FileChange + +from .conftest import DAY, NOW + + +def commit(days_ago: float, *files: FileChange) -> Commit: + ts = int(NOW - days_ago * DAY) + return Commit(sha=f"s{days_ago}", ts=ts, email="me", files=files, author_ts=ts, subject=f"c{days_ago}") + + +def fc(path: str, ins: int, dels: int, binary: bool = False) -> FileChange: + return FileChange(path, ins, dels, binary=binary) + + +def test_window_totals_split_buckets_and_windows() -> None: + repo = RepoData( + name="r", + commits=( + commit(1, fc("a.py", 100, 20), fc("README.md", 10, 0), fc("uv.lock", 50, 20)), + commit(1.2, fc("b.py", 5, 5), fc("logo.png", 0, 0, binary=True)), + commit(40, fc("c.py", 30, 0)), + commit(400, fc("d.py", 999, 0)), + ), + tags=(("t1", NOW - 2 * DAY), ("t2", NOW - 50 * DAY), ("t3", NOW - 500 * DAY), ("t4", NOW + DAY)), + ) + empty = RepoData(name="e", commits=(), tags=()) + w30 = window_totals([repo, empty], 30, NOW) + assert (w30.code_ins, w30.code_del, w30.net) == (105, 25, 80) + assert w30.net_with_docs == 90 + assert w30.commits == 2 + assert w30.active_days == 1 + assert w30.tags == 1 + assert w30.repos_with_tags == 1 + assert w30.excluded_share == 70 / 210 + w90 = window_totals([repo], 90, NOW) + assert (w90.net, w90.commits, w90.active_days, w90.tags) == (110, 3, 2, 2) + + +def test_empty_window_has_zero_share() -> None: + w = window_totals([], 30, NOW) + assert (w.net, w.excluded_share, w.active_days) == (0, 0.0, 0) + + +def test_dedup_keeps_the_larger_copy_of_rewritten_work() -> None: + small = Commit("x1", 10, "me", (fc("a.py", 1, 0),), author_ts=5, subject="s") + big = Commit("x2", 20, "me", (fc("a.py", 9, 0), fc("b.py", 1, 0)), author_ts=5, subject="s") + other = Commit("x3", 30, "me", (fc("c.py", 1, 0),), author_ts=6, subject="s") + tie = Commit("x4", 40, "me", (fc("d.py", 1, 0),), author_ts=7, subject="t") + a = RepoData("archive", (small, tie), (("t", 1), ("u", 2))) + b = RepoData("main", (big, other, tie), (("t", 1),)) + got = dedup([a, b]) + assert [c.sha for c in got[0].commits] == ["x4"] + assert [c.sha for c in got[1].commits] == ["x2", "x3"] + assert (got[0].tags, got[1].tags) == ((("t", 1), ("u", 2)), ()) diff --git a/devstats/tests/test_cli.py b/devstats/tests/test_cli.py new file mode 100644 index 0000000..d2050f3 --- /dev/null +++ b/devstats/tests/test_cli.py @@ -0,0 +1,109 @@ +"""End to end: `python -m devstats compare` over a scratch ~/src.""" + +from __future__ import annotations + +import io +from pathlib import Path + +import pytest + +from devstats.cli import main + +from .conftest import DAY, NOW, lines, run + + +@pytest.fixture +def src(make_repo, tmp_path: Path) -> Path: + """signal-bot + a worktree, a master-only repo, a collaborator, a stale ref.""" + bot = make_repo("signal-bot") + bot.commit({"bot.py": lines(100), "README.md": lines(40), "pnpm-lock.yaml": lines(500)}, NOW - DAY) + bot.commit({"bot.py": None}, NOW - 50 * DAY + 1) # dates out of order on purpose: kept by --since + bot.commit({"x.py": lines(10)}, NOW - 2 * DAY, email="ppolgon@gmail.com") + bot.tag("v1", NOW - DAY, annotated=True) + bot.commit({"pushed.py": lines(3)}, NOW - DAY) # pushed from a worktree: only origin has it + run(bot.path, "update-ref", "refs/remotes/origin/main", "HEAD") + run(bot.path, "update-ref", "refs/heads/main", "HEAD~1") # local main behind origin + run(bot.path, "worktree", "add", "-q", str(tmp_path / "src" / "sb-wt-a"), "-b", "wt") + old = make_repo("old", branch="master") + old.commit({"o.py": lines(20)}, NOW - 200 * DAY) + nob = make_repo("nobranch", branch="dev") + nob.commit({"n.py": lines(7)}, NOW - DAY) + return tmp_path / "src" + + +def compare(*args: str, doc: Path) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + rc = main(["compare", *args], now=NOW, out=out, err=err, doc_path=doc) + return rc, out.getvalue(), err.getvalue() + + +def test_compare_prints_all_windows_and_article_figures(src: Path, tmp_path: Path) -> None: + doc = tmp_path / "DOCS-comparison.md" + rc, out, err = compare("--root", str(src), doc=doc) + assert rc == 0 + for needle in ("30 d", "90 d", "300 d ≈ lifetime (10 mo)", "12,000", "9,700", "4,500", "×0.67", "194", + "160", "55", "+docs", "excluded", "tags/week", "repos with ≥1 tag", "÷ 194"): + assert needle in out, needle + assert "signal-bot (main): default ref is 1.0 days behind its upstream tracking ref" in err + assert "nobranch: no main/master/origin HEAD branch, skipped" in err + assert not doc.exists() + assert "signal-bot" not in out + + +def test_by_repo_folds_worktrees_and_write_has_no_repo_names(src: Path, tmp_path: Path) -> None: + doc = tmp_path / "DOCS-comparison.md" + rc, out, _ = compare("--root", str(src), "--by-repo", "--write", doc=doc) + assert rc == 0 + assert "signal-bot" in out + assert "sb-wt" not in out + text = doc.read_text() + assert "Generated 2026-11-18" in text + assert "pnpm-lock.yaml" in text # the exclude list is printed + for name in ("signal-bot", "sb-wt", "old", "nobranch"): + assert f"| {name}" not in text + + +def test_a_local_clone_changes_nothing_but_the_repo_list(src: Path, tmp_path: Path) -> None: + doc = tmp_path / "d.md" + _, before, _ = compare("--root", str(src), doc=doc) + run(src, "clone", "-q", "signal-bot", "bot-clone") + _, after, _ = compare("--root", str(src), doc=doc) + assert before == after + + +def test_email_flag_adds_the_collaborator(src: Path, tmp_path: Path) -> None: + doc = tmp_path / "d.md" + _, base, _ = compare("--root", str(src), "--by-repo", "1", doc=doc) + _, more, _ = compare("--root", str(src), "--by-repo", "1", "--email", "PPolgon@gmail.com", doc=doc) + assert base != more + + +def test_default_root_is_home_src(src: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("HOME", str(tmp_path)) + rc, out, _ = compare(doc=tmp_path / "d.md") + assert rc == 0 + assert "| 30 d" in out + + +def test_no_repos_is_an_error(tmp_path: Path) -> None: + rc, _, err = compare("--root", str(tmp_path / "empty"), doc=tmp_path / "d.md") + assert rc == 2 + assert "no git repos" in err + + +def test_compare_leaves_the_walked_repos_untouched(src: Path, tmp_path: Path) -> None: + before = {p: run(p, "for-each-ref") + run(p, "status", "--porcelain") for p in src.iterdir()} + compare("--root", str(src), doc=tmp_path / "d.md") + after = {p: run(p, "for-each-ref") + run(p, "status", "--porcelain") for p in src.iterdir()} + assert before == after + assert not (src / "signal-bot" / ".git" / "FETCH_HEAD").exists() + + +def test_module_entry_point(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + import runpy + + monkeypatch.setattr("sys.argv", ["devstats", "compare", "--help"]) + with pytest.raises(SystemExit) as exc: + runpy.run_module("devstats", run_name="__main__") + assert exc.value.code == 0 + assert "--by-repo" in capsys.readouterr().out diff --git a/devstats/tests/test_discover.py b/devstats/tests/test_discover.py new file mode 100644 index 0000000..bb5823b --- /dev/null +++ b/devstats/tests/test_discover.py @@ -0,0 +1,31 @@ +"""Repo discovery: one level under each root, worktrees folded into their repo.""" + +from __future__ import annotations + +from pathlib import Path + +from devstats.discover import discover + +from .conftest import DAY, NOW, lines, run + + +def test_worktrees_count_once_under_the_main_repo(make_repo, tmp_path: Path) -> None: + main = make_repo("signal-bot") + main.commit({"a.py": lines(1)}, NOW - DAY) + run(main.path, "worktree", "add", "-q", str(tmp_path / "src" / "sb-wt-a"), "-b", "wt-a") + make_repo("other") + (tmp_path / "src" / "not-a-repo").mkdir() + (tmp_path / "src" / "file.txt").write_text("x") + broken = tmp_path / "src" / "broken" + broken.mkdir() + (broken / ".git").write_text("gitdir: /nonexistent/worktree\n") + repos, warnings = discover([tmp_path / "src"]) + assert [r.name for r in repos] == ["other", "signal-bot"] + assert warnings == ["broken: not a readable git repo, skipped"] + + +def test_a_root_that_is_itself_a_repo_and_duplicate_roots(make_repo, tmp_path: Path) -> None: + repo = make_repo("solo", root=tmp_path) + repos, _ = discover([repo.path, repo.path, tmp_path / "missing"]) + assert [r.name for r in repos] == ["solo"] + diff --git a/devstats/tests/test_excludes.py b/devstats/tests/test_excludes.py new file mode 100644 index 0000000..f1b0fed --- /dev/null +++ b/devstats/tests/test_excludes.py @@ -0,0 +1,68 @@ +"""The one exclude list decides what counts as code, docs or dropped churn.""" + +from __future__ import annotations + +import pytest + +from devstats.excludes import RULES, classify + + +@pytest.mark.parametrize( + ("path", "bucket"), + [ + ("src/main.py", "code"), + ("tests/test_main.py", "code"), + ("lib/screen.dart", "code"), + ("scenes/level.tscn", "code"), + ("Makefile", "code"), + ("package.json", "code"), + ("web/tsconfig.app.json", "code"), + ("requirements-dev.txt", "code"), + ("native/CMakeLists.txt", "code"), + # lockfiles + ("web/pnpm-lock.yaml", "excluded"), + ("package-lock.json", "excluded"), + ("uv.lock", "excluded"), + ("app/pubspec.lock", "excluded"), + ("go.sum", "excluded"), + # generated + ("lib/model.g.dart", "excluded"), + ("lib/model.freezed.dart", "excluded"), + ("static/app.min.js", "excluded"), + ("coverage.xml", "excluded"), + ("icon.svg.import", "excluded"), + ("player.gd.uid", "excluded"), + ("android/build/reports/problems/problems-report.html", "excluded"), + ("web/dist/index.js", "excluded"), + # vendored + ("web/node_modules/x/index.js", "excluded"), + ("addons/gut/gut.gd", "excluded"), + ("game/addons/dev_tools/panel.gd", "excluded"), + ("godot_dev_tools/addons/dev_tools/panel.gd", "code"), + ("third_party/lib.c", "excluded"), + ("vendor/pkg/a.go", "excluded"), + # data / assets + ("pacman/words.txt", "excluded"), + ("tools/eval/data/reference.json", "excluded"), + ("assets/audio/MANIFEST.json", "excluded"), + ("tests/fixtures/run.tcx", "excluded"), + ("tests/fixtures/host/q.py", "excluded"), + ("games/chips/sea.tres", "excluded"), + ("report.csv", "excluded"), + # docs and translations + ("README.md", "docs"), + ("docs/guide.py", "docs"), + ("lib/l10n/app_pl.arb", "docs"), + ("public/locales/en.json", "docs"), + ("LICENSE", "docs"), + # an excluded dir beats a docs file and a code keep + ("node_modules/x/README.md", "excluded"), + ("node_modules/x/package.json", "excluded"), + ], +) +def test_classify(path: str, bucket: str) -> None: + assert classify(path) == bucket + + +def test_rules_use_known_buckets_only() -> None: + assert {bucket for bucket, _ in RULES} == {"code", "docs", "excluded"} diff --git a/devstats/tests/test_numstat.py b/devstats/tests/test_numstat.py new file mode 100644 index 0000000..4d1a6ea --- /dev/null +++ b/devstats/tests/test_numstat.py @@ -0,0 +1,81 @@ +"""Parsing `git log --numstat -z` and reading one ref set from a real repo.""" + +from __future__ import annotations + +from devstats.numstat import FileChange, parse_log, read_commits + +from .conftest import DAY, ME, NOW, lines + + +def test_parse_empty_input() -> None: + assert parse_log(b"") == [] + + +def test_parse_commit_without_files_then_rename_first() -> None: + raw = ( + b"\x1eaaa\x1f100\x1fMe@X.com\x1f90\x1fFix: a\x1fb\x00\n" + b"\x1ebbb\x1f200\x1fme@x.com\x1f190\x1fsecond\x00\n" + b"3\t1\t\x00old.py\x00new.py\x00-\t-\tlogo.png\x002\t0\tb.md\x00" + ) + first, second = parse_log(raw) + assert first.sha == "aaa" + assert first.ts == 100 + assert first.email == "me@x.com" + assert first.files == () + assert (first.author_ts, first.subject) == (90, "Fix: a\x1fb") + assert second.identity == ("me@x.com", 190, "second") + assert second.churn == 6 + assert second.files == ( + FileChange("new.py", 3, 1, binary=False), + FileChange("logo.png", 0, 0, binary=True), + FileChange("b.md", 2, 0, binary=False), + ) + + +def test_read_commits_skips_merges_and_old_commits(make_repo) -> None: + repo = make_repo("r") + repo.commit({"old.py": lines(50)}, NOW - 400 * DAY) + repo.commit({"a.py": lines(10)}, NOW - 5 * DAY) + base = repo.path + from .conftest import run + + run(base, "checkout", "-q", "-b", "side") + repo.commit({"b.py": lines(4)}, NOW - 4 * DAY) + run(base, "checkout", "-q", "main") + repo.commit({"c.py": lines(2)}, NOW - 3 * DAY) + run( + base, + "merge", + "-q", + "--no-ff", + "-m", + "m", + "side", + env={"GIT_COMMITTER_DATE": f"@{NOW - 2 * DAY} +0000", "GIT_AUTHOR_DATE": f"@{NOW - 2 * DAY} +0000"}, + ) + repo.rename("a.py", "z.py", NOW - DAY, extra="tail\n") + got = read_commits(base, ["refs/heads/main"], NOW - 300 * DAY) + files = sorted(f.path for c in got for f in c.files) + assert files == ["a.py", "b.py", "c.py", "z.py"] + assert all(c.email == ME for c in got) + rename = next(c for c in got if any(f.path == "z.py" for f in c.files)) + assert rename.files == (FileChange("z.py", 1, 0, binary=False),) + + +def test_read_commits_dedups_commits_reachable_from_two_refs(make_repo) -> None: + repo = make_repo("r") + repo.commit({"a.py": lines(3)}, NOW - DAY) + from .conftest import run + + run(repo.path, "update-ref", "refs/remotes/origin/main", "HEAD") + got = read_commits(repo.path, ["refs/heads/main", "refs/remotes/origin/main"], NOW - 30 * DAY) + assert len(got) == 1 + + +def test_binary_and_pure_rename_from_a_real_repo(make_repo) -> None: + repo = make_repo("r") + repo.commit({"logo.png": b"\x00\x01\x02", "a.py": lines(5)}, NOW - 2 * DAY) + repo.rename("a.py", "b.py", NOW - DAY) + got = read_commits(repo.path, ["refs/heads/main"], NOW - 30 * DAY) + assert got[0].files == (FileChange("b.py", 0, 0, binary=False),) + assert FileChange("logo.png", 0, 0, binary=True) in got[1].files diff --git a/devstats/tests/test_refs.py b/devstats/tests/test_refs.py new file mode 100644 index 0000000..ce4e5bb --- /dev/null +++ b/devstats/tests/test_refs.py @@ -0,0 +1,64 @@ +"""Default-branch resolution and the stale-local-ref warning.""" + +from __future__ import annotations + +from devstats.refs import Ref, list_refs, resolve, tag_times + +from .conftest import DAY, NOW, lines, run + + +def ref(ts: int, sha: str = "s", symref: str = "") -> Ref: + return Ref(sha=sha, ts=ts, symref=symref, created=ts) + + +def test_origin_head_names_the_branch_and_both_tips_are_logged() -> None: + refs = { + "refs/remotes/origin/HEAD": ref(0, symref="refs/remotes/origin/trunk"), + "refs/remotes/origin/trunk": ref(NOW, sha="o"), + "refs/heads/trunk": ref(NOW - 2 * DAY - DAY // 2, sha="l"), + "refs/heads/main": ref(NOW), + } + got = resolve(refs) + assert got.branch == "trunk" + assert got.log_refs == ("refs/heads/trunk", "refs/remotes/origin/trunk") + assert got.behind_days == 2.5 + + +def test_falls_back_to_main_then_master_without_origin() -> None: + assert resolve({"refs/heads/main": ref(1)}).log_refs == ("refs/heads/main",) + got = resolve({"refs/heads/master": ref(1), "refs/heads/dev": ref(2)}) + assert got.branch == "master" + assert got.behind_days is None + + +def test_origin_only_branch_is_still_counted() -> None: + got = resolve({"refs/remotes/origin/main": ref(1)}) + assert got.log_refs == ("refs/remotes/origin/main",) + + +def test_no_default_branch() -> None: + got = resolve({"refs/heads/dev": ref(1)}) + assert got.branch is None + assert got.log_refs == () + + +def test_local_ahead_or_equal_is_not_behind() -> None: + same = {"refs/heads/main": ref(5, sha="a"), "refs/remotes/origin/main": ref(5, sha="a")} + ahead = {"refs/heads/main": ref(9, sha="a"), "refs/remotes/origin/main": ref(5, sha="b")} + assert resolve(same).behind_days is None + assert resolve(ahead).behind_days is None + + +def test_list_refs_reads_branches_remotes_and_tags(make_repo) -> None: + repo = make_repo("r") + repo.commit({"a.py": lines(1)}, NOW - 10 * DAY) + repo.tag("v1", NOW - 9 * DAY, annotated=True) + repo.tag("light", NOW - 8 * DAY) + run(repo.path, "update-ref", "refs/remotes/origin/main", "HEAD") + run(repo.path, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + refs = list_refs(repo.path) + assert refs["refs/remotes/origin/HEAD"].symref == "refs/remotes/origin/main" + assert refs["refs/heads/main"].ts == NOW - 10 * DAY + # annotated: tagger date; lightweight: the commit's date + assert sorted(ts for _, ts in tag_times(refs)) == [NOW - 10 * DAY, NOW - 9 * DAY] + assert refs["refs/tags/light"].sha in dict(tag_times(refs))