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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
|
#!/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.
An item whose reason has been written is no longer a hole, so it is not counted
as one: the `dead_code.allowlist` in `tests/architecture-budget.json` names
every item that stays `pub` by decision, and those items leave the `dead`,
`test` and `deadonly` columns. `deadonly` therefore means *dead and unargued*,
which is the one number that can honestly be held at zero forever.
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.
`pub(crate)` is not automatically the narrow state. A `pub(crate)` item whose
name is never written outside the one file that declares it is *over-wide*: it
says "the whole crate may reach this" about something only its own file reaches,
and it is one keystroke away from being a hole in the module's real interface.
`overwide` counts those. The search space is `src/` only, because `tests/` is a
separate crate and cannot name a `pub(crate)` item at all, so a test mentioning
the word says nothing about crate-internal visibility. Like every other column
here the flag is a lead, not a verdict — a `pub(crate)` type that appears in a
`pub` signature in its own file cannot go private without a private-in-public
error — and the compiler, not this file, decides.
The census counts; it does not remember. What is *accepted* lives in exactly one
machine-parsable file, `tests/architecture-budget.json`, which holds a
`dead_code` section: the accepted `deadonly` count per module, and an `allowlist`
of `module.item` -> one-line reason for every item deliberately kept. `--budget`
reads that file and fails on an excess, on a dead item nobody argued for, and on
an allowlist entry that no longer names a real item — a stale permission is as
bad as a missing one, because it is how an item comes back unnoticed.
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
overwide of those, ones no file outside the declaring file names: wider than
anything reaches, and a candidate for plain private
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.
The over-wide count is held down the same way `deadonly` is: an item that stays
`pub(crate)` despite nothing outside its file reading it is allowed only by name,
in `over_visibility.allowlist`, with the compiler fact that forces it written
beside it. `over_visibility.overwide` is the accepted count per module, and
`--budget` fails on an excess, on an unargued item, and on a permission whose
item is gone.
`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
tools/arch-census.py --list-dead name every dead item, with file:line
tools/arch-census.py --list-overwide name every over-wide pub(crate) item
"""
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+")
PUB_CRATE_NAME_RE = re.compile(
r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)"
)
# `pub(crate) use` is a re-export, not a declaration; the same rule the `pub`
# side follows, so a re-export cannot be counted as an item that could be private.
PUB_CRATE_USE_RE = re.compile(r"^\s*pub\(crate\)\s+use\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*(?://|//!|///)")
BUDGET = os.path.join(ROOT, "tests", "architecture-budget.json")
def load_allowlist(path=None):
"""The `module.item` names that stay `pub` by decision, with their reasons."""
try:
with open(path or BUDGET) as handle:
section = json.load(handle).get("dead_code", {})
except (ValueError, OSError):
return {}
allow = section.get("allowlist", {})
return allow if isinstance(allow, dict) else {}
def load_over_visibility(path=None):
"""The `module.item` names that stay `pub(crate)` by decision, with reasons."""
try:
with open(path or BUDGET) as handle:
section = json.load(handle).get("over_visibility", {})
except (ValueError, OSError):
return {}
allow = section.get("allowlist", {})
return allow if isinstance(allow, dict) else {}
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 every place that declares it.
Each entry is `(path, lineno)`, because a count cannot be acted on: the
question a reader asks of a dead item is *where is it*, and a census that can
only answer "db has 8" sends them back to grep.
"""
names = collections.defaultdict(list)
for path, text in texts.items():
for lineno, line in enumerate(text.splitlines(), 1):
if COMMENT.match(line):
continue
m = PUB_RE.match(line)
if m:
names[m.group(1)].append((path, lineno))
return names
def pub_crate_declarations(texts):
"""Every `pub(crate)` item name, with every place that declares it.
The twin of `declarations`, and it exists for the same reason: a count of
over-wide items is only useful if the tool can say which file and line.
`pub(crate) use` is a re-export and is not an item, so it is not a candidate
for going private on its own.
"""
names = collections.defaultdict(list)
for path, text in texts.items():
for lineno, line in enumerate(text.splitlines(), 1):
if COMMENT.match(line) or PUB_CRATE_USE_RE.match(line):
continue
m = PUB_CRATE_NAME_RE.match(line)
if m:
names[m.group(1)].append((path, lineno))
return names
def census(allow=None, over_allow=None):
allow = set(load_allowlist() if allow is None else allow)
over_allow = set(load_over_visibility() if over_allow is None else over_allow)
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)
pc_names = pub_crate_declarations(src_texts)
mods = sorted({module_of(p) for p in src_files})
rows = {}
# Every name a module declares, `pub` or `pub(crate)`. The allowlist is
# checked against this, so a permission cannot outlive the item it names.
declared = collections.defaultdict(set)
# Only the `pub(crate)` half, because an over-wide permission has to name a
# `pub(crate)` item: a key pointing at a `pub` one excuses nothing.
pc_declared = collections.defaultdict(set)
for mod in mods:
rows[mod] = {
"pub": 0,
"dead": 0,
"test": 0,
"deadonly": 0,
"priv": 0,
"overwide": 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
m = PUB_CRATE_NAME_RE.match(line)
if m:
declared[module_of(path)].add(m.group(1))
pc_declared[module_of(path)].add(m.group(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)
dead_items = []
# 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:
declared[mod].add(name)
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:
if f"{mod}.{name}" in allow:
# Argued, so not a hole: it stays `pub` on purpose and the reason
# is in the budget file next to its name.
dead_items.append({
"module": mod,
"name": name,
"kind": "allowlisted",
"file": os.path.relpath(next(p for p, _ in paths if module_of(p) == mod), ROOT),
"line": next(ln for p, ln in paths if module_of(p) == mod),
})
continue
rows[mod]["dead"] += 1
if used_by_tests:
rows[mod]["test"] += 1
else:
rows[mod]["deadonly"] += 1
here, line = next((pl for pl in paths if module_of(pl[0]) == mod))
dead_items.append({
"module": mod,
"name": name,
"kind": "test" if used_by_tests else "deadonly",
"file": os.path.relpath(here, ROOT),
"line": line,
})
overwide_items = []
# A `pub(crate)` name is over-wide when no file except the one that declares
# it says the word. `tests/` is not consulted: it is a separate crate and
# cannot name a `pub(crate)` item, so a mention there is noise. As with
# `dead`, a name declared in several files is only flagged when none of them
# is read from outside any of them — the flag is a lead, and a false one is
# cheaper than a missed one.
for name, places in sorted(pc_names.items()):
declaring = {p for p, _ in places}
outside = any(
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
for path, line in places:
mod = module_of(path)
if f"{mod}.{name}" in over_allow:
overwide_items.append({
"module": mod,
"name": name,
"kind": "allowlisted",
"file": os.path.relpath(path, ROOT),
"line": line,
})
continue
rows[mod]["overwide"] += 1
overwide_items.append({
"module": mod,
"name": name,
"kind": "overwide",
"file": os.path.relpath(path, ROOT),
"line": line,
})
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)
dead_items.sort(key=lambda d: (d["module"], d["name"]))
overwide_items.sort(key=lambda d: (d["module"], d["name"], d["file"], d["line"]))
return {
"modules": rows,
"dead_items": dead_items,
"overwide_items": overwide_items,
"declared": {mod: sorted(v) for mod, v in sorted(declared.items())},
"pc_declared": {mod: sorted(v) for mod, v in sorted(pc_declared.items())},
"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()),
"overwide": sum(r["overwide"] 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. `overwide` is the
# opposite: it counts the `pub(crate)` items nothing outside their own file
# reaches, and the only direction that number may move is down. The same list is
# mirrored by `budgeted` in tests/architecture.rs.
BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "overwide", "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 dead_code_section(budget):
"""The `dead_code` section as `(accepted deadonly per module, allowlist)`."""
section = budget.get("dead_code", {})
return section.get("deadonly", {}), section.get("allowlist", {})
def check_dead_code(data, budget):
"""Every surviving dead item is counted, named, and argued — or it fails.
Three ways to fail, because three things go wrong. A module can grow past its
accepted count. An item can appear that no one argued for. And an allowlist
entry can outlive the item it excused, which is how a deleted item comes back:
the permission is still on the books, so nobody notices the new one.
An entry stays valid while the item it names is still declared in that module,
even once the item has been narrowed to `pub(crate)` — the reason a caller
outside the module does not name it is worth keeping. Re-widening a narrowed
item is not caught here; it raises the module's `deadonly` over its accepted
count, which is what the count is for.
"""
accepted, allowlist = dead_code_section(budget)
problems = []
actual = {mod: row["deadonly"] for mod, row in data["modules"].items()}
for mod in sorted(set(actual) | set(accepted)):
have, allowed = actual.get(mod, 0), accepted.get(mod, 0)
if have > allowed:
problems.append(f"{mod}.deadonly: {have} > {allowed} accepted")
for item in data["dead_items"]:
if item["kind"] != "deadonly":
continue
key = f"{item['module']}.{item['name']}"
if key not in allowlist:
problems.append(f"{key} at {item['file']}:{item['line']} is dead and unargued")
elif not str(allowlist[key]).strip():
problems.append(f"{key} is allowlisted with no reason")
declared = data["declared"]
for key in sorted(allowlist):
mod, _, name = key.partition(".")
if name not in declared.get(mod, []):
problems.append(f"allowlist names {key}, which no module member is; delete the permission")
return problems
def over_visibility_section(budget):
"""The `over_visibility` section as `(accepted overwide per module, allowlist)`."""
section = budget.get("over_visibility", {})
return section.get("overwide", {}), section.get("allowlist", {})
def check_over_visibility(data, budget):
"""Every surviving over-wide item is counted, named and argued — or it fails.
The mirror of `check_dead_code` for the `pub(crate)` side, with the same
three failures: a module past its accepted count, an item nobody argued for,
and a permission whose item is gone. A reason has to say why the compiler
will not let the item go private — a `pub(crate)` type in a `pub` signature
in its own file, a trait impl that has to stay visible — because "it seemed
safer" is not a reason and does not stop the next widening.
"""
accepted, allowlist = over_visibility_section(budget)
problems = []
actual = {mod: row["overwide"] for mod, row in data["modules"].items()}
for mod in sorted(set(actual) | set(accepted)):
have, allowed = actual.get(mod, 0), accepted.get(mod, 0)
if have > allowed:
problems.append(f"{mod}.overwide: {have} > {allowed} accepted")
for item in data["overwide_items"]:
if item["kind"] != "overwide":
continue
key = f"{item['module']}.{item['name']}"
if key not in allowlist:
problems.append(f"{key} at {item['file']}:{item['line']} is over-wide and unargued")
elif not str(allowlist[key]).strip():
problems.append(f"{key} is allowlisted with no reason")
pc_declared = data["pc_declared"]
for key in sorted(allowlist):
mod, _, name = key.partition(".")
if name not in pc_declared.get(mod, []):
problems.append(
f"over_visibility allowlist names {key}, which is no longer a "
"`pub(crate)` item here; it is private, or it was never one"
)
return problems
def list_dead(data):
"""Name every dead item. A count tells a module is wide; this says which items."""
width = max(len(d["module"]) for d in data["dead_items"]) if data["dead_items"] else 0
for kind, label in (("deadonly", "named by nobody"), ("test", "named only by tests"),
("allowlisted", "kept `pub` by decision, reason in the budget file")):
rows = [d for d in data["dead_items"] if d["kind"] == kind]
print(f"\n{label} — {len(rows)} items")
for d in rows:
print(f" {d['module'].ljust(width)} {d['name'].ljust(34)} {d['file']}:{d['line']}")
totals = data["totals"]
print(f"\n{totals['dead']} dead of {totals['pub']} pub; "
f"{totals['deadonly']} of them unargued")
def list_overwide(data):
"""Name every over-wide `pub(crate)` item, with the file that declares it."""
items = data["overwide_items"]
width = max((len(d["module"]) for d in items), default=0)
for kind, label in (("overwide", "wider than anything reaches; a candidate for plain private"),
("allowlisted", "kept `pub(crate)` by decision, reason in the budget file")):
rows = [d for d in items if d["kind"] == kind]
print(f"\n{label} — {len(rows)} items")
for d in rows:
print(f" {d['module'].ljust(width)} {d['name'].ljust(34)} {d['file']}:{d['line']}")
totals = data["totals"]
print(f"\n{totals['overwide']} over-wide of {totals['priv']} pub(crate)")
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} {'overwd':>7} {'glob':>5} {'lines':>6} largest file")
print("-" * (width + 57))
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['overwide']:>7} {row['glob']:>5} "
f"{row['lines']:>6} {row['largest']:>4} {row['largest_file']}")
print("-" * (width + 57))
print(f"{'total'.ljust(width)} {totals['pub']:>4} {totals['dead']:>5} {totals['test']:>5} "
f"{totals['deadonly']:>7} {totals['priv']:>5} {totals['overwide']:>7} {totals['glob']:>5} "
f"{totals['lines']:>6} {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['overwide']} over-wide, "
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) | over-wide | 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['overwide']} | {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")
ap.add_argument("--list-dead", action="store_true", help="name every dead item with its file:line")
ap.add_argument("--list-overwide", action="store_true",
help="name every over-wide pub(crate) item with its file:line")
ap.add_argument("--allowlist", metavar="FILE", help="read the kept-item allowlist from FILE")
args = ap.parse_args()
data = census(
allow=load_allowlist(args.allowlist) if args.allowlist else None,
over_allow=load_over_visibility(args.allowlist) if args.allowlist else None,
)
if args.write_budget:
# Preserve any section another tool owns (for example `test_surface`,
# written by tools/test-surface.py). Two writers of one file must not
# erase each other, or the ratchet silently stops checking one axis.
# The same rule applies inside `dead_code`: the accepted counts are this
# tool's to write, the allowlist is a human's to argue.
existing = {}
if os.path.exists(args.write_budget):
try:
existing = json.load(open(args.write_budget))
except (ValueError, OSError):
existing = {}
out = dict(existing)
out["modules"] = data["modules"]
out["totals"] = data["totals"]
dead_code = dict(out.get("dead_code") or {})
dead_code["deadonly"] = {
mod: row["deadonly"] for mod, row in sorted(data["modules"].items())
}
out["dead_code"] = dead_code
# Same split as `dead_code`: the accepted count is the tool's to write,
# the allowlist of kept `pub(crate)` items is a human's to argue.
over = dict(out.get("over_visibility") or {})
over.setdefault("allowlist", {})
over["overwide"] = {
mod: row["overwide"] for mod, row in sorted(data["modules"].items())
}
out["over_visibility"] = over
with open(args.write_budget, "w") as handle:
json.dump(out, 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
if args.list_dead:
list_dead(data)
return 0
if args.list_overwide:
list_overwide(data)
return 0
print_census(data)
if args.budget:
with open(args.budget) as handle:
budget = json.load(handle)
over = check_budget(data, budget)
problems = check_dead_code(data, budget) + check_over_visibility(data, budget)
if over or problems:
if over:
print("\nOVER BUDGET — these numbers grew:")
for mod, key, allowed, actual in over:
print(f" {mod}.{key}: {actual} > {allowed}")
if problems:
print("\nDEAD CODE — every survivor must be counted, named and argued:")
for problem in problems:
print(f" {problem}")
return 1
print(f"\nwithin budget: {args.budget}")
if args.record:
record(data, args.record)
return 0
if __name__ == "__main__":
sys.exit(main())
|