Files
leleka/scripts/limits/diffs.py
T
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

83 lines
3.0 KiB
Python

"""Which lines of which files changed against a base, from `git diff --unified=0`."""
import re
import subprocess
from dataclasses import dataclass, field
HUNK = re.compile(r"^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
class GitError(Exception):
pass
@dataclass
class Changes:
added: list = field(default_factory=list) # new-file line numbers that were added or changed, ascending
gaps: list = field(default_factory=list) # n: lines were deleted between line n and line n + 1
def git(root, *args):
done = subprocess.run(["git", "-c", "core.quotepath=off", *args], cwd=root, capture_output=True)
if done.returncode != 0:
raise GitError(f"git {' '.join(args)}: {done.stderr.decode('utf-8', 'replace').strip()}")
return done.stdout.decode("utf-8", "replace")
def _commit(root, ref):
try:
return git(root, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}").strip()
except GitError:
return None
def resolve_base(root, requested, candidates):
"""(commit, label) to diff against: `requested`, else the merge-base of HEAD with the first candidate ref."""
if requested:
found = _commit(root, requested)
if found is None:
raise GitError(f"base ref {requested!r} does not exist")
return found, requested
for ref in candidates:
if _commit(root, ref):
return git(root, "merge-base", "HEAD", ref).strip(), f"merge-base(HEAD, {ref})"
raise GitError(f"none of {list(candidates)} exists: pass --base REF")
def _hunk(changes, match):
start = int(match.group(2))
count = 1 if match.group(3) is None else int(match.group(3))
if count:
changes.added.extend(range(start, start + count))
else:
changes.gaps.append(start)
old = 1 if match.group(1) is None else int(match.group(1))
return old, count
def _target(line):
path = line[4:].split("\t")[0]
return None if path == "/dev/null" else (path[2:] if path.startswith("b/") else path)
def parse(diff):
"""{path: Changes} from a unified diff with zero context lines."""
result, current, left = {}, None, (0, 0)
for line in diff.splitlines():
if left != (0, 0):
left = (left[0] - line.startswith("-"), left[1] - line.startswith("+"))
elif line.startswith("+++ "):
current = _target(line)
if current:
result.setdefault(current, Changes())
elif line.startswith("@@") and current and HUNK.match(line):
left = _hunk(result[current], HUNK.match(line))
return result
def changed(root, base):
"""{path: Changes} for tracked files that differ from `base` in the working tree, and untracked ones (all lines)."""
result = parse(git(root, "diff", "--unified=0", "--no-color", "-M", base, "--"))
for rel in git(root, "ls-files", "--others", "--exclude-standard").splitlines():
text = (root / rel).read_text(encoding="utf-8", errors="replace") if (root / rel).is_file() else ""
result[rel] = Changes(list(range(1, len(text.splitlines()) + 1)))
return result