1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
|
#!/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.
What `dead` means precisely is *the name is never written outside the module*.
That is a lead, not a verdict. A row type returned by a public query is part of
the interface even though no caller ever writes its name — they bind it with
`let` and call methods on it — so the way to find out which flagged items are
real is to privatize them and let the compiler answer: it rejects the ones that
are load-bearing and says nothing about the rest. Whatever survives that is
budgeted rather than zeroed, and the budget is where the reason lives.
The metric errs the other way too. Mentions are matched as words over the raw
file, so a name that appears only inside someone else's error *string* counts
as used: `watch::upstream::resolve` looked live for as long as some unrelated
db message happened to end "... to resolve". A flagged item is a question; a
clean item is not always an answer.
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+")
GLOB_RE = re.compile(r"^\s*pub(?:\(crate\))?\s+use\s+[^\n]*::\*")
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
for line in text.splitlines():
if COMMENT.match(line):
continue
if PUB_CRATE_RE.match(line):
row["priv"] += 1
if GLOB_RE.match(line):
row["glob"] += 1
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 "",
},
}
# `priv` is deliberately absent: a `pub(crate)` item is the good state, so a
# rising count is progress and must never be a ceiling. The same list is
# mirrored by `budgeted` in tests/architecture.rs.
BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "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())
|