File size: 3,202 Bytes
ee446e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""Ratchet on per-function cyclomatic complexity.

`core/modules` carry real CC debt: several checklist functions run past 100.
A global threshold cannot be met without a rewrite nobody asked for, so this
gate does what the other ratchets do -- it forbids the debt from GROWING.

Two rules:

1. No function may exceed ``CEILING``. The worst existing offenders are
   exempted by name in ``KNOWN`` with their measured value, so they are
   frozen where they are rather than blocking the gate.
2. A ``KNOWN`` entry may only go DOWN. Raising one, or adding a new entry,
   fails: paying down debt is the point.

Run with ``--record`` after a deliberate refactor to rewrite the exemptions
to the measured values (they may then be deleted when they fall under the
ceiling).
"""

from __future__ import annotations

import json
import pathlib
import sys

from radon.complexity import cc_visit

CEILING = 26  # rank F begins at 26
CONFIG = pathlib.Path("complexity-gate.json")
SKIP_PARTS = {"mutants", "__pycache__", "scratch", "tests"}


def measured() -> dict[str, int]:
    """Every function over CEILING, keyed by `path::name`."""
    found: dict[str, int] = {}
    for root in ("core", "modules", "adapters", "app"):
        for path in pathlib.Path(root).rglob("*.py"):
            if SKIP_PARTS & set(path.parts):
                continue
            try:
                source = path.read_text(encoding="utf8")
                blocks = cc_visit(source)
            except (OSError, UnicodeDecodeError, SyntaxError):
                continue
            for block in blocks:
                if block.complexity > CEILING:
                    found[f"{path.as_posix()}::{block.name}"] = block.complexity
    return found


def main() -> int:
    record = "--record" in sys.argv
    current = measured()

    if record:
        CONFIG.write_text(json.dumps(current, indent=2, sort_keys=True) + "\n", encoding="utf8")
        print(f"check-complexity: recorded {len(current)} function(s) over {CEILING}")
        return 0

    known: dict[str, int] = json.loads(CONFIG.read_text(encoding="utf8")) if CONFIG.exists() else {}
    failures: list[str] = []

    for name, score in sorted(current.items()):
        allowed = known.get(name)
        if allowed is None:
            failures.append(f"{name} is new at {score} (ceiling {CEILING})")
        elif score > allowed:
            failures.append(f"{name} rose {allowed} -> {score}")

    if failures:
        for failure in failures:
            print(f"check-complexity: FAIL — {failure}", file=sys.stderr)
        print(
            f"check-complexity: FAIL — {len(failures)} function(s) grew past the ratchet. "
            "Extract a helper rather than raising an exemption.",
            file=sys.stderr,
        )
        return 1

    paid_down = [name for name, recorded in known.items() if current.get(name, 0) < recorded and name in current]
    note = f"; {len(paid_down)} below their recorded value — run --record to tighten" if paid_down else ""
    print(f"check-complexity: ok — {len(current)} function(s) over {CEILING}, none above their exemption{note}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())