Patchnoisseur / app /diff_parser.py
michoo42's picture
App
d85bfb7 verified
Raw
History Blame Contribute Delete
6.15 kB
"""Parse a multi-commit unified diff into a side-by-side render model."""
from __future__ import annotations
import re
from dataclasses import dataclass, field
HUNK_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
COMMIT_HEADER_RE = re.compile(r"^=== (.+?) ===\s*$")
@dataclass
class Row:
left_no: int | None
left_text: str
left_kind: str # "context" | "removed" | "empty"
right_no: int | None
right_text: str
right_kind: str # "context" | "added" | "empty"
@dataclass
class Hunk:
header: str
rows: list[Row] = field(default_factory=list)
@dataclass
class File:
old_path: str
new_path: str
hunks: list[Hunk] = field(default_factory=list)
note: str = "" # e.g. binary diff
@dataclass
class Commit:
url: str
files: list[File] = field(default_factory=list)
def _pair_block(removed: list[tuple[int, str]], added: list[tuple[int, str]]) -> list[Row]:
rows: list[Row] = []
for i in range(max(len(removed), len(added))):
if i < len(removed):
ln, txt = removed[i]
left = (ln, txt, "removed")
else:
left = (None, "", "empty")
if i < len(added):
ln, txt = added[i]
right = (ln, txt, "added")
else:
right = (None, "", "empty")
rows.append(Row(left[0], left[1], left[2], right[0], right[1], right[2]))
return rows
def _parse_hunk(lines: list[str], start_old: int, start_new: int) -> list[Row]:
rows: list[Row] = []
old_n, new_n = start_old, start_new
removed: list[tuple[int, str]] = []
added: list[tuple[int, str]] = []
def flush():
nonlocal removed, added
if removed or added:
rows.extend(_pair_block(removed, added))
removed, added = [], []
for ln in lines:
if not ln:
continue
marker, text = ln[0], ln[1:]
if marker == " ":
flush()
rows.append(Row(old_n, text, "context", new_n, text, "context"))
old_n += 1
new_n += 1
elif marker == "-":
removed.append((old_n, text))
old_n += 1
elif marker == "+":
added.append((new_n, text))
new_n += 1
elif marker == "\\":
# "\ No newline at end of file" — display as context on whichever side it follows
pass
else:
# unexpected line inside a hunk; treat as context
flush()
rows.append(Row(old_n, ln, "context", new_n, ln, "context"))
old_n += 1
new_n += 1
flush()
return rows
def parse(diff_text: str) -> list[Commit]:
"""Split diff_text by `=== url ===` headers, then by `diff --git`, then by hunks."""
commits: list[Commit] = []
current = Commit(url="")
current_file: File | None = None
pending_hunk_header: str | None = None
pending_hunk_lines: list[str] | None = None
pending_old_start = 0
pending_new_start = 0
def finalize_hunk():
nonlocal pending_hunk_header, pending_hunk_lines
if current_file is not None and pending_hunk_header is not None and pending_hunk_lines is not None:
rows = _parse_hunk(pending_hunk_lines, pending_old_start, pending_new_start)
current_file.hunks.append(Hunk(header=pending_hunk_header, rows=rows))
pending_hunk_header = None
pending_hunk_lines = None
def finalize_commit():
nonlocal current
finalize_hunk()
if current.files or current.url:
commits.append(current)
current = Commit(url="")
lines = diff_text.splitlines()
i = 0
while i < len(lines):
line = lines[i]
m = COMMIT_HEADER_RE.match(line)
if m:
finalize_commit()
current = Commit(url=m.group(1))
current_file = None
i += 1
continue
if line.startswith("diff --git "):
finalize_hunk()
current_file = File(old_path="", new_path="")
current.files.append(current_file)
# try to read old/new path from following ---/+++ lines (or rename headers)
i += 1
while i < len(lines) and not lines[i].startswith("@@") and not lines[i].startswith("diff --git ") and not COMMIT_HEADER_RE.match(lines[i]):
hdr = lines[i]
if hdr.startswith("--- "):
current_file.old_path = hdr[4:].removeprefix("a/").strip()
elif hdr.startswith("+++ "):
current_file.new_path = hdr[4:].removeprefix("b/").strip()
elif hdr.startswith("Binary files "):
current_file.note = hdr
elif hdr.startswith("rename from "):
current_file.old_path = hdr[len("rename from "):].strip()
elif hdr.startswith("rename to "):
current_file.new_path = hdr[len("rename to "):].strip()
i += 1
if not current_file.old_path and not current_file.new_path:
# fall back to the `diff --git a/foo b/bar` paths
parts = line.split()
if len(parts) >= 4:
current_file.old_path = parts[2].removeprefix("a/")
current_file.new_path = parts[3].removeprefix("b/")
continue
m = HUNK_RE.match(line)
if m and current_file is not None:
finalize_hunk()
pending_hunk_header = line
pending_hunk_lines = []
pending_old_start = int(m.group(1)) or 1
pending_new_start = int(m.group(3)) or 1
i += 1
continue
if pending_hunk_lines is not None:
# collect hunk body until next file/hunk/commit header
if line.startswith("diff --git ") or COMMIT_HEADER_RE.match(line) or HUNK_RE.match(line):
continue # handled by the loop on next iteration
pending_hunk_lines.append(line)
i += 1
continue
i += 1
finalize_commit()
return commits