File size: 6,148 Bytes
d85bfb7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | """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
|