STRA-338 S6 part 2: SSE streaming leaves responses.rs; architecture gate rewritten to the 301 limits
The text, buffered and tool-call streaming code of the Responses API (750 lines) moves from control-plane/src/responses.rs to responses/stream.rs without a logic change, and the architecture gate becomes a small package (scripts/archcheck) whose functions stay within 30 lines, complexity 10, nesting 4 and 5 parameters. The source counters now stop only at a column-0 cfg(test) module, so a single cfg(test) function no longer hides the code after it; that raises some measured baselines (cuda-driver, runtime, model-format, strata-control) without any code change, and the baseline was rewritten using --allow-increase for that reason alone. Verified: cargo test -p strata-control 277 lib tests, 0 failed; 18 gate self-tests pass; fmt clean.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Dependency-direction and size gate for the hexagonal architecture (LeaseVibe STRA-338). See check-architecture.py."""
|
||||
@@ -0,0 +1,90 @@
|
||||
"""The baseline file: what may be written to it, and what a rewrite may never raise."""
|
||||
import json
|
||||
|
||||
EMPTY = {"violations": [], "oversize": {}, "source": {}}
|
||||
COMMENT = ("Debt that exists today. Every number may only fall (scripts/check-architecture.py --update-baseline "
|
||||
"refuses to raise one). Do not edit by hand; regenerate. Policy: architecture.json.")
|
||||
|
||||
|
||||
def load(path):
|
||||
"""The baseline at `path`, or an empty one when the file does not exist."""
|
||||
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else json.loads(json.dumps(EMPTY))
|
||||
|
||||
|
||||
def save(path, baseline):
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(json.dumps(baseline, indent=1) + "\n")
|
||||
|
||||
|
||||
def build(limit, violations, sizes, counts):
|
||||
"""The baseline that describes the current state."""
|
||||
return {
|
||||
"_comment": COMMENT,
|
||||
"violations": sorted(violations),
|
||||
"oversize": {p: n for p, n in sorted(sizes.items()) if n > limit},
|
||||
"source": dict(sorted(counts.items())),
|
||||
}
|
||||
|
||||
|
||||
def _stem_root(path, oversize):
|
||||
"""The oversize file `path` was split from: a same-stem directory (responses.rs -> responses/*.rs)."""
|
||||
parts = path.split("/")
|
||||
for depth in range(len(parts) - 1, 0, -1):
|
||||
root = "/".join(parts[:depth]) + ".rs"
|
||||
if root in oversize:
|
||||
return root
|
||||
return None
|
||||
|
||||
|
||||
def _family_lines(old, new):
|
||||
totals = {}
|
||||
for path, n in new.items():
|
||||
root = path if path in old else _stem_root(path, old)
|
||||
if root:
|
||||
totals[root] = totals.get(root, 0) + n
|
||||
return totals
|
||||
|
||||
|
||||
def _moved(path, lines, old, new):
|
||||
"""Same base name and no more lines than an oversize entry that disappeared: the file moved."""
|
||||
name = path.rsplit("/", 1)[-1]
|
||||
gone = [n for p, n in old.items() if p not in new and p.rsplit("/", 1)[-1] == name]
|
||||
return any(lines <= before for before in gone)
|
||||
|
||||
|
||||
def _oversize_problem(path, lines, old, new, family):
|
||||
if path in old:
|
||||
grew = lines > old[path] and family[path] > old[path]
|
||||
return f"oversize {path}: {old[path]} -> {lines}" if grew else None
|
||||
root = _stem_root(path, old)
|
||||
if root:
|
||||
too_big = family[root] > old[root]
|
||||
return f"oversize {path}: split of {root} holds {family[root]} lines, was {old[root]}" if too_big else None
|
||||
return None if _moved(path, lines, old, new) else f"oversize {path}: new file with {lines} lines"
|
||||
|
||||
|
||||
def raised_oversize(old, new):
|
||||
"""Problems for an oversize section that gained lines. Moves and same-stem splits are not gains."""
|
||||
family = _family_lines(old, new)
|
||||
found = [_oversize_problem(p, n, old, new, family) for p, n in new.items()]
|
||||
return [problem for problem in found if problem]
|
||||
|
||||
|
||||
def _totals(section):
|
||||
totals = {}
|
||||
for key, n in section.items():
|
||||
pid = key.split(":", 1)[0]
|
||||
totals[pid] = totals.get(pid, 0) + n
|
||||
return totals
|
||||
|
||||
|
||||
def raised_source(old, new):
|
||||
"""Problems for a source ratchet whose total over all crates rose (code that moved crates keeps its total)."""
|
||||
before, after = _totals(old), _totals(new)
|
||||
return [f"source {pid}: total {before.get(pid, 0)} -> {n}" for pid, n in after.items() if n > before.get(pid, 0)]
|
||||
|
||||
|
||||
def raised(old, new):
|
||||
"""Everything a baseline rewrite would raise."""
|
||||
problems = [f"new violation {v}" for v in new["violations"] if v not in old["violations"]]
|
||||
return problems + raised_oversize(old["oversize"], new["oversize"]) + raised_source(old["source"], new["source"])
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Command line of the architecture gate."""
|
||||
import argparse
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from . import baseline as bl
|
||||
from . import measure, rules
|
||||
|
||||
CONFIG, BASELINE = "architecture.json", "architecture-baseline.json"
|
||||
|
||||
|
||||
def parse_args(argv, default_root):
|
||||
parser = argparse.ArgumentParser(description="Dependency-direction, size and source-ratchet gate (STRA-338).")
|
||||
parser.add_argument("--root", default=str(default_root))
|
||||
flag = {"action": "store_true"}
|
||||
parser.add_argument("--update-baseline", help="rewrite the baseline; refuses to raise a number", **flag)
|
||||
parser.add_argument("--allow-increase", help="with --update-baseline: allow raising, justify in review", **flag)
|
||||
parser.add_argument("--report", action="store_true", help="print the layer graph, the census and the ratchets")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def report(packages, config, sizes, counts):
|
||||
layers = rules.layer_index(config)
|
||||
for layer, names in config["layers"].items():
|
||||
print(f"{layer}: {', '.join(names) if names else '(none yet)'}")
|
||||
for pkg in packages:
|
||||
print(f"{pkg['name']:30} {layers.get(pkg['name'], ['?'])[0]} -> {', '.join(pkg['normal'])}")
|
||||
over = sorted(((n, p) for p, n in sizes.items() if n > config["max_lines"]), reverse=True)
|
||||
print(f"\n{len(over)} files over {config['max_lines']} lines; total {sum(n for n, _ in over)} lines")
|
||||
for n, path in over[:15]:
|
||||
print(f" {n:6} {path}")
|
||||
print("\n".join(f" {key} = {n}" for key, n in sorted(counts.items())))
|
||||
|
||||
|
||||
def update_baseline(path, old, current, allow_increase):
|
||||
"""Write the baseline; without --allow-increase refuse to raise anything. Returns the exit code."""
|
||||
problems = [] if allow_increase or not path.exists() else bl.raised(old, current)
|
||||
if problems:
|
||||
print("refusing to raise the baseline (use --allow-increase and justify it in review):", file=sys.stderr)
|
||||
print("\n".join(f" {p}" for p in problems), file=sys.stderr)
|
||||
return 1
|
||||
bl.save(path, current)
|
||||
print(f"wrote {path.name}: {len(current['violations'])} violations, {len(current['oversize'])} oversize files, "
|
||||
f"{len(current['source'])} ratchets")
|
||||
return 0
|
||||
|
||||
|
||||
def print_findings(found):
|
||||
for line in found.debt:
|
||||
print(f"debt (baseline): {line}")
|
||||
for line in found.stale:
|
||||
print(f"stale baseline: {line} (scripts/check-architecture.py --update-baseline)")
|
||||
for line in found.errors:
|
||||
print(f"ERROR: {line}", file=sys.stderr)
|
||||
print(f"architecture: {len(found.errors)} errors, {len(found.debt)} baselined violations, "
|
||||
f"{len(found.stale)} stale baseline entries")
|
||||
return 1 if found.errors else 0
|
||||
|
||||
|
||||
def main(argv, default_root):
|
||||
args = parse_args(argv, default_root)
|
||||
root = pathlib.Path(args.root).resolve()
|
||||
config = json.loads((root / CONFIG).read_text(encoding="utf-8"))
|
||||
baseline_path = root / BASELINE
|
||||
old = bl.load(baseline_path)
|
||||
packages = measure.load_metadata(root)
|
||||
sizes = measure.file_lines(root, packages)
|
||||
counts = measure.count_patterns(packages, config["source_patterns"])
|
||||
found = rules.evaluate(packages, config, old, sizes, counts)
|
||||
if args.report:
|
||||
report(packages, config, sizes, counts)
|
||||
return 0
|
||||
if args.update_baseline:
|
||||
current = bl.build(config["max_lines"], found.violations, sizes, counts)
|
||||
return update_baseline(baseline_path, old, current, args.allow_increase)
|
||||
return print_findings(found)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""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."""
|
||||
lines = text.splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
if line.startswith("#[cfg(test)]") and index + 1 < len(lines) and lines[index + 1].startswith("mod "):
|
||||
return [row for row in lines[:index] if not row.lstrip().startswith("//")]
|
||||
return [row for row in lines if not row.lstrip().startswith("//")]
|
||||
|
||||
|
||||
def count_patterns(packages, patterns):
|
||||
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only."""
|
||||
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
|
||||
|
||||
|
||||
def _package_counts(src, compiled):
|
||||
totals = {}
|
||||
if not src.is_dir():
|
||||
return totals
|
||||
for path in rust_files(src):
|
||||
if is_test_file(path, src):
|
||||
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
|
||||
@@ -0,0 +1,129 @@
|
||||
"""The rules, as pure functions over plain data (no cargo, no file system)."""
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass
|
||||
class Findings:
|
||||
errors: list = field(default_factory=list)
|
||||
debt: list = field(default_factory=list)
|
||||
stale: list = field(default_factory=list)
|
||||
violations: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
def layer_index(config):
|
||||
"""{package: [layers]}; a package listed twice is reported by `assignment_errors`."""
|
||||
index = {}
|
||||
for layer, names in config["layers"].items():
|
||||
for name in names:
|
||||
index.setdefault(name, []).append(layer)
|
||||
return index
|
||||
|
||||
|
||||
def assignment_errors(packages, config):
|
||||
"""Every workspace package must have exactly one layer, and every listed name must be a package."""
|
||||
layers, known, errors = layer_index(config), {p["name"] for p in packages}, []
|
||||
for name, assigned in sorted(layers.items()):
|
||||
if len(assigned) > 1:
|
||||
errors.append(f"{name} is assigned to more than one layer: {assigned}")
|
||||
if name not in known:
|
||||
errors.append(f"{name} has a layer in architecture.json but is not a workspace package")
|
||||
order = list(config["layers"])
|
||||
errors += [f"{p['name']} has no layer in architecture.json: assign it to one of {order}"
|
||||
for p in packages if p["name"] not in layers]
|
||||
return errors
|
||||
|
||||
|
||||
def edge_violations(pkg, config):
|
||||
"""{key: message} for the layer and adapter edges of one package."""
|
||||
layers = layer_index(config)
|
||||
rank = {layer: i for i, layer in enumerate(config["layers"])}
|
||||
name, mine = pkg["name"], layers[pkg["name"]][0]
|
||||
sideways = {tuple(e) for e in config["adapter_edges"]}
|
||||
found = {}
|
||||
for dep in (d for d in pkg["normal"] if d in layers):
|
||||
theirs = layers[dep][0]
|
||||
if rank[theirs] > rank[mine]:
|
||||
found[f"layer-up {name} -> {dep}"] = f"{name} ({mine}) depends on {dep} ({theirs})"
|
||||
elif mine == theirs == config["adapter_layer"] and (name, dep) not in sideways:
|
||||
found[f"adapter-sideways {name} -> {dep}"] = (
|
||||
f"adapter {name} depends on adapter {dep}; list the edge in adapter_edges only if it is a real port")
|
||||
return found
|
||||
|
||||
|
||||
def purity_violations(pkg, config):
|
||||
"""{key: message} for forbidden external crates in a pure layer."""
|
||||
name, layer = pkg["name"], layer_index(config)[pkg["name"]][0]
|
||||
if layer not in config["pure_layers"]:
|
||||
return {}
|
||||
banned = set(config["forbidden_in_pure"])
|
||||
return {f"forbidden-dep {name} {ext}": f"{name} ({layer}) must stay pure but uses {ext}"
|
||||
for ext in pkg["external"] if ext in banned}
|
||||
|
||||
|
||||
def graph_violations(packages, config):
|
||||
"""All layer, adapter and purity violations of the workspace."""
|
||||
layers, found = layer_index(config), {}
|
||||
for pkg in (p for p in packages if p["name"] in layers):
|
||||
found.update(edge_violations(pkg, config))
|
||||
found.update(purity_violations(pkg, config))
|
||||
return found
|
||||
|
||||
|
||||
def classify(violations, baseline):
|
||||
"""Split violations into new errors and baselined debt; report baseline entries that no longer apply."""
|
||||
known = set(baseline["violations"])
|
||||
errors = [message for key, message in sorted(violations.items()) if key not in known]
|
||||
debt = [key for key in sorted(violations) if key in known]
|
||||
stale = [f"violation no longer present: {key}" for key in baseline["violations"] if key not in violations]
|
||||
return errors, debt, stale
|
||||
|
||||
|
||||
def _size_error(path, lines, allowed, limit):
|
||||
if allowed is None:
|
||||
return f"{path} has {lines} lines (limit {limit}); split it instead of adding a new large file"
|
||||
if lines > allowed:
|
||||
return f"{path} grew to {lines} lines (baseline {allowed}); large files may only shrink"
|
||||
return None
|
||||
|
||||
|
||||
def _size_stale(path, allowed, now, limit):
|
||||
if now is None:
|
||||
return f"oversize entry for a file that is gone: {path}"
|
||||
if now <= limit:
|
||||
return f"{path} is now {now} lines, under the limit: drop its baseline entry"
|
||||
if now < allowed:
|
||||
return f"{path} shrank from {allowed} to {now} lines: tighten the baseline"
|
||||
return None
|
||||
|
||||
|
||||
def size_findings(sizes, baseline, limit):
|
||||
"""(errors, stale) for the per-file line limit and the per-file non-growth rule."""
|
||||
errors = [_size_error(p, n, baseline["oversize"].get(p), limit) for p, n in sorted(sizes.items()) if n > limit]
|
||||
stale = [_size_stale(p, allowed, sizes.get(p), limit) for p, allowed in baseline["oversize"].items()]
|
||||
return [e for e in errors if e], [s for s in stale if s]
|
||||
|
||||
|
||||
def ratchet_findings(counts, baseline):
|
||||
"""(errors, stale) for source pattern counts, which may only fall."""
|
||||
errors, stale = [], []
|
||||
for key, n in sorted(counts.items()):
|
||||
allowed = baseline["source"].get(key, 0)
|
||||
if n > allowed:
|
||||
errors.append(f"source ratchet {key} rose to {n} (baseline {allowed}); the count may only fall")
|
||||
elif n < allowed:
|
||||
stale.append(f"source ratchet {key} fell from {allowed} to {n}: tighten the baseline")
|
||||
stale += [f"source ratchet {key} is now 0 (baseline {allowed}): tighten the baseline"
|
||||
for key, allowed in baseline["source"].items() if key not in counts]
|
||||
return errors, stale
|
||||
|
||||
|
||||
def evaluate(packages, config, baseline, sizes, counts):
|
||||
"""Run every rule. Returns Findings."""
|
||||
result = Findings(errors=assignment_errors(packages, config))
|
||||
result.violations = graph_violations(packages, config)
|
||||
errors, result.debt, stale = classify(result.violations, baseline)
|
||||
size_errors, size_stale = size_findings(sizes, baseline, config["max_lines"])
|
||||
ratchet_errors, ratchet_stale = ratchet_findings(counts, baseline)
|
||||
result.errors += errors + size_errors + ratchet_errors
|
||||
result.stale = stale + size_stale + ratchet_stale
|
||||
return result
|
||||
+13
-278
@@ -1,291 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Dependency-direction and size gate for the hexagonal architecture (LeaseVibe STRA-338, ADR on that item).
|
||||
|
||||
Rules, all read from `architecture.json` (the policy) and `architecture-baseline.json` (the debt that exists today):
|
||||
Rules, read from `architecture.json` (the policy) and `architecture-baseline.json` (the debt that exists today):
|
||||
|
||||
layers every workspace package has exactly one layer (L0 contract .. L4 host); a normal dependency must point to the
|
||||
same or a LOWER layer. A higher-layer edge is a violation.
|
||||
adapters inside L3 a crate may depend on another L3 crate only through an edge listed in "adapter_edges"
|
||||
(adapters point inward to ports, not sideways to each other).
|
||||
pure packages in "pure_layers" (L0, L1) must not use the "forbidden_in_pure" external crates (async runtime, HTTP, ...).
|
||||
size no .rs file over "max_lines"; a file already over it may not grow beyond its baseline entry.
|
||||
ratchet counts of "source_patterns" (env reads, Instant::now, #[path] includes, process globals, dyn) per crate may only fall.
|
||||
layers every workspace package has exactly one layer (L0 contract .. L4 host); a normal dependency must point to
|
||||
the same or a LOWER layer.
|
||||
adapters inside L3 a crate may depend on another L3 crate only through an edge listed in "adapter_edges".
|
||||
pure packages in "pure_layers" must not use the "forbidden_in_pure" external crates.
|
||||
size no .rs file over "max_lines"; a file already over it may not grow beyond its baseline entry.
|
||||
ratchet counts of "source_patterns" (env reads, Instant::now, #[path], process globals, dyn) may only fall.
|
||||
|
||||
A violation that is listed in the baseline is reported as debt and does not fail. A baseline entry that no longer applies is
|
||||
reported as "stale" (run --update-baseline to drop it). The baseline can only be lowered with --update-baseline; raising it needs
|
||||
--allow-increase and is visible in review. Pure stdlib Python, no network, no GPU; it is a build-time check, never part of serving.
|
||||
A violation listed in the baseline is debt and does not fail. The baseline can only be lowered with --update-baseline;
|
||||
raising it needs --allow-increase and is visible in review. Pure stdlib Python, no network, no GPU: a build-time check.
|
||||
|
||||
Usage:
|
||||
scripts/check-architecture.py check (exit 1 on a new violation)
|
||||
scripts/check-architecture.py --update-baseline rewrite the baseline to the current state; refuses to raise any number
|
||||
scripts/check-architecture.py --update-baseline --allow-increase
|
||||
scripts/check-architecture.py --report print the layer graph, the oversize census and the ratchet counts
|
||||
Usage: scripts/check-architecture.py [--update-baseline [--allow-increase]] [--report]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
CONFIG = "architecture.json"
|
||||
BASELINE = "architecture-baseline.json"
|
||||
|
||||
|
||||
def load_metadata(root):
|
||||
out = subprocess.run(["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"],
|
||||
cwd=root, check=True, capture_output=True, text=True).stdout
|
||||
meta = json.loads(out)
|
||||
packages = []
|
||||
internal = {p["name"] for p in meta["packages"]}
|
||||
for p in meta["packages"]:
|
||||
packages.append({
|
||||
"name": p["name"],
|
||||
"dir": pathlib.Path(p["manifest_path"]).parent,
|
||||
"normal": sorted({d["name"] for d in p["dependencies"] if d["kind"] is None and d["name"] in internal}),
|
||||
"external": sorted({d["name"] for d in p["dependencies"] if d["kind"] is None and d["name"] not in internal}),
|
||||
})
|
||||
return sorted(packages, key=lambda p: p["name"])
|
||||
|
||||
|
||||
def rust_files(directory):
|
||||
for path in sorted(directory.rglob("*.rs")):
|
||||
if "target" in path.relative_to(directory).parts:
|
||||
continue
|
||||
yield path
|
||||
|
||||
|
||||
def file_lines(root, packages):
|
||||
"""{relative posix path: line count} for every .rs file in a workspace package."""
|
||||
result = {}
|
||||
for pkg in packages:
|
||||
for path in rust_files(pkg["dir"]):
|
||||
result[path.relative_to(root).as_posix()] = len(path.read_text(encoding="utf-8", errors="replace").splitlines())
|
||||
return result
|
||||
|
||||
|
||||
def count_patterns(root, packages, patterns):
|
||||
"""{"<pattern id>:<crate>": n} for the non-zero counts. Only src/ files, and only the lines before the first
|
||||
column-0 `#[cfg(test)]` of a file (test modules sit at the bottom by convention); comment lines and test files are skipped."""
|
||||
compiled = [(p["id"], re.compile(p["regex"])) for p in patterns]
|
||||
counts = {}
|
||||
for pkg in packages:
|
||||
src = pkg["dir"] / "src"
|
||||
if not src.is_dir():
|
||||
continue
|
||||
for path in rust_files(src):
|
||||
if path.name == "tests.rs" or path.name.endswith("_tests.rs") or "tests" in path.relative_to(src).parts[:-1]:
|
||||
continue # a test module moved to its own file counts like the inline `#[cfg(test)]` module it replaces
|
||||
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
if line.startswith("#[cfg(test)]"):
|
||||
break
|
||||
if line.lstrip().startswith("//"):
|
||||
continue
|
||||
for pid, rx in compiled:
|
||||
n = len(rx.findall(line))
|
||||
if n:
|
||||
key = f"{pid}:{pkg['name']}"
|
||||
counts[key] = counts.get(key, 0) + n
|
||||
return counts
|
||||
|
||||
|
||||
def layer_index(config):
|
||||
index = {}
|
||||
for layer, names in config["layers"].items():
|
||||
for name in names:
|
||||
index.setdefault(name, []).append(layer)
|
||||
return index
|
||||
|
||||
|
||||
def evaluate(packages, config, baseline, sizes, counts):
|
||||
"""Pure function over plain data. Returns (errors, debt, stale, current_violations)."""
|
||||
errors, debt, stale = [], [], []
|
||||
layers = layer_index(config)
|
||||
order = list(config["layers"])
|
||||
rank = {layer: i for i, layer in enumerate(order)}
|
||||
pure = set(config["pure_layers"])
|
||||
forbidden = set(config["forbidden_in_pure"])
|
||||
adapter_layer = config["adapter_layer"]
|
||||
adapter_edges = {tuple(e) for e in config["adapter_edges"]}
|
||||
known = {p["name"] for p in packages}
|
||||
violations = {}
|
||||
|
||||
for name in sorted(layers):
|
||||
if len(layers[name]) > 1:
|
||||
errors.append(f"{name} is assigned to more than one layer: {layers[name]}")
|
||||
if name not in known:
|
||||
errors.append(f"{name} has a layer in {CONFIG} but is not a workspace package")
|
||||
for pkg in packages:
|
||||
name = pkg["name"]
|
||||
if name not in layers:
|
||||
errors.append(f"{name} has no layer in {CONFIG}: assign it to one of {order}")
|
||||
continue
|
||||
mine = layers[name][0]
|
||||
for dep in pkg["normal"]:
|
||||
if dep not in layers:
|
||||
continue
|
||||
theirs = layers[dep][0]
|
||||
if rank[theirs] > rank[mine]:
|
||||
violations[f"layer-up {name} -> {dep}"] = f"{name} ({mine}) depends on {dep} ({theirs})"
|
||||
elif mine == theirs == adapter_layer and (name, dep) not in adapter_edges:
|
||||
violations[f"adapter-sideways {name} -> {dep}"] = (
|
||||
f"adapter {name} depends on adapter {dep}; add the edge to adapter_edges only if it is a real port")
|
||||
if mine in pure:
|
||||
for ext in pkg["external"]:
|
||||
if ext in forbidden:
|
||||
violations[f"forbidden-dep {name} {ext}"] = f"{name} ({mine}) must stay pure but depends on {ext}"
|
||||
|
||||
for key, message in sorted(violations.items()):
|
||||
(debt if key in baseline["violations"] else errors).append(message if key not in baseline["violations"] else key)
|
||||
stale += [f"violation no longer present: {key}" for key in baseline["violations"] if key not in violations]
|
||||
|
||||
limit = config["max_lines"]
|
||||
for path, lines in sorted(sizes.items()):
|
||||
if lines <= limit:
|
||||
continue
|
||||
allowed = baseline["oversize"].get(path)
|
||||
if allowed is None:
|
||||
errors.append(f"{path} has {lines} lines (limit {limit}); split it instead of adding a new large file")
|
||||
elif lines > allowed:
|
||||
errors.append(f"{path} grew to {lines} lines (baseline {allowed}); large files may only shrink")
|
||||
for path, allowed in baseline["oversize"].items():
|
||||
now = sizes.get(path)
|
||||
if now is None:
|
||||
stale.append(f"oversize entry for a file that is gone: {path}")
|
||||
elif now <= limit:
|
||||
stale.append(f"{path} is now {now} lines, under the limit: drop its baseline entry")
|
||||
elif now < allowed:
|
||||
stale.append(f"{path} shrank from {allowed} to {now} lines: tighten the baseline")
|
||||
|
||||
for key, n in sorted(counts.items()):
|
||||
allowed = baseline["source"].get(key, 0)
|
||||
if n > allowed:
|
||||
errors.append(f"source ratchet {key} rose to {n} (baseline {allowed}); the count may only fall")
|
||||
elif n < allowed:
|
||||
stale.append(f"source ratchet {key} fell from {allowed} to {n}: tighten the baseline")
|
||||
for key, allowed in baseline["source"].items():
|
||||
if key not in counts:
|
||||
stale.append(f"source ratchet {key} is now 0 (baseline {allowed}): tighten the baseline")
|
||||
return errors, debt, stale, violations
|
||||
|
||||
|
||||
def new_baseline(config, violations, sizes, counts):
|
||||
limit = config["max_lines"]
|
||||
return {
|
||||
"_comment": "Debt that exists today. Every number may only fall (scripts/check-architecture.py --update-baseline refuses to raise one). "
|
||||
"Do not edit by hand; regenerate. Policy: architecture.json.",
|
||||
"violations": sorted(violations),
|
||||
"oversize": {p: n for p, n in sorted(sizes.items()) if n > limit},
|
||||
"source": dict(sorted(counts.items())),
|
||||
}
|
||||
|
||||
|
||||
def raised(old, new):
|
||||
"""Entries of `new` that are absent from or larger than `old` (a baseline update may only lower)."""
|
||||
problems = []
|
||||
for v in new["violations"]:
|
||||
if v not in old["violations"]:
|
||||
problems.append(f"new violation {v}")
|
||||
# a file that moved (same base name, no more lines than the entry that disappeared) is not an increase
|
||||
gone = {}
|
||||
for path, n in old["oversize"].items():
|
||||
if path not in new["oversize"]:
|
||||
gone.setdefault(path.rsplit("/", 1)[-1], []).append(n)
|
||||
# a file split into a directory of the same stem (responses.rs -> responses/*.rs): the family may not hold more lines than the original
|
||||
def family(path):
|
||||
parts = path.split("/")
|
||||
for depth in range(len(parts) - 1, 0, -1):
|
||||
root = "/".join(parts[:depth]) + ".rs"
|
||||
if root in old["oversize"]:
|
||||
return root
|
||||
return None
|
||||
family_lines = {}
|
||||
for path, n in new["oversize"].items():
|
||||
root = path if path in old["oversize"] else family(path)
|
||||
if root:
|
||||
family_lines[root] = family_lines.get(root, 0) + n
|
||||
for path, n in new["oversize"].items():
|
||||
if path in old["oversize"]:
|
||||
if n > old["oversize"][path] and family_lines[path] > old["oversize"][path]:
|
||||
problems.append(f"oversize {path}: {old['oversize'][path]} -> {n}")
|
||||
elif family(path):
|
||||
root = family(path)
|
||||
if family_lines[root] > old["oversize"][root]:
|
||||
problems.append(f"oversize {path}: split of {root} holds {family_lines[root]} lines, was {old['oversize'][root]}")
|
||||
elif not any(n <= before for before in gone.get(path.rsplit("/", 1)[-1], [])):
|
||||
problems.append(f"oversize {path}: new file with {n} lines")
|
||||
# code that moved to another crate raises the destination and lowers the source: compare the total per pattern
|
||||
def totals(section):
|
||||
result = {}
|
||||
for key, n in section.items():
|
||||
result[key.split(":", 1)[0]] = result.get(key.split(":", 1)[0], 0) + n
|
||||
return result
|
||||
before, after = totals(old["source"]), totals(new["source"])
|
||||
for pid, n in after.items():
|
||||
if n > before.get(pid, 0):
|
||||
problems.append(f"source {pid}: total {before.get(pid, 0)} -> {n}")
|
||||
return problems
|
||||
|
||||
|
||||
def report(packages, config, sizes, counts):
|
||||
layers = layer_index(config)
|
||||
for layer, names in config["layers"].items():
|
||||
print(f"{layer}: {', '.join(names) if names else '(none yet)'}")
|
||||
print()
|
||||
for pkg in packages:
|
||||
print(f"{pkg['name']:28} {layers.get(pkg['name'], ['?'])[0]} -> {', '.join(pkg['normal'])}")
|
||||
over = sorted(((n, p) for p, n in sizes.items() if n > config["max_lines"]), reverse=True)
|
||||
print(f"\n{len(over)} files over {config['max_lines']} lines; total {sum(n for n, _ in over)} lines")
|
||||
for n, p in over[:15]:
|
||||
print(f" {n:6} {p}")
|
||||
print("\nsource counts:")
|
||||
for key, n in sorted(counts.items()):
|
||||
print(f" {key} = {n}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--root", default=str(pathlib.Path(__file__).resolve().parent.parent))
|
||||
parser.add_argument("--update-baseline", action="store_true")
|
||||
parser.add_argument("--allow-increase", action="store_true")
|
||||
parser.add_argument("--report", action="store_true")
|
||||
args = parser.parse_args()
|
||||
root = pathlib.Path(args.root).resolve()
|
||||
|
||||
config = json.loads((root / CONFIG).read_text(encoding="utf-8"))
|
||||
baseline_path = root / BASELINE
|
||||
baseline = (json.loads(baseline_path.read_text(encoding="utf-8")) if baseline_path.exists()
|
||||
else {"violations": [], "oversize": {}, "source": {}})
|
||||
packages = load_metadata(root)
|
||||
sizes = file_lines(root, packages)
|
||||
counts = count_patterns(root, packages, config["source_patterns"])
|
||||
errors, debt, stale, violations = evaluate(packages, config, baseline, sizes, counts)
|
||||
|
||||
if args.report:
|
||||
report(packages, config, sizes, counts)
|
||||
return 0
|
||||
if args.update_baseline:
|
||||
updated = new_baseline(config, violations, sizes, counts)
|
||||
problems = [] if args.allow_increase else raised(baseline, updated)
|
||||
if baseline_path.exists() and problems:
|
||||
print("refusing to raise the baseline (use --allow-increase and justify it in review):", file=sys.stderr)
|
||||
print("\n".join(f" {p}" for p in problems), file=sys.stderr)
|
||||
return 1
|
||||
with open(baseline_path, "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(json.dumps(updated, indent=1) + "\n")
|
||||
print(f"wrote {BASELINE}: {len(updated['violations'])} violations, {len(updated['oversize'])} oversize files, "
|
||||
f"{len(updated['source'])} ratchets")
|
||||
return 0
|
||||
|
||||
for line in debt:
|
||||
print(f"debt (baseline): {line}")
|
||||
for line in stale:
|
||||
print(f"stale baseline: {line} (scripts/check-architecture.py --update-baseline)")
|
||||
for line in errors:
|
||||
print(f"ERROR: {line}", file=sys.stderr)
|
||||
print(f"architecture: {len(errors)} errors, {len(debt)} baselined violations, {len(stale)} stale baseline entries")
|
||||
return 1 if errors else 0
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from archcheck.cli import main # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
sys.exit(main(sys.argv[1:], pathlib.Path(__file__).resolve().parent.parent))
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative and positive proofs for scripts/check-architecture.py: each rule must fail on a synthetic violation.
|
||||
"""Negative and positive proofs for the architecture gate: each rule must fail on a synthetic violation.
|
||||
|
||||
Usage: python3 scripts/check_architecture_test.py (no cargo, no network)
|
||||
"""
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
spec = importlib.util.spec_from_file_location("check_architecture", HERE / "check-architecture.py")
|
||||
ca = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(ca)
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from archcheck import baseline as bl # noqa: E402
|
||||
from archcheck import measure, rules # noqa: E402
|
||||
|
||||
CONFIG = {
|
||||
"max_lines": 400,
|
||||
@@ -19,8 +20,8 @@ CONFIG = {
|
||||
"forbidden_in_pure": ["tokio"],
|
||||
"layers": {"L0": ["api"], "L1": ["lib"], "L2": ["core"], "L3": ["adapter-a", "adapter-b"], "L4": ["host"]},
|
||||
"adapter_edges": [["adapter-b", "adapter-a"]],
|
||||
"source_patterns": [],
|
||||
}
|
||||
EMPTY = {"violations": [], "oversize": {}, "source": {}}
|
||||
|
||||
|
||||
def pkg(name, normal=(), external=()):
|
||||
@@ -38,118 +39,110 @@ def packages(**overrides):
|
||||
|
||||
|
||||
def run(pkgs, baseline=None, sizes=None, counts=None):
|
||||
baseline = baseline or {"violations": [], "oversize": {}, "source": {}}
|
||||
return ca.evaluate(pkgs, CONFIG, baseline, sizes or {}, counts or {})
|
||||
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, sizes or {}, counts or {})
|
||||
|
||||
|
||||
class Rules(unittest.TestCase):
|
||||
def base(violations=(), oversize=None, source=None):
|
||||
return {"violations": list(violations), "oversize": oversize or {}, "source": source or {}}
|
||||
|
||||
|
||||
class GraphRules(unittest.TestCase):
|
||||
def test_clean_graph_passes(self):
|
||||
errors, debt, stale, _ = run(packages())
|
||||
self.assertEqual((errors, debt, stale), ([], [], []))
|
||||
found = run(packages())
|
||||
self.assertEqual((found.errors, found.debt, found.stale), ([], [], []))
|
||||
|
||||
def test_upward_edge_fails(self):
|
||||
errors, _, _, v = run(packages(**{"core": pkg("core", ["host"])}))
|
||||
self.assertIn("layer-up core -> host", v)
|
||||
self.assertEqual(len(errors), 1)
|
||||
found = run(packages(core=pkg("core", ["host"])))
|
||||
self.assertIn("layer-up core -> host", found.violations)
|
||||
self.assertEqual(len(found.errors), 1)
|
||||
|
||||
def test_core_may_not_depend_on_an_adapter(self):
|
||||
errors, _, _, _ = run(packages(**{"core": pkg("core", ["adapter-a"])}))
|
||||
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in errors))
|
||||
found = run(packages(core=pkg("core", ["adapter-a"])))
|
||||
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in found.errors))
|
||||
|
||||
def test_sideways_adapter_edge_fails_unless_listed(self):
|
||||
errors, _, _, v = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])}))
|
||||
self.assertIn("adapter-sideways adapter-a -> adapter-b", v)
|
||||
self.assertEqual(len(errors), 1)
|
||||
|
||||
def test_listed_sideways_edge_passes(self):
|
||||
self.assertEqual(run(packages())[0], [])
|
||||
found = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])}))
|
||||
self.assertIn("adapter-sideways adapter-a -> adapter-b", found.violations)
|
||||
self.assertEqual(run(packages()).errors, [])
|
||||
|
||||
def test_unassigned_package_fails(self):
|
||||
errors, _, _, _ = run(packages(extra=pkg("extra")))
|
||||
self.assertTrue(any("extra has no layer" in e for e in errors))
|
||||
found = run(packages(extra=pkg("extra")))
|
||||
self.assertTrue(any("extra has no layer" in e for e in found.errors))
|
||||
|
||||
def test_pure_crate_with_forbidden_dependency_fails(self):
|
||||
errors, _, _, v = run(packages(lib=pkg("lib", ["api"], ["tokio"])))
|
||||
self.assertIn("forbidden-dep lib tokio", v)
|
||||
self.assertEqual(len(errors), 1)
|
||||
def test_pure_crate_with_forbidden_dependency_fails_but_an_adapter_may_use_it(self):
|
||||
found = run(packages(lib=pkg("lib", ["api"], ["tokio"])))
|
||||
self.assertIn("forbidden-dep lib tokio", found.violations)
|
||||
self.assertEqual(run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])})).errors, [])
|
||||
|
||||
def test_adapter_may_use_forbidden_dependency(self):
|
||||
errors, _, _, _ = run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])}))
|
||||
self.assertEqual(errors, [])
|
||||
def test_baselined_violation_is_debt_and_a_fixed_one_is_stale(self):
|
||||
known = base(violations=["layer-up core -> host"])
|
||||
found = run(packages(core=pkg("core", ["host"])), known)
|
||||
self.assertEqual((found.errors, found.debt), ([], ["layer-up core -> host"]))
|
||||
self.assertEqual(len(run(packages(), known).stale), 1)
|
||||
|
||||
def test_baselined_violation_is_debt_not_error(self):
|
||||
baseline = {"violations": ["layer-up core -> host"], "oversize": {}, "source": {}}
|
||||
errors, debt, _, _ = run(packages(**{"core": pkg("core", ["host"])}), baseline)
|
||||
self.assertEqual(errors, [])
|
||||
self.assertEqual(debt, ["layer-up core -> host"])
|
||||
|
||||
def test_fixed_violation_is_reported_stale(self):
|
||||
baseline = {"violations": ["layer-up core -> host"], "oversize": {}, "source": {}}
|
||||
errors, _, stale, _ = run(packages(), baseline)
|
||||
self.assertEqual(errors, [])
|
||||
self.assertEqual(len(stale), 1)
|
||||
class SizeAndRatchetRules(unittest.TestCase):
|
||||
def test_new_large_file_fails_and_a_file_at_the_limit_passes(self):
|
||||
self.assertEqual(len(run(packages(), sizes={"big.rs": 401}).errors), 1)
|
||||
self.assertEqual(run(packages(), sizes={"ok.rs": 400}).errors, [])
|
||||
|
||||
def test_new_large_file_fails(self):
|
||||
errors, _, _, _ = run(packages(), sizes={"crates/x/src/big.rs": 401})
|
||||
self.assertEqual(len(errors), 1)
|
||||
|
||||
def test_file_at_the_limit_passes(self):
|
||||
self.assertEqual(run(packages(), sizes={"a.rs": 400})[0], [])
|
||||
|
||||
def test_baselined_large_file_may_not_grow(self):
|
||||
baseline = {"violations": [], "oversize": {"big.rs": 900}, "source": {}}
|
||||
self.assertEqual(run(packages(), baseline, {"big.rs": 900})[0], [])
|
||||
self.assertEqual(len(run(packages(), baseline, {"big.rs": 901})[0]), 1)
|
||||
|
||||
def test_shrunk_large_file_is_stale(self):
|
||||
baseline = {"violations": [], "oversize": {"big.rs": 900}, "source": {}}
|
||||
errors, _, stale, _ = run(packages(), baseline, {"big.rs": 700})
|
||||
self.assertEqual(errors, [])
|
||||
self.assertEqual(len(stale), 1)
|
||||
def test_baselined_large_file_may_not_grow_and_shrinking_is_stale(self):
|
||||
known = base(oversize={"big.rs": 900})
|
||||
self.assertEqual(run(packages(), known, {"big.rs": 900}).errors, [])
|
||||
self.assertEqual(len(run(packages(), known, {"big.rs": 901}).errors), 1)
|
||||
self.assertEqual(len(run(packages(), known, {"big.rs": 700}).stale), 1)
|
||||
|
||||
def test_ratchet_may_only_fall(self):
|
||||
baseline = {"violations": [], "oversize": {}, "source": {"env-read:host": 10}}
|
||||
self.assertEqual(run(packages(), baseline, counts={"env-read:host": 10})[0], [])
|
||||
self.assertEqual(len(run(packages(), baseline, counts={"env-read:host": 11})[0]), 1)
|
||||
self.assertEqual(len(run(packages(), baseline, counts={"env-read:host": 9})[2]), 1)
|
||||
known = base(source={"env-read:host": 10})
|
||||
self.assertEqual(run(packages(), known, counts={"env-read:host": 10}).errors, [])
|
||||
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 11}).errors), 1)
|
||||
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 9}).stale), 1)
|
||||
|
||||
def test_new_ratchet_key_starts_at_zero(self):
|
||||
self.assertEqual(len(run(packages(), counts={"env-read:host": 1})[0]), 1)
|
||||
self.assertEqual(len(run(packages(), counts={"env-read:host": 1}).errors), 1)
|
||||
|
||||
def test_baseline_update_refuses_increase(self):
|
||||
old = {"violations": [], "oversize": {"a.rs": 500}, "source": {"env-read:host": 3}}
|
||||
higher = {"violations": ["layer-up a -> b"], "oversize": {"a.rs": 501}, "source": {"env-read:host": 4}}
|
||||
self.assertEqual(len(ca.raised(old, higher)), 3)
|
||||
moved = {"violations": [], "oversize": {"a.rs": 500}, "source": {"env-read:other": 3}}
|
||||
self.assertEqual(ca.raised(old, moved), []) # same total, different crate: the code moved
|
||||
lower = {"violations": [], "oversize": {"a.rs": 450}, "source": {"env-read:host": 2}}
|
||||
self.assertEqual(ca.raised(old, lower), [])
|
||||
|
||||
def test_baseline_update_accepts_a_moved_file_but_not_a_new_large_one(self):
|
||||
old = {"violations": [], "oversize": {"src/a.rs": 500}, "source": {}}
|
||||
moved = {"violations": [], "oversize": {"src/sub/a.rs": 500}, "source": {}}
|
||||
self.assertEqual(ca.raised(old, moved), [])
|
||||
grown = {"violations": [], "oversize": {"src/sub/a.rs": 501}, "source": {}}
|
||||
self.assertEqual(len(ca.raised(old, grown)), 1)
|
||||
fresh = {"violations": [], "oversize": {"src/a.rs": 500, "src/b.rs": 450}, "source": {}}
|
||||
self.assertEqual(len(ca.raised(old, fresh)), 1)
|
||||
class BaselineRewrite(unittest.TestCase):
|
||||
def test_refuses_increase_and_accepts_decrease(self):
|
||||
old = base(oversize={"a.rs": 500}, source={"env-read:host": 3})
|
||||
higher = base(["layer-up a -> b"], {"a.rs": 501}, {"env-read:host": 4})
|
||||
self.assertEqual(len(bl.raised(old, higher)), 3)
|
||||
self.assertEqual(bl.raised(old, base(oversize={"a.rs": 450}, source={"env-read:host": 2})), [])
|
||||
|
||||
def test_baseline_update_accepts_a_split_into_a_same_stem_directory(self):
|
||||
old = {"violations": [], "oversize": {"src/big.rs": 1000}, "source": {}}
|
||||
split = {"violations": [], "oversize": {"src/big.rs": 500, "src/big/part.rs": 480}, "source": {}}
|
||||
self.assertEqual(ca.raised(old, split), [])
|
||||
bloated = {"violations": [], "oversize": {"src/big.rs": 600, "src/big/part.rs": 480}, "source": {}}
|
||||
self.assertEqual(len(ca.raised(old, bloated)), 1)
|
||||
def test_code_that_moved_between_crates_keeps_its_total(self):
|
||||
old = base(source={"env-read:host": 3})
|
||||
self.assertEqual(bl.raised(old, base(source={"env-read:other": 3})), [])
|
||||
|
||||
def test_pattern_counter_stops_at_cfg_test_and_skips_comments(self):
|
||||
import tempfile
|
||||
def test_a_moved_file_is_accepted_but_a_new_large_one_is_not(self):
|
||||
old = base(oversize={"src/a.rs": 500})
|
||||
self.assertEqual(bl.raised(old, base(oversize={"src/sub/a.rs": 500})), [])
|
||||
self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1)
|
||||
self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1)
|
||||
|
||||
def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self):
|
||||
old = base(oversize={"src/big.rs": 1000})
|
||||
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), [])
|
||||
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1)
|
||||
|
||||
|
||||
class Measurement(unittest.TestCase):
|
||||
def test_counter_stops_at_a_test_module_and_skips_comments(self):
|
||||
text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n'
|
||||
self.assertEqual(measure.production_lines(text), ['let a = std::env::var("A");'])
|
||||
|
||||
def test_a_single_cfg_test_function_does_not_hide_the_code_after_it(self):
|
||||
text = '#[cfg(test)]\nfn only_tests() {}\nlet a = env::var("A");\n'
|
||||
self.assertEqual(len(measure.production_lines(text)), 3)
|
||||
|
||||
def test_counts_are_per_crate_and_skip_test_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = pathlib.Path(tmp) / "src"
|
||||
src.mkdir()
|
||||
(src / "lib.rs").write_text("let a = std::env::var(\"A\");\n// env::var(\"B\")\n#[cfg(test)]\nmod t { fn f() { env::var(\"C\"); } }\n")
|
||||
counts = ca.count_patterns(pathlib.Path(tmp), [{"name": "p", "dir": pathlib.Path(tmp)}],
|
||||
[{"id": "env-read", "regex": r"\benv::var(_os)?\("}])
|
||||
self.assertEqual(counts, {"env-read:p": 1})
|
||||
(src / "lib.rs").write_text('let a = env::var("A");\n')
|
||||
(src / "tests.rs").write_text('let b = env::var("B");\n')
|
||||
package = dict(pkg("p"), dir=pathlib.Path(tmp))
|
||||
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
|
||||
self.assertEqual(counts, {"e:p": 1})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user