Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / tools / structure_check.py

structure_check.py545 lines · 21.9 KiBRaw
1#!/usr/bin/env python3
2"""Cheap structure ratchets for Modern-Apps (no build, stdlib only).
3
4Four checks, wired into ./check (see docs/structure/README.md):
5
6 wear Token-stream identity of the duplicated Wear protocol pairs
7 listed in docs/structure/wear-protocol-pairs.tsv. Each file is
8 normalized (package/import lines dropped, comments stripped
9 with a string-aware scanner) and the resulting token streams
10 must be identical per pair.
11 generated Every Kotlin/Rust file carrying a GENERATED/@generated header
12 (definition in docs/structure/README.md) must be listed in
13 docs/structure/generated-sources.tsv with a generator command,
14 and every listed file must still exist and carry the header.
15 Presence only: nothing is regenerated.
16 exceptions Every escape-hatch marker occurrence in Kotlin sources must
17 match docs/structure/exceptions.tsv exactly (type, file,
18 reason). Regenerate with --regen after an intentional change
19 and review the TSV diff; a new marker without a reason edit
20 fails here (and malformed markers fail lint anyway).
21
22 lines Total source lines (.kt/.java/.rs/.swift, tests included,
23 via git ls-files) must not exceed the baseline in
24 docs/structure/line-budget.json. Per-module totals are
25 printed. Excluded modules (data-driven, in that file --
26 currently the forthcoming communicate-dev module) do not
27 count. Shrinking passes; growing fails until the baseline
28 is deliberately bumped in the same change.
29
30Usage:
31 python3 tools/structure_check.py [wear|generated|exceptions|lines|all]
32 python3 tools/structure_check.py exceptions --regen
33 python3 tools/structure_check.py lines [--report|--regen]
34
35Exit code 0 = clean, 1 = violations (each violation is named).
36Scope exclusions follow root AGENTS.md "Never scan": build/, target/,
37third_party/, analysis/, personal/, .git/ etc. are never walked, and
38lint-rules/ + tools/ + docs/ are excluded from the marker/generated scans
39because they legitimately quote marker/header strings as data.
40"""
41import json
42import os
43import re
44import subprocess
45import sys
46
47ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
48DOCS = os.path.join(ROOT, "docs", "structure")
49WEAR_TSV = os.path.join(DOCS, "wear-protocol-pairs.tsv")
50GENERATED_TSV = os.path.join(DOCS, "generated-sources.tsv")
51EXCEPTIONS_TSV = os.path.join(DOCS, "exceptions.tsv")
52LINE_BUDGET_JSON = os.path.join(DOCS, "line-budget.json")
53SETTINGS_GRADLE = os.path.join(ROOT, "settings.gradle.kts")
54
55SKIP_DIRS = {
56 ".git", ".gradle", ".kotlin", "build", "target", "analysis",
57 "third_party", "personal", "release", "captures", ".idea", "__pycache__",
58}
59# Dirs whose files quote markers/headers as data, not as uses.
60DATA_DIRS = ("lint-rules/", "tools/", "docs/")
61
62
63def rel(path):
64 return os.path.relpath(path, ROOT).replace(os.sep, "/")
65
66
67def walk_files(exts):
68 for dirpath, dirnames, filenames in os.walk(ROOT):
69 dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
70 for name in sorted(filenames):
71 if name.endswith(exts):
72 yield os.path.join(dirpath, name)
73
74
75def is_data_path(rpath):
76 return rpath.startswith(DATA_DIRS)
77
78
79# ---------------------------------------------------------------- wear ----
80def strip_comments(text):
81 """Remove // and /* */ comments, respecting Kotlin strings/chars."""
82 out = []
83 i, n = 0, len(text)
84 while i < n:
85 if text.startswith('"""', i):
86 j = text.find('"""', i + 3)
87 j = n if j < 0 else j + 3
88 out.append(text[i:j]); i = j
89 elif text[i] == '"':
90 j = i + 1
91 while j < n and text[j] != '"':
92 j += 2 if text[j] == "\\" else 1
93 out.append(text[i:j + 1]); i = j + 1
94 elif text[i] == "'":
95 j = i + 1
96 while j < n and text[j] != "'":
97 j += 2 if text[j] == "\\" else 1
98 out.append(text[i:j + 1]); i = j + 1
99 elif text.startswith("//", i):
100 j = text.find("\n", i)
101 i = n if j < 0 else j
102 elif text.startswith("/*", i):
103 depth, j = 1, i + 2
104 while j < n and depth:
105 if text.startswith("/*", j):
106 depth += 1; j += 2
107 elif text.startswith("*/", j):
108 depth -= 1; j += 2
109 else:
110 j += 1
111 out.append(" "); i = j
112 else:
113 out.append(text[i]); i += 1
114 return "".join(out)
115
116
117TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|\d[\w.]*|[^\w\s]")
118
119
120def normalized_tokens(path):
121 text = open(path, encoding="utf-8", errors="ignore").read()
122 text = strip_comments(text)
123 lines = [
124 ln for ln in text.splitlines()
125 if not re.match(r"\s*(package|import)\s", ln)
126 ]
127 return TOKEN_RE.findall("\n".join(lines))
128
129
130def check_wear():
131 violations = []
132 pairs = []
133 for ln, line in enumerate(open(WEAR_TSV, encoding="utf-8"), 1):
134 if not line.strip() or line.startswith("#"):
135 continue
136 parts = line.rstrip("\n").split("\t")
137 if len(parts) != 3:
138 violations.append(f"wear: {WEAR_TSV}:{ln}: expected 3 tab-separated fields")
139 continue
140 pairs.append(parts)
141 for pair_id, phone, wear in pairs:
142 pp, wp = os.path.join(ROOT, phone), os.path.join(ROOT, wear)
143 if not os.path.isfile(pp):
144 violations.append(f"wear[{pair_id}]: missing phone file {phone}")
145 continue
146 if not os.path.isfile(wp):
147 violations.append(f"wear[{pair_id}]: missing wear file {wear}")
148 continue
149 a, b = normalized_tokens(pp), normalized_tokens(wp)
150 if a != b:
151 idx = next((k for k in range(min(len(a), len(b))) if a[k] != b[k]),
152 min(len(a), len(b)))
153 lo = max(0, idx - 6)
154 violations.append(
155 f"wear[{pair_id}]: DRIFT {phone} <-> {wear} "
156 f"(tokens phone={len(a)} wear={len(b)}, first diff at token {idx}: "
157 f"phone ...{' '.join(a[lo:idx + 6])} | wear ...{' '.join(b[lo:idx + 6])})")
158 print(f"wear: {len(pairs)} pairs checked")
159 return violations
160
161
162# ------------------------------------------------------------- generated ----
163GENERATED_RE = re.compile(
164 r"BEGIN GENERATED|@generated\b"
165 r"|^\s*(?://[!/]?|/\*+|\*)?\s*GENERATED\b"
166 r"|Code generated[^\n]*DO NOT EDIT|// Generated (constants|constant tables)"
167 r"|Do not hand-edit")
168HEADER_LINES = 40
169
170
171def has_generated_header(path):
172 try:
173 with open(path, encoding="utf-8", errors="ignore") as fh:
174 for i, line in enumerate(fh):
175 if i >= HEADER_LINES:
176 break
177 if GENERATED_RE.search(line):
178 return line.strip()
179 except OSError:
180 return None
181 return None
182
183
184def check_generated():
185 violations = []
186 listed = {}
187 for ln, line in enumerate(open(GENERATED_TSV, encoding="utf-8"), 1):
188 if not line.strip() or line.startswith("#"):
189 continue
190 parts = line.rstrip("\n").split("\t")
191 if len(parts) != 2 or not parts[1].strip():
192 violations.append(
193 f"generated: {GENERATED_TSV}:{ln}: expected '<path>\\t<generator command>'")
194 continue
195 listed[parts[0]] = parts[1]
196 found = {}
197 for path in walk_files((".kt", ".rs")):
198 rpath = rel(path)
199 if is_data_path(rpath):
200 continue
201 marker = has_generated_header(path)
202 if marker:
203 found[rpath] = marker
204 for rpath in sorted(found):
205 if rpath not in listed:
206 violations.append(
207 f"generated: UNLISTED {rpath} (header: {found[rpath][:100]}) "
208 f"-- add it to docs/structure/generated-sources.tsv with its generator")
209 for rpath in sorted(listed):
210 path = os.path.join(ROOT, rpath)
211 if not os.path.isfile(path):
212 violations.append(f"generated: STALE {rpath} listed but file is gone")
213 elif not has_generated_header(path):
214 violations.append(
215 f"generated: STALE {rpath} listed but its GENERATED header is gone")
216 print(f"generated: {len(found)} generated files in tree, {len(listed)} listed")
217 return violations
218
219
220# ------------------------------------------------------------ exceptions ----
221# Canonical markers (verbatim list in root AGENTS.md and
222# lint-rules ExceptionMarkerFormatDetector). type -> (keyword, reason prefix)
223MARKERS = [
224 ("PACKAGE_JNI", "PACKAGE STRUCTURE EXCEPTION (JNI)", None),
225 ("RAW_SCAFFOLD", "RAW SCAFFOLD EXCEPTION", "// RAW SCAFFOLD EXCEPTION:"),
226 ("TOAST", "TOAST EXCEPTION", "// TOAST EXCEPTION:"),
227 ("RAW_ANIMATION", "RAW ANIMATION EXCEPTION", "// RAW ANIMATION EXCEPTION:"),
228 ("SCAFFOLD_LOADING", "SCAFFOLD LOADING EXCEPTION", "// SCAFFOLD LOADING EXCEPTION:"),
229 ("SCAFFOLD_SEARCH", "SCAFFOLD SEARCH EXCEPTION", "// SCAFFOLD SEARCH EXCEPTION:"),
230 ("SCREENSHOT_COVERAGE", "SCREENSHOT COVERAGE EXCEPTION",
231 "// SCREENSHOT COVERAGE EXCEPTION:"),
232]
233
234
235def scan_exceptions():
236 # Aggregated by (type, file, reason) with an occurrence count: line
237 # numbers are deliberately not recorded, so moving a marker inside its
238 # file does not churn the inventory -- only adding, removing, or
239 # rewording a marker does (the growth this ratchet exists to catch).
240 from collections import Counter
241 counts = Counter()
242 total = 0
243 for path in walk_files((".kt", ".kts")):
244 rpath = rel(path)
245 if is_data_path(rpath):
246 continue
247 with open(path, encoding="utf-8", errors="ignore") as fh:
248 for line in fh:
249 for mtype, keyword, prefix in MARKERS:
250 if keyword in line:
251 if prefix is None:
252 reason = "JNI (verbatim marker; no free-text reason)"
253 else:
254 idx = line.find(prefix)
255 reason = (line[idx + len(prefix):].strip()
256 if idx >= 0 else "(malformed: no colon prefix)")
257 counts[(mtype, rpath, reason)] += 1
258 total += 1
259 break
260 rows = [(t, f, r, str(c)) for (t, f, r), c in sorted(counts.items())]
261 return rows, total
262
263
264def exceptions_tsv_text(rows):
265 out = ["# type\tfile\treason\tcount",
266 "# Generated by: python3 tools/structure_check.py exceptions --regen",
267 "# A new/changed marker requires regenerating this file and reviewing "
268 "the diff; the reason column is copied verbatim from the source marker."]
269 out += ["\t".join(r) for r in rows]
270 return "\n".join(out) + "\n"
271
272
273def check_exceptions(regen=False):
274 rows, total = scan_exceptions()
275 if regen:
276 with open(EXCEPTIONS_TSV, "w", encoding="utf-8", newline="\n") as fh:
277 fh.write(exceptions_tsv_text(rows))
278 print(f"exceptions: regenerated {EXCEPTIONS_TSV} with {total} markers")
279 return []
280 expected = exceptions_tsv_text(rows)
281 actual = ""
282 if os.path.isfile(EXCEPTIONS_TSV):
283 actual = open(EXCEPTIONS_TSV, encoding="utf-8").read()
284 if actual != expected:
285 exp = [l for l in expected.splitlines() if l and not l.startswith("#")]
286 act = [l for l in actual.splitlines() if l and not l.startswith("#")]
287 violations = []
288 for l in sorted(set(exp) - set(act)):
289 violations.append(f"exceptions: UNRECORDED {l}")
290 for l in sorted(set(act) - set(exp)):
291 violations.append(f"exceptions: STALE {l}")
292 violations.append(
293 "exceptions: run `python3 tools/structure_check.py exceptions --regen` "
294 "and review/commit the docs/structure/exceptions.tsv diff")
295 recorded = sum(int(l.split("\t")[3]) for l in act if len(l.split("\t")) == 4)
296 print(f"exceptions: {total} markers in tree, {recorded} recorded")
297 return violations
298 from collections import Counter
299 counts = Counter()
300 for r in rows:
301 counts[r[0]] += int(r[3])
302 print(f"exceptions: {total} markers recorded "
303 f"({', '.join(f'{k}={v}' for k, v in sorted(counts.items()))})")
304 return []
305
306
307# --------------------------------------------------------------- lines ----
308DEFAULT_SOURCE_EXTENSIONS = (".kt", ".java", ".rs", ".swift")
309DEFAULT_EXCLUDED_SEGMENTS = ("third_party", "build", "target")
310# Communicate dev module, pre-registered before it existed. The exact
311# Gradle/dir name is communicate-dev -- include(":communicate-dev")
312# with dir communicate-dev/ (settings.gradle.kts also has :madeveloper,
313# a different app). Only a module with exactly that name/dir is
314# excluded; every other module counts.
315DEFAULT_EXCLUDED_MODULES = ("communicate-dev",)
316
317
318def default_line_budget():
319 return {
320 "version": 1,
321 "extensions": list(DEFAULT_SOURCE_EXTENSIONS),
322 "excluded_path_segments": list(DEFAULT_EXCLUDED_SEGMENTS),
323 "excluded_modules": list(DEFAULT_EXCLUDED_MODULES),
324 "baseline_lines": 0,
325 "modules": {},
326 }
327
328
329def load_line_budget(path=LINE_BUDGET_JSON):
330 """Return (budget_dict, error_or_None). Defaults fill absent keys."""
331 budget = default_line_budget()
332 if not os.path.isfile(path):
333 return budget, f"lines: missing baseline {rel(path)} -- create it with " \
334 "`python3 tools/structure_check.py lines --regen`"
335 try:
336 with open(path, encoding="utf-8") as fh:
337 data = json.load(fh)
338 except (OSError, ValueError) as exc:
339 return budget, f"lines: cannot parse {rel(path)}: {exc}"
340 if not isinstance(data, dict):
341 return budget, f"lines: {rel(path)} must be a JSON object"
342 for key in budget:
343 if key in data:
344 budget[key] = data[key]
345 if not isinstance(budget["baseline_lines"], int) or budget["baseline_lines"] < 0:
346 return budget, f"lines: {rel(path)}: baseline_lines must be a non-negative int"
347 return budget, None
348
349
350def is_counted_source(rpath, extensions, excluded_segments):
351 if not rpath.endswith(tuple(extensions)):
352 return False
353 segments = rpath.split("/")
354 return not any(seg in excluded_segments for seg in segments)
355
356
357def parse_module_dirs(settings_text):
358 """Gradle module display name (slash form) -> project dir (slash form).
359
360 Parses include(":a:b") plus project(":a:b").projectDir = file("...")
361 overrides from settings.gradle.kts. includeBuild is not a module.
362 """
363 modules = {}
364 for match in re.finditer(r'include\("(:[^"]+)"\)', settings_text):
365 name = match.group(1)[1:].replace(":", "/")
366 modules[name] = name
367 for match in re.finditer(
368 r'project\("(:[^"]+)"\)\.projectDir\s*=\s*file\("([^"]+)"\)',
369 settings_text):
370 name = match.group(1)[1:].replace(":", "/")
371 if name in modules:
372 modules[name] = match.group(2).replace("\\", "/").strip("/")
373 return modules
374
375
376def module_for_path(rpath, module_dirs):
377 """Longest matching project dir wins; fallback is the top segment."""
378 best_name, best_len = None, -1
379 for name, mdir in module_dirs.items():
380 if (rpath == mdir or rpath.startswith(mdir + "/")) and len(mdir) > best_len:
381 best_name, best_len = name, len(mdir)
382 if best_name is not None:
383 return best_name
384 return rpath.split("/")[0] if "/" in rpath else "(root)"
385
386
387def is_excluded_module(module, excluded_modules):
388 for entry in excluded_modules:
389 norm = entry.strip().lstrip(":").replace(":", "/").strip("/")
390 if module == norm or module.replace("/", "-") == norm.replace("/", "-"):
391 return True
392 return False
393
394
395def count_source_lines(path):
396 """Logical lines: newline count, plus a final unterminated line."""
397 with open(path, "rb") as fh:
398 data = fh.read()
399 if not data:
400 return 0
401 return data.count(b"\n") + (0 if data.endswith(b"\n") else 1)
402
403
404def tally_lines(root, rpaths, module_dirs, budget):
405 """Return (total, per_module, excluded_total, excluded_per_module)."""
406 extensions = budget.get("extensions") or DEFAULT_SOURCE_EXTENSIONS
407 excluded_segments = set(budget.get("excluded_path_segments")
408 or DEFAULT_EXCLUDED_SEGMENTS)
409 excluded_modules = budget.get("excluded_modules") or []
410 per_module, excluded_per_module = {}, {}
411 total = excluded_total = 0
412 for rpath in rpaths:
413 if not is_counted_source(rpath, extensions, excluded_segments):
414 continue
415 try:
416 lines = count_source_lines(os.path.join(root, rpath))
417 except OSError:
418 continue # tracked file deleted in the working tree
419 module = module_for_path(rpath, module_dirs)
420 if is_excluded_module(module, excluded_modules):
421 excluded_per_module[module] = excluded_per_module.get(module, 0) + lines
422 excluded_total += lines
423 else:
424 per_module[module] = per_module.get(module, 0) + lines
425 total += lines
426 return total, per_module, excluded_total, excluded_per_module
427
428
429def list_source_files(root, extensions):
430 """git ls-files based enumeration (tracked + untracked, not ignored).
431
432 No full-tree walk: build/, target/, third_party/ etc. are filtered
433 afterwards by segment, and git itself drops ignored build outputs.
434 """
435 patterns = ["*" + ext for ext in extensions]
436 out = subprocess.check_output(
437 ["git", "-C", root, "ls-files", "--cached", "--others",
438 "--exclude-standard", "-z", "--"] + patterns)
439 return [p for p in out.decode("utf-8", errors="ignore").split("\0") if p]
440
441
442def write_line_budget(budget, total, per_module, path=LINE_BUDGET_JSON):
443 data = {
444 "version": 1,
445 "description": "Line-count ratchet baseline. Total source lines "
446 "(.kt/.java/.rs/.swift, tests included; third_party/, build/, "
447 "target/ segments excluded) must not exceed baseline_lines. "
448 "Shrinking passes; deliberate growth bumps baseline_lines in "
449 "the same change. Regenerate: python3 tools/structure_check.py "
450 "lines --regen (review the diff). Per-module figures are a "
451 "snapshot for reporting, not per-module caps.",
452 "extensions": list(budget.get("extensions") or DEFAULT_SOURCE_EXTENSIONS),
453 "excluded_path_segments": list(
454 budget.get("excluded_path_segments") or DEFAULT_EXCLUDED_SEGMENTS),
455 "excluded_modules": list(
456 budget.get("excluded_modules") or DEFAULT_EXCLUDED_MODULES),
457 "excluded_modules_note": "communicate-dev is the Communicate "
458 "dev module, pre-registered before it existed. The exact "
459 "name is include(\":communicate-dev\") with dir "
460 "communicate-dev/ (settings.gradle.kts also has "
461 ":madeveloper, a different app); only that exact module is "
462 "excluded.",
463 "baseline_lines": total,
464 "modules": dict(sorted(per_module.items())),
465 }
466 with open(path, "w", encoding="utf-8", newline="\n") as fh:
467 json.dump(data, fh, indent=2, sort_keys=False)
468 fh.write("\n")
469 return data
470
471
472def check_lines(regen=False, report=False):
473 budget, error = load_line_budget()
474 violations = []
475 if error and not regen:
476 return [error]
477 try:
478 settings_text = open(SETTINGS_GRADLE, encoding="utf-8").read()
479 except OSError:
480 settings_text = ""
481 module_dirs = parse_module_dirs(settings_text)
482 extensions = budget.get("extensions") or DEFAULT_SOURCE_EXTENSIONS
483 try:
484 rpaths = list_source_files(ROOT, extensions)
485 except (OSError, subprocess.CalledProcessError) as exc:
486 return [f"lines: git ls-files failed ({exc}); ratchet cannot run"]
487 total, per_module, excluded_total, excluded_per = tally_lines(
488 ROOT, rpaths, module_dirs, budget)
489 if regen:
490 write_line_budget(budget, total, per_module)
491 print(f"lines: regenerated {rel(LINE_BUDGET_JSON)} "
492 f"at {total:,} lines ({len(per_module)} modules)")
493 return []
494 baseline = budget["baseline_lines"]
495 print(f"lines: {total:,} source lines, baseline {baseline:,}, "
496 f"{len(per_module)} modules"
497 + (f", excluded {excluded_total:,} lines in "
498 f"{', '.join(sorted(excluded_per))}" if excluded_total else
499 " (excluded modules: "
500 + ", ".join(budget.get("excluded_modules") or []) + ")"))
501 for module in sorted(per_module, key=lambda m: (-per_module[m], m)):
502 print(f"lines: {per_module[module]:>9,} {module}")
503 if report:
504 print("lines: --report only, ratchet not enforced")
505 return []
506 if total > baseline:
507 violations.append(
508 f"lines: total {total:,} exceeds baseline {baseline:,} by "
509 f"{total - baseline:,} -- cut lines, or if this growth is "
510 f"deliberate bump the baseline in the same change: "
511 f"`python3 tools/structure_check.py lines --regen` and review "
512 f"the docs/structure/line-budget.json diff")
513 else:
514 print(f"lines: {baseline - total:,} lines of headroom under baseline")
515 return violations
516
517
518def main(argv):
519 which = argv[1] if len(argv) > 1 else "all"
520 regen = "--regen" in argv
521 report = "--report" in argv
522 violations = []
523 if which in ("wear", "all"):
524 violations += check_wear()
525 if which in ("generated", "all"):
526 violations += check_generated()
527 if which in ("exceptions", "all"):
528 violations += check_exceptions(regen=regen)
529 if which in ("lines", "all"):
530 violations += check_lines(regen=regen and which == "lines",
531 report=report and which == "lines")
532 if which not in ("wear", "generated", "exceptions", "lines", "all"):
533 print(__doc__)
534 return 2
535 if violations:
536 print("\nSTRUCTURE CHECK FAILURES:")
537 for v in violations:
538 print(f" - {v}")
539 return 1
540 print("structure: OK")
541 return 0
542
543
544if __name__ == "__main__":
545 sys.exit(main(sys.argv))