"""The files and parts a diff touched, named as a prediction names them.""" import re from failure import Failure from git_cli.git_repo import git, Git from touch_predictions.prediction import Part, Touches from touch_predictions.file_parts import part_names HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.M) def touched(base: str, head: str, cwd: str, skipped: set[str], run: Git = git) -> Touches | Failure: """What the diff from base to head touched, less the paths in skipped. A file added, deleted or without text hunks is touched whole. A rename reads as a file deleted and one added.""" listed = run("diff", "--no-renames", "--name-status", "-z", base, head, "--", cwd=cwd) if isinstance(listed, Failure): return listed fields = listed.split("\0") touches: Touches = {} for status, path in sorted(zip(fields[::2], fields[1::2]), key=lambda pair: pair[1]): if path in skipped: continue parts = modified(base, head, path, cwd, run) if status == "M" else () if isinstance(parts, Failure): return parts touches[path] = parts return touches def modified(base: str, head: str, path: str, cwd: str, run: Git) -> tuple[Part, ...] | Failure: """The parts of path whose lines the diff removed, in base's text, or added, in head's; line ranges of head's text where either text has no names.""" diff = run("diff", "--no-renames", "-U0", base, head, "--", path, cwd=cwd, errors="replace") if isinstance(diff, Failure): return diff hunks = [(int(old), int(olds or 1), int(new), int(news or 1)) for old, olds, new, news in HUNK.findall(diff)] names: set[str] | None = set() for revision, lines in ((base, [line for old, olds, _, _ in hunks for line in range(old, old + olds)]), (head, [line for _, _, new, news in hunks for line in range(new, new + news)])): text = run("show", f"{revision}:{path}", cwd=cwd, errors="replace") if isinstance(text, Failure): return text found = part_names(path, text, lines) names = None if names is None or found is None else names | found if names is None: # A hunk that only deletes names the line it left, or the first where it left none. return tuple(Part(f"lines {max(new, 1)}-{max(new + max(news, 1) - 1, 1)}") for _, _, new, news in hunks) return tuple(Part(name) for name in sorted(names))