Files
leleka/scripts/archcheck/cli.py
T

81 lines
3.8 KiB
Python

"""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, {len(current['mechanical_names'])} mechanical file names")
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)
exceptions, excused = config.get("exceptions", []), {}
counts = measure.count_patterns(packages, config["source_patterns"], exceptions, excused)
exception_errors = rules.exception_findings(exceptions, excused, {p["id"] for p in config["source_patterns"]})
names = measure.mechanical_names(root, packages, config.get("mechanical_names", {}))
found = rules.evaluate(packages, config, old, rules.Measured(sizes, counts, names, tuple(exception_errors)))
if args.report:
report(packages, config, sizes, counts)
return 0
if args.update_baseline:
current = bl.build(config["max_lines"], found.violations, sizes, counts, names)
return update_baseline(baseline_path, old, current, args.allow_increase)
return print_findings(found)