"""The diff gate: functions and lines that are new or changed must be within the limits; the allowlist only falls. Pure functions over `State` (a scanned file and, for the diff gate, its changed lines): no git and no file system here. """ from bisect import bisect_left from dataclasses import dataclass, field from . import allow, model from .diffs import Changes LABELS = (("fn_lines", "lines"), ("complexity", "complexity"), ("nesting", "nesting"), ("params", "parameters")) @dataclass class State: rel: str text: str fns: list wide: set changes: Changes = field(default_factory=Changes) def lines(self): return self.text.splitlines() @dataclass class Result: errors: list = field(default_factory=list) needs: dict = field(default_factory=dict) # (path, name) -> measures that an allowlist entry would have to record def _hits(ascending, low, high): at = bisect_left(ascending, low) return at < len(ascending) and ascending[at] <= high def touched(fn, changes): """The function has an added or changed line, or lost lines between two of its own.""" return _hits(changes.added, fn.start, fn.end) or _hits(changes.gaps, fn.start, fn.end - 1) def outside_wide(state): """Number of wide lines that are in no function of the file.""" return sum(1 for n in state.wide if not any(fn.start <= n <= fn.end for fn in state.fns)) def fn_errors(rel, fn, limits): return [f"{rel}:{fn.start}: {fn.key}: {label} {getattr(fn, kind)} > {limits[kind]}" for kind, label in LABELS if getattr(fn, kind) > limits[kind]] def _file_entry_covers(state, entries): entry = entries.get((state.rel, allow.FILE)) return entry is not None and entry.get("width", 0) >= outside_wide(state) def wide_errors(state, entries, limits, tab_width, result): """Errors for added or changed lines wider than the limit; a line inside an allowlisted function is that entry's.""" lines = state.lines() for n in sorted(set(state.changes.added) & state.wide): holders = [fn for fn in state.fns if fn.start <= n <= fn.end] if any((state.rel, fn.key) in entries for fn in holders): continue if not holders and _file_entry_covers(state, entries): continue width = model.line_width(lines[n - 1], tab_width) result.errors.append(f"{state.rel}:{n}: width {width} > {limits['width']}") for fn in holders[:1]: result.needs[(state.rel, fn.key)] = fn.measures() if not holders: result.needs[(state.rel, allow.FILE)] = {"width": outside_wide(state)} def check_changed(states, entries, limits, tab_width): """Result for the new and changed code of the given states (those that have changes).""" result = Result() for state in states: for fn in state.fns: if (state.rel, fn.key) in entries or not touched(fn, state.changes): continue errors = fn_errors(state.rel, fn, limits) result.errors += errors if errors: result.needs[(state.rel, fn.key)] = fn.measures() wide_errors(state, entries, limits, tab_width, result) return result def current_measures(state, name): """The measures an allowlist entry is compared with now, or None when its function is gone.""" if state is None: return None if name == allow.FILE: return {"width": outside_wide(state)} return next((fn.measures() for fn in state.fns if fn.key == name), None) def _entry_state(rel, name, entry, now, limits): """(errors, stale) of one allowlist entry against the current measures.""" where = f"{rel} {name}" if now is None: return [], [f"allowlist entry for a function that is gone: {where}"] top = allow.recorded(entry, limits) errors = [f"allowlist {where}: {kind} grew from {top[kind]} to {now[kind]}; an allowlisted function may only shrink" for kind in now if now[kind] > top[kind]] if not model.over(now, limits): return errors, [f"allowlist {where} is within the limits now: drop the entry"] fell = [kind for kind in now if kind in entry and now[kind] < top[kind]] return errors, [f"allowlist {where}: {kind} fell from {top[kind]} to {now[kind]}: tighten" for kind in fell] def check_allowlist(entries, states, limits): """(errors, stale) for every allowlist entry: a recorded number may not grow; a fixed function's entry is stale.""" errors, stale = [], [] for (rel, name), entry in sorted(entries.items()): errors += [f"allowlist {rel} {name}: no {field_name}" for field_name in allow.missing_fields(entry)] now = current_measures(states.get(rel), name) found, old = _entry_state(rel, name, entry, now, limits) errors += found stale += old return errors, stale def tightened(entries, states, limits): """The allowlist after dropping fixed and gone functions and lowering recorded numbers; a number is never raised.""" kept = {} for key, entry in entries.items(): now = current_measures(states.get(key[0]), key[1]) if now is None or not model.over(now, limits): continue top = allow.recorded(entry, limits) kept[key] = {**entry, **{kind: min(top[kind], now[kind]) for kind in now}} return kept