"""Parse `git diff --name-status -M` and extract changed names from a unified diff.""" from __future__ import annotations import posixpath import re from dataclasses import dataclass MIN_NAME_LENGTH = 4 _FILE_HEADER = re.compile(r"^diff --git a/.* b/(.*)$") _R_ASSIGN = re.compile(r"^\s*([A-Za-z.][\w.]*)\s*(?:<-|=)\s*function\b") _R_TARGET = re.compile(r"tar_target\(\s*([A-Za-z.][\w.]*)") _YAML_KEY = re.compile(r"^([A-Za-z_][\w.-]*)\s*:") @dataclass(frozen=True) class Change: status: str # "A", "M", "D" or "R" path: str old_path: str | None = None def parse_name_status(text: str) -> tuple[Change, ...]: """Parse name-status output. R becomes R with old_path; C and T count as M.""" changes: list[Change] = [] for line in text.splitlines(): if not line.strip(): continue fields = line.split("\t") code = fields[0][:1] if code == "R" and len(fields) >= 3: changes.append(Change("R", fields[2], fields[1])) elif code == "C" and len(fields) >= 3: changes.append(Change("M", fields[2], None)) elif code in ("A", "M", "D", "T") and len(fields) >= 2: changes.append(Change("M" if code == "T" else code, fields[1], None)) else: raise ValueError(f"unrecognized name-status line: {line!r}") return tuple(changes) def _names_in_line(path: str, content: str) -> list[str]: if path.endswith(".R"): found = [] match = _R_ASSIGN.match(content) if match: found.append(match.group(1)) found.extend(_R_TARGET.findall(content)) return found if posixpath.basename(path) == "config.yml": match = _YAML_KEY.match(content) return [match.group(1)] if match else [] return [] def changed_names(diff_text: str) -> tuple[frozenset[str], frozenset[str]]: """Names net added and net removed across the diff (a name on both sides cancels).""" added: set[str] = set() removed: set[str] = set() path = "" for line in diff_text.splitlines(): header = _FILE_HEADER.match(line) if header: path = header.group(1) elif line.startswith(("+++", "---")): continue elif line[:1] in ("+", "-"): target = added if line[0] == "+" else removed target.update( n for n in _names_in_line(path, line[1:]) if len(n) >= MIN_NAME_LENGTH ) return frozenset(added - removed), frozenset(removed - added)