"""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 mechanical_findings(names, baseline): """(errors, stale) for file names left over from mechanical splits: none may be new, the baselined ones only go.""" known = set(baseline.get("mechanical_names", [])) errors = [f"{path}: a file name from a mechanical split (impl_*, *_fn, *_); name it for what it is and what " f"it is for" for path in names if path not in known] stale = [f"mechanical file name is gone: {path}: tighten the baseline" for path in sorted(known - set(names))] return errors, stale def exception_findings(exceptions, excused, known_ratchets): """Errors for the `exceptions` list of architecture.json: each needs a reason, a known ratchet and at least one hit in its file; an entry that excuses nothing is a stale exception and must be removed.""" errors = [] for e in exceptions: label = f"exception {e.get('crate')} {e.get('file')} {e.get('ratchet')}" if not str(e.get("reason", "")).strip(): errors.append(f"{label}: an exception needs a reason") if e.get("ratchet") not in known_ratchets: errors.append(f"{label}: unknown ratchet") elif (e.get("crate"), e.get("file"), e.get("ratchet")) not in excused: errors.append(f"{label}: the file has no such hit any more; remove the exception") return errors @dataclass class Measured: """What was measured in the source tree: file line counts, source pattern counts, mechanical file names.""" sizes: dict counts: dict names: tuple = () exception_errors: tuple = () def evaluate(packages, config, baseline, measured): """Run every rule on the package graph and the measurements. Returns Findings.""" sizes, counts, names = measured.sizes, measured.counts, measured.names 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) name_errors, name_stale = mechanical_findings(names, baseline) result.errors += errors + size_errors + ratchet_errors + name_errors + list(measured.exception_errors) result.stale = stale + size_stale + ratchet_stale + name_stale return result