Files
Pavlo Ratushnyi 334af80d3d STRA-367: limits gate for lawbook 301 (function 30 lines, complexity 10, nesting 4, width 120)
New and changed code is checked against the base (merge-base with the integration branch):
every added or touched function and every added or changed line must be within the limits,
unless limits-allowlist.json lists the function with a reason and an owner; an allowlisted
function may only shrink. The legacy that exists today is a per-crate census in
limits-baseline.json whose totals may only fall (same --update-baseline semantics as the
architecture gate). Rust is measured from the rustsplit lexer, the gate's own Python from ast.
56 self-tests, including a temporary git repository.
2026-11-06 11:26:53 +01:00

92 lines
3.8 KiB
Python

"""Counts Clippy's length, complexity and argument lints per crate and ratchets them (opt-in, STRA-367).
Reads `cargo clippy --message-format=json` on stdin (scripts/check-clippy-limits.sh pipes it in). The counts live in
clippy-limits-baseline.json; the total of a lint over all crates may only fall.
"""
import argparse
import json
import pathlib
import sys
LINTS = ("clippy::too_many_lines", "clippy::cognitive_complexity", "clippy::too_many_arguments")
BASELINE = "clippy-limits-baseline.json"
COMMENT = ("Count of Clippy warnings per crate for the lawbook 301 lints, thresholds in "
"scripts/limits/clippy/clippy.toml (scripts/check-clippy-limits.sh). A total per lint may only fall; "
"regenerate with --update-baseline. "
"Measured on Linux (WSL Ubuntu, Clippy 0.1.99). Not part of the default gate.")
def crate_of(package_id):
"""The package name from either form of a cargo package id."""
if "#" not in package_id:
return package_id.split(" ")[0]
path, fragment = package_id.split("#", 1)
return fragment.split("@")[0] if "@" in fragment else path.rstrip("/").rsplit("/", 1)[-1]
def _site(message):
span = next((s for s in message.get("spans", []) if s.get("is_primary")), {})
return span.get("file_name"), span.get("line_start"), span.get("column_start")
def count(lines):
"""{crate: {lint: n}} from cargo's JSON lines; a warning repeated for the lib and test targets counts once."""
seen, counts = set(), {}
for line in lines:
try:
event = json.loads(line)
except ValueError:
continue
message = event.get("message") or {}
code = (message.get("code") or {}).get("code")
key = (code, event.get("package_id"), *_site(message))
if event.get("reason") == "compiler-message" and code in LINTS and key not in seen:
seen.add(key)
row = counts.setdefault(crate_of(event["package_id"]), {})
row[code] = row.get(code, 0) + 1
return counts
def totals(counts):
out = dict.fromkeys(LINTS, 0)
for row in counts.values():
for lint, n in row.items():
out[lint] += n
return out
def compare(counts, base):
"""(errors, stale) between the current counts and the baseline counts."""
now, before = totals(counts), totals(base)
errors = [f"{lint} rose to {n} (baseline {before[lint]}); the count may only fall"
for lint, n in now.items() if n > before[lint]]
stale = [f"{lint} fell from {before[lint]} to {n}: tighten the baseline"
for lint, n in now.items() if n < before[lint]]
return errors, stale
def main(argv, lines, root):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--update-baseline", action="store_true")
parser.add_argument("--allow-increase", action="store_true")
args = parser.parse_args(argv)
path = root / BASELINE
base = json.loads(path.read_text(encoding="utf-8"))["clippy"] if path.exists() else {}
counts = count(lines)
errors, stale = compare(counts, base)
if args.update_baseline:
if errors and path.exists() and not args.allow_increase:
print("\n".join(f"refusing: {e}" for e in errors), file=sys.stderr)
return 1
data = {"_comment": COMMENT, "clippy": dict(sorted(counts.items()))}
path.write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8")
print(f"wrote {BASELINE}: {sum(totals(counts).values())} warnings in {len(counts)} crates")
return 0
print("\n".join(f"stale: {s}" for s in stale))
print("\n".join(f"ERROR: {e}" for e in errors), file=sys.stderr)
print(f"clippy limits: {totals(counts)}; {len(errors)} errors")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:], sys.stdin, pathlib.Path(__file__).resolve().parent.parent.parent))