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.
144 lines
6.4 KiB
Python
144 lines
6.4 KiB
Python
"""Command line of the limits gate (STRA-367)."""
|
|
import argparse
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
|
|
from archcheck import measure as arch
|
|
|
|
from . import allow, baseline, census, diffs, files, gate, policy
|
|
|
|
ALLOWLIST, BASELINE = "limits-allowlist.json", "limits-baseline.json"
|
|
|
|
|
|
def parse_args(argv, default_root):
|
|
parser = argparse.ArgumentParser(description="Lawbook 301 limits for new and changed code; legacy only falls")
|
|
parser.add_argument("--root", default=str(default_root))
|
|
parser.add_argument("--base", default=os.environ.get("LIMITS_BASE"), help="ref to diff against")
|
|
flag = {"action": "store_true"}
|
|
parser.add_argument("--update-baseline", help="rewrite the census baseline and tighten the allowlist", **flag)
|
|
parser.add_argument("--allow-increase", help="with --update-baseline: allow raising a total", **flag)
|
|
parser.add_argument("--allowlist-add", help="allowlist what the diff gate rejects (--reason, --owner)", **flag)
|
|
parser.add_argument("--reason", default="")
|
|
parser.add_argument("--owner", default="", help="the work item that removes the debt, for example STRA-367")
|
|
parser.add_argument("--skip-diff", help="do not run the diff gate and the allowlist check", **flag)
|
|
parser.add_argument("--skip-census", help="do not run the census ratchet", **flag)
|
|
parser.add_argument("--report", help="print the census and the worst functions", **flag)
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def scan_states(root, pol, changes):
|
|
"""{path: State} for the changed files (with their changes) that are in scope."""
|
|
states = {}
|
|
for rel, change in sorted(changes.items()):
|
|
if policy.language(pol, rel) and (root / rel).is_file():
|
|
text = files.read(root, rel)
|
|
fns, wide = files.scan_text(pol, rel, text)
|
|
states[rel] = gate.State(rel, text, fns, wide, change)
|
|
return states
|
|
|
|
|
|
def add_entry_files(root, pol, states, entries):
|
|
"""Scan the files of allowlist entries that did not change, so the ratchet sees every entry."""
|
|
for rel, _ in entries:
|
|
if rel not in states and (root / rel).is_file():
|
|
text = files.read(root, rel)
|
|
fns, wide = files.scan_text(pol, rel, text)
|
|
states[rel] = gate.State(rel, text, fns, wide)
|
|
return states
|
|
|
|
|
|
def diff_gate(root, pol, entries, base):
|
|
"""(Result, stale, states, label) of the diff gate and the allowlist ratchet."""
|
|
commit, label = diffs.resolve_base(root, base, pol.base_candidates)
|
|
states = scan_states(root, pol, diffs.changed(root, commit))
|
|
result = gate.check_changed(list(states.values()), entries, pol.limits, pol.tab_width)
|
|
add_entry_files(root, pol, states, entries)
|
|
errors, stale = gate.check_allowlist(entries, states, pol.limits)
|
|
result.errors += errors
|
|
return result, stale, states, label
|
|
|
|
|
|
def census_gate(root, pol, base_data):
|
|
counts = census.collect(root, pol, owners(root, pol)).counts
|
|
return baseline.findings(counts, base_data)
|
|
|
|
|
|
def owners(root, pol):
|
|
return {**census.crate_files(root, arch.load_metadata(root)), **census.python_files(root, pol)}
|
|
|
|
|
|
def add_to_allowlist(root, entries, result, args):
|
|
"""Write an entry for everything the diff gate rejected; the reason and the owner are mandatory."""
|
|
if not args.reason.strip() or not args.owner.strip():
|
|
print("--allowlist-add needs --reason and --owner (the item that removes the debt)", file=sys.stderr)
|
|
return 1
|
|
for (rel, name), measures in sorted(result.needs.items()):
|
|
entries[(rel, name)] = allow.new_entry(rel, name, measures, args.reason, args.owner)
|
|
allow.save(root / ALLOWLIST, entries)
|
|
print(f"wrote {ALLOWLIST}: {len(result.needs)} entries added, {len(entries)} in total")
|
|
return 0
|
|
|
|
|
|
def update_baseline(root, pol, entries, states, args):
|
|
path = root / BASELINE
|
|
old, collected = baseline.load(path), census.collect(root, pol, owners(root, pol))
|
|
new = baseline.build(collected.counts, pol.limits)
|
|
problems = [] if args.allow_increase or not path.exists() else baseline.raised(old, new)
|
|
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
|
|
baseline.save(path, new)
|
|
kept = gate.tightened(entries, add_entry_files(root, pol, states, entries), pol.limits)
|
|
allow.save(root / ALLOWLIST, kept)
|
|
print(f"wrote {BASELINE} and {ALLOWLIST}: {len(kept)} of {len(entries)} allowlist entries remain")
|
|
return 0
|
|
|
|
|
|
def print_report(collected, limits):
|
|
for scope in census.SCOPES:
|
|
for crate, row in sorted(collected.counts[scope].items()):
|
|
print(f"{scope:5} {crate:32} " + " ".join(f"{k}={row.get(k, 0)}" for k in limits))
|
|
print("totals", census.totals(collected.counts))
|
|
for rel, fn in sorted(collected.worst, key=lambda item: -item[1].fn_lines)[:15]:
|
|
print(f" {fn.fn_lines:5} lines cx {fn.complexity:3} nest {fn.nesting} {rel}:{fn.start} {fn.key}")
|
|
return 0
|
|
|
|
|
|
def run(args, root, pol):
|
|
entries = allow.load(root / ALLOWLIST)
|
|
if args.update_baseline:
|
|
return update_baseline(root, pol, entries, {}, args)
|
|
skipped = (gate.Result(), [], {}, "")
|
|
result, stale, states, label = skipped if args.skip_diff else diff_gate(root, pol, entries, args.base)
|
|
if args.allowlist_add:
|
|
return add_to_allowlist(root, entries, result, args)
|
|
errors, notes = list(result.errors), list(stale)
|
|
if not args.skip_census:
|
|
found, tight = census_gate(root, pol, baseline.load(root / BASELINE))
|
|
errors, notes = errors + found, notes + tight
|
|
return finish(errors, notes, label, len(states))
|
|
|
|
|
|
def finish(errors, notes, label, checked):
|
|
for line in notes:
|
|
print(f"stale: {line} (scripts/check-limits.py --update-baseline)")
|
|
for line in errors:
|
|
print(f"ERROR: {line}", file=sys.stderr)
|
|
base = label or "not used"
|
|
print(f"limits: {len(errors)} errors, {len(notes)} stale entries; base {base}, {checked} files in scope")
|
|
return 1 if errors else 0
|
|
|
|
|
|
def main(argv, default_root):
|
|
args = parse_args(argv, default_root)
|
|
root = pathlib.Path(args.root).resolve()
|
|
pol = policy.load(root)
|
|
try:
|
|
if args.report:
|
|
return print_report(census.collect(root, pol, owners(root, pol)), pol.limits)
|
|
return run(args, root, pol)
|
|
except diffs.GitError as error:
|
|
print(f"limits: {error}", file=sys.stderr)
|
|
return 2 |