57 lines
2.7 KiB
Python
57 lines
2.7 KiB
Python
"""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 plan.touches 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. A separator, as file_parts defines it, names its part only where the diff changed no other line."""
|
|
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)]
|
|
sides = []
|
|
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
|
|
sides.append((text, lines))
|
|
names = named(path, sides, separators=False) or named(path, sides, separators=True)
|
|
if names is None:
|
|
# A hunk that only deletes lines counts as the line above them, or as line 1 where it deleted the file's first lines.
|
|
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))
|
|
|
|
|
|
def named(path: str, sides: list[tuple[str, list[int]]], separators: bool) -> set[str] | None:
|
|
"""The parts the lines of each side lie in, each side a text and its lines; None where either text has no names."""
|
|
names: set[str] = set()
|
|
for text, lines in sides:
|
|
found = part_names(path, text, lines, separators)
|
|
if found is None:
|
|
return None
|
|
names |= found
|
|
return names
|