Files
leleka/scripts/archcheck/measure.py
T
Pavlo Ratushnyi 82d31e68da STRA-338 S13: the source ratchets also skip an inline module under a test cfg
An inline `#[cfg(all(test, ...))] mod x {` proof module in a production file (gdn_chain, gdn_verification,
mtp_expert_workspace, kar_ple_cache) was counted. production_lines now skips it up to its closing brace
and still counts the code after it. Accounting only: env-read leleka-runtime 101 to 93, leleka-cuda-driver
77 to 76, instant-now strata-control 37 to 35; nothing rose.
2026-11-05 21:44:34 +01:00

170 lines
6.2 KiB
Python

"""Measurements taken from the workspace: package graph, file sizes, source pattern counts."""
import json
import pathlib
import re
import subprocess
TEST_DIRS = ("tests",)
def load_metadata(root):
"""Workspace packages with their normal internal and external dependencies."""
cmd = ["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"]
meta = json.loads(subprocess.run(cmd, cwd=root, check=True, capture_output=True, text=True).stdout)
internal = {p["name"] for p in meta["packages"]}
return sorted((_package(p, internal) for p in meta["packages"]), key=lambda p: p["name"])
def _package(raw, internal):
normal = [d["name"] for d in raw["dependencies"] if d["kind"] is None]
return {
"name": raw["name"],
"dir": pathlib.Path(raw["manifest_path"]).parent,
"normal": sorted({n for n in normal if n in internal}),
"external": sorted({n for n in normal if n not in internal}),
}
def rust_files(directory):
"""Every .rs file under a directory except build output."""
for path in sorted(directory.rglob("*.rs")):
if "target" not in path.relative_to(directory).parts:
yield path
def _text(path):
return path.read_text(encoding="utf-8", errors="replace")
def file_lines(root, packages):
"""{relative posix path: line count} for every .rs file in a workspace package."""
sizes = {}
for pkg in packages:
for path in rust_files(pkg["dir"]):
sizes[path.relative_to(root).as_posix()] = len(_text(path).splitlines())
return sizes
def is_test_file(path, src):
"""A test module in its own file counts like the inline `#[cfg(test)]` module it replaces."""
parts = path.relative_to(src).parts
return path.name == "tests.rs" or path.name.endswith("_tests.rs") or any(d in parts[:-1] for d in TEST_DIRS)
def production_lines(text):
"""Lines before the first `#[cfg(test)]` module (column 0, followed by `mod`); comment lines are dropped.
An inline module under another test cfg (`#[cfg(all(test, ...))]` then `mod x {`) is skipped up to its closing
`}` at column 0; the code after it still counts."""
lines = text.splitlines()
kept = []
index = 0
while index < len(lines):
line = lines[index]
following = lines[index + 1] if index + 1 < len(lines) else ""
if line.startswith("#[cfg(test)]") and following.startswith("mod "):
break
if _is_test_cfg(line) and line.startswith("#[cfg(") and following.startswith("mod ") and following.rstrip().endswith("{"):
index = _after_block(lines, index + 1)
continue
if not line.lstrip().startswith("//"):
kept.append(line)
index += 1
return kept
def _after_block(lines, start):
"""Index of the line after the column-0 `}` that closes the block opened at `start`."""
for index in range(start + 1, len(lines)):
if lines[index].startswith("}"):
return index + 1
return len(lines)
def count_patterns(packages, patterns):
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only (test files and modules declared under a test cfg are skipped)."""
compiled = [(p["id"], re.compile(p["regex"])) for p in patterns]
counts = {}
for pkg in packages:
for pid, n in _package_counts(pkg["dir"] / "src", compiled).items():
counts[f"{pid}:{pkg['name']}"] = n
return counts
_MOD_LINE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;")
_PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]')
def test_only_modules(src):
"""Files compiled only for tests: a `mod x;` declared under a `#[cfg(...test...)]` attribute (with or without a
`#[path]`). `_under_test_module` extends this to the files below such a module."""
found = set()
for path in rust_files(src):
for name, explicit in _test_declarations(_text(path)):
target = _module_file(path, name, explicit)
if target is not None:
found.add(target)
return found
def _test_declarations(text):
"""[(module name, #[path] value or None)] of the `mod x;` lines whose attribute block is a test cfg."""
out = []
attrs = []
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("#[") or (attrs and _unbalanced(" ".join(attrs))):
attrs.append(stripped)
continue
decl = _MOD_LINE.match(stripped)
if decl and _is_test_cfg(" ".join(attrs)):
explicit = _PATH_ATTR.search(" ".join(attrs))
out.append((decl.group(1), explicit.group(1) if explicit else None))
attrs = []
return out
def _unbalanced(text):
return text.count("[") > text.count("]") or text.count("(") > text.count(")")
def _is_test_cfg(block):
return "cfg(" in block and re.search(r"\btest\b", block) is not None and "not(test" not in block
def _module_file(declaring, name, explicit):
here = declaring.parent
if explicit:
target = (here / explicit).resolve()
return target if target.is_file() else None
base = here if declaring.name in ("lib.rs", "main.rs", "mod.rs") else here / declaring.stem
for candidate in (base / f"{name}.rs", base / name / "mod.rs"):
if candidate.is_file():
return candidate.resolve()
return None
def _under_test_module(path, test_files):
"""The file itself or a file in the directory a test-only module owns (`x.rs` owns `x/`, `mod.rs` its folder)."""
resolved = path.resolve()
for owner in test_files:
folder = owner.parent if owner.name == "mod.rs" else owner.with_suffix("")
if resolved == owner or resolved.is_relative_to(folder):
return True
return False
def _package_counts(src, compiled):
totals = {}
if not src.is_dir():
return totals
test_files = test_only_modules(src)
for path in rust_files(src):
if is_test_file(path, src) or _under_test_module(path, test_files):
continue
rows = production_lines(_text(path))
for pid, rx in compiled:
n = sum(len(rx.findall(row)) for row in rows)
if n:
totals[pid] = totals.get(pid, 0) + n
return totals