summaryrefslogtreecommitdiffstats
path: root/tools/arch-census.py
diff options
context:
space:
mode:
authordev <dev@localhost>2026-11-20 16:49:20 +0000
committerdev <dev@localhost>2026-11-20 16:49:20 +0000
commit28387a3b920d2ecff62d2ef267af6b875be9d28d (patch)
tree247860f1d8019a32677c5cdcc43adb833bc2ea5d /tools/arch-census.py
parenta0ebd201713ae5a5a871b46aa526ffc40770f4bc (diff)
downloadaur-build-28387a3b920d2ecff62d2ef267af6b875be9d28d.tar.gz
aur-build-28387a3b920d2ecff62d2ef267af6b875be9d28d.zip
tools: census how wide each module's interface actually is
An interface is only as narrow as the items a module hands out, and nobody had counted them: 585 pub items across 27 modules, 146 of which nothing outside their own module ever names. That is not an interface, it is a hole in the module boundary, and every one of them is a thing a later refactor cannot change without a grep across the crate. The census counts pub items per module, how many of them are dead, how many of those a test does name (the integration tests are separate crates, so a name only they use is genuinely pub and the honest thing is to count it rather than pretend it is private), the glob re-exports that flatten a namespace, and the crate:: edge set between modules. The edge set is already acyclic, which is the useful surprise: a layer map can be declared over the graph as it stands rather than after breaking something. It also says where the width is — db hands out 226 items, http 68 of which 54 are dead — so the work has an order. Baseline for all of it: 273 tests passing, clippy -D warnings clean, release build clean.
Diffstat (limited to 'tools/arch-census.py')
-rwxr-xr-xtools/arch-census.py296
1 files changed, 296 insertions, 0 deletions
diff --git a/tools/arch-census.py b/tools/arch-census.py
new file mode 100755
index 0000000..ca6d7b8
--- /dev/null
+++ b/tools/arch-census.py
@@ -0,0 +1,296 @@
+#!/usr/bin/env python3
+"""Census the module tree: how wide each interface is, and what reaches into what.
+
+An interface is only as narrow as the items a module actually hands out, so the
+two numbers that matter are how many `pub` items a module declares and how many
+of them nothing outside that module ever names. A `pub` item with no outside
+reader is not an interface, it is a hole: every one of them is a thing a caller
+may depend on and a thing a later refactor cannot change without a grep across
+the crate. `tests/` counts as an outside reader on purpose — the integration
+tests are separate crates, so a name only they use is genuinely `pub`, and the
+honest way to say that is to count it rather than pretend it is private.
+
+Reported per module:
+ pub items declared `pub` (fn, struct, enum, trait, const, static, type)
+ dead of those, ones no file outside the module names — including tests/
+ test of the dead ones, the ones a test does name: pub for the test tier
+ deadonly dead minus test: exported, and named by nobody at all
+ priv items declared `pub(crate)`: crate-internal on purpose
+ glob `use … ::*` re-exports, which flatten a namespace and hide width
+ lines total lines of the module, and its largest single file
+
+Reported for the crate: the `crate::x` edge set between modules, which is the
+dependency graph the layer map in tests/architecture.rs is allowed to be.
+
+`tests/architecture.rs` enforces the same two definitions against a committed
+budget and fails when a number grows; this tool is the human-facing report of
+where the numbers are and where they moved.
+
+Usage:
+ tools/arch-census.py print the census
+ tools/arch-census.py --json the same numbers as JSON
+ tools/arch-census.py --record FILE append a dated section to a markdown file
+ tools/arch-census.py --budget FILE compare against a budget, exit 1 if over
+ tools/arch-census.py --write-budget FILE write the current numbers as budget
+"""
+
+import argparse
+import collections
+import json
+import os
+import re
+import sys
+from datetime import datetime, timezone
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+SRC = os.path.join(ROOT, "src")
+TESTS = os.path.join(ROOT, "tests")
+
+# A declaration, not a re-export: `pub use` is counted separately as a glob.
+PUB_RE = re.compile(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)")
+PUB_CRATE_RE = re.compile(r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+", re.M)
+GLOB_RE = re.compile(r"^\s*pub(?:\(crate\))?\s+use\s+[^\n]*::\*", re.M)
+EDGE_RE = re.compile(r"\bcrate::([a-z_][a-z0-9_]*)")
+# The binaries are separate crates, so they name the library through its own
+# name rather than through `crate::`. Those edges are part of the graph too.
+LIB_EDGE_RE = re.compile(r"\baur_build::([a-z_][a-z0-9_]*)")
+COMMENT = re.compile(r"^\s*(?://|//!|///)")
+
+
+def rust_files(*dirs):
+ out = []
+ for d in dirs:
+ for base, _, names in os.walk(d):
+ for name in names:
+ if name.endswith(".rs"):
+ out.append(os.path.join(base, name))
+ return sorted(out)
+
+
+def read_all(files):
+ texts = {}
+ for path in files:
+ with open(path, errors="replace") as handle:
+ texts[path] = handle.read()
+ return texts
+
+
+def module_of(path):
+ """The module a file belongs to.
+
+ A directory is one module (`src/db/*.rs` is `db`); a top-level file is a
+ module of its own (`src/ops.rs` is `ops`), because a layer map that lumps
+ eleven unrelated files into one box cannot say anything about them. The
+ binaries are separate crates and keep their own names.
+ """
+ rel = os.path.relpath(path, SRC)
+ parts = rel.split(os.sep)
+ if parts[0] == "bin":
+ return os.path.join("bin", *parts[1:]).removesuffix(".rs")
+ if len(parts) > 1:
+ return parts[0]
+ return parts[0].removesuffix(".rs")
+
+
+def declarations(texts):
+ """Every `pub` item name, with the modules that declare it and the files."""
+ names = collections.defaultdict(list)
+ for path, text in texts.items():
+ for line in text.splitlines():
+ if COMMENT.match(line):
+ continue
+ m = PUB_RE.match(line)
+ if m:
+ names[m.group(1)].append(path)
+ return names
+
+
+def census():
+ src_files = rust_files(SRC)
+ test_files = rust_files(TESTS)
+ src_texts = read_all(src_files)
+ test_texts = read_all(test_files)
+ names = declarations(src_texts)
+
+ mods = sorted({module_of(p) for p in src_files})
+ rows = {}
+ for mod in mods:
+ rows[mod] = {
+ "pub": 0,
+ "dead": 0,
+ "test": 0,
+ "deadonly": 0,
+ "priv": 0,
+ "glob": 0,
+ "lines": 0,
+ "largest": 0,
+ "largest_file": "",
+ }
+
+ for path, text in src_texts.items():
+ row = rows[module_of(path)]
+ row["lines"] += text.count("\n") + 1
+ row["priv"] += len(PUB_CRATE_RE.findall(text))
+ row["glob"] += len(GLOB_RE.findall(text))
+ size = text.count("\n") + 1
+ if size > row["largest"]:
+ row["largest"] = size
+ row["largest_file"] = os.path.relpath(path, ROOT)
+
+ # A name is dead when no file outside the module that declares it says it.
+ # A name declared in two modules is only dead if neither is referenced.
+ for name, paths in names.items():
+ declaring = {module_of(p) for p in paths}
+ for mod in declaring:
+ rows[mod]["pub"] += 1
+ outside = any(
+ module_of(p) not in declaring and re.search(r"\b%s\b" % re.escape(name), t)
+ for p, t in src_texts.items()
+ )
+ if outside:
+ continue
+ used_by_tests = any(re.search(r"\b%s\b" % re.escape(name), t) for t in test_texts.values())
+ for mod in declaring:
+ rows[mod]["dead"] += 1
+ if used_by_tests:
+ rows[mod]["test"] += 1
+ else:
+ rows[mod]["deadonly"] += 1
+
+ edges = collections.defaultdict(set)
+ for path, text in src_texts.items():
+ src_mod = module_of(path)
+ pattern = LIB_EDGE_RE if src_mod.startswith("bin") or src_mod == "main" else EDGE_RE
+ for line in text.splitlines():
+ if COMMENT.match(line):
+ continue
+ for target in pattern.findall(line):
+ if target in rows and target != src_mod:
+ edges[src_mod].add(target)
+
+ return {
+ "modules": rows,
+ "edges": {k: sorted(v) for k, v in sorted(edges.items())},
+ "totals": {
+ "pub": sum(r["pub"] for r in rows.values()),
+ "dead": sum(r["dead"] for r in rows.values()),
+ "test": sum(r["test"] for r in rows.values()),
+ "deadonly": sum(r["deadonly"] for r in rows.values()),
+ "priv": sum(r["priv"] for r in rows.values()),
+ "glob": sum(r["glob"] for r in rows.values()),
+ "edges": sum(len(v) for v in edges.values()),
+ "lines": sum(r["lines"] for r in rows.values()),
+ "largest": max((r["largest"] for r in rows.values()), default=0),
+ "largest_file": max(rows.values(), key=lambda r: r["largest"])["largest_file"]
+ if rows
+ else "",
+ },
+ }
+
+
+BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "priv", "glob")
+
+
+def check_budget(data, budget):
+ """Numbers over budget, as (module, key, budget, actual) tuples."""
+ over = []
+ mods = budget.get("modules", {})
+ for mod, row in sorted(data["modules"].items()):
+ allowed = mods.get(mod)
+ if allowed is None:
+ over.append((mod, "module", "absent from budget", "present"))
+ continue
+ for key in BUDGET_KEYS:
+ if key in allowed and row[key] > allowed[key]:
+ over.append((mod, key, allowed[key], row[key]))
+ return over
+
+
+def print_census(data):
+ totals = data["totals"]
+ width = max(len(m) for m in data["modules"])
+ print(f"{'module'.ljust(width)} {'pub':>4} {'dead':>5} {'test':>5} {'deadon':>7} "
+ f"{'priv':>5} {'glob':>5} {'lines':>6} largest file")
+ print("-" * (width + 49))
+ for mod, row in sorted(data["modules"].items()):
+ print(f"{mod.ljust(width)} {row['pub']:>4} {row['dead']:>5} {row['test']:>5} "
+ f"{row['deadonly']:>7} {row['priv']:>5} {row['glob']:>5} {row['lines']:>6} "
+ f"{row['largest']:>4} {row['largest_file']}")
+ print("-" * (width + 49))
+ print(f"{'total'.ljust(width)} {totals['pub']:>4} {totals['dead']:>5} {totals['test']:>5} "
+ f"{totals['deadonly']:>7} {totals['priv']:>5} {totals['glob']:>5} {totals['lines']:>6} "
+ f"{totals['largest']:>4} {totals['largest_file']}")
+ print(f"\ncrate:: edges between modules: {totals['edges']}")
+ for src_mod, targets in sorted(data["edges"].items()):
+ print(f" {src_mod.ljust(width)} -> {' '.join(targets)}")
+
+
+def record(data, path):
+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
+ totals = data["totals"]
+ new = not os.path.exists(path)
+ with open(path, "a") as handle:
+ if new:
+ handle.write("# Architecture census\n")
+ handle.write(f"\n## {stamp}\n\n")
+ handle.write(f"totals: {totals['pub']} pub, {totals['dead']} dead "
+ f"({totals['test']} test-only, {totals['deadonly']} named by nobody), "
+ f"{totals['priv']} pub(crate), "
+ f"{totals['glob']} glob re-exports, {totals['edges']} edges, "
+ f"largest file {totals['largest']} ({totals['largest_file']})\n\n")
+ handle.write("| module | pub | dead | test-only | dead-only | pub(crate) | glob | lines | largest file |\n")
+ handle.write("|---|---|---|---|---|---|---|---|---|\n")
+ for mod, row in sorted(data["modules"].items()):
+ handle.write(f"| {mod} | {row['pub']} | {row['dead']} | {row['test']} | "
+ f"{row['deadonly']} | "
+ f"{row['priv']} | {row['glob']} | {row['lines']} | "
+ f"{row['largest']} {row['largest_file']} |\n")
+ handle.write("\n```\n")
+ for src_mod, targets in sorted(data["edges"].items()):
+ handle.write(f"{src_mod} -> {' '.join(targets)}\n")
+ handle.write("```\n")
+ print(f"recorded in {path}")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--json", action="store_true", help="print the census as JSON")
+ ap.add_argument("--record", metavar="FILE", help="append a dated section to a markdown file")
+ ap.add_argument("--budget", metavar="FILE", help="fail if a number is over the committed budget")
+ ap.add_argument("--write-budget", metavar="FILE", help="write the current numbers as the budget")
+ args = ap.parse_args()
+
+ data = census()
+
+ if args.write_budget:
+ with open(args.write_budget, "w") as handle:
+ json.dump({"modules": data["modules"], "totals": data["totals"]}, handle, indent=2,
+ sort_keys=True)
+ handle.write("\n")
+ print(f"wrote {args.write_budget}")
+ return 0
+
+ if args.json:
+ print(json.dumps(data, indent=2, sort_keys=True))
+ return 0
+
+ print_census(data)
+
+ if args.budget:
+ with open(args.budget) as handle:
+ budget = json.load(handle)
+ over = check_budget(data, budget)
+ if over:
+ print("\nOVER BUDGET — these numbers grew:")
+ for mod, key, allowed, actual in over:
+ print(f" {mod}.{key}: {actual} > {allowed}")
+ return 1
+ print(f"\nwithin budget: {args.budget}")
+
+ if args.record:
+ record(data, args.record)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())