| 1 |
""" |
| 2 |
Streamed ultra-minimal patch applier. |
| 3 |
|
| 4 |
Assumptions: |
| 5 |
- git-style headers '--- a/...' and '+++ b/...' (or '/dev/null' for adds). |
| 6 |
- Hunks contain contiguous blocks of '-' lines followed by '+' lines (no context, nointerleaving). |
| 7 |
- No deletions/renames of files; additions allowed where src is /dev/null. |
| 8 |
- Every modified file exists and has the expected lines to be removed. |
| 9 |
- Reads the patch line-by-line and applies each file as parsed. |
| 10 |
""" |
| 11 |
|
| 12 |
import os |
| 13 |
import pathlib |
| 14 |
from typing import List, Tuple, Optional |
| 15 |
|
| 16 |
|
| 17 |
def _parse_patch_file_path(file_path: str) -> Optional[str]: |
| 18 |
if file_path == "/dev/null": |
| 19 |
return None |
| 20 |
return file_path[2:] if file_path.startswith(("a/", "b/")) else file_path |
| 21 |
|
| 22 |
|
| 23 |
def _write_file(path: pathlib.Path, lines_without_linebreaks): |
| 24 |
path.parent.mkdir(exist_ok=True) |
| 25 |
with path.open(mode="w", encoding="utf-8", newline="\n") as f: |
| 26 |
for line in lines_without_linebreaks: |
| 27 |
f.write(line + "\n") |
| 28 |
|
| 29 |
|
| 30 |
def _parse_hunk_header(hdr: str) -> Tuple[int, int, int, int]: |
| 31 |
""" |
| 32 |
Parse a unified diff hunk header like: |
| 33 |
@@ -old_start,old_count +new_start,new_count @@ optional |
| 34 |
where the counts may be omitted (meaning 1). |
| 35 |
|
| 36 |
Returns (old_start, old_count, new_start, new_count). |
| 37 |
""" |
| 38 |
parts = hdr.split() |
| 39 |
old = parts[1] # like -12,3 or -12 |
| 40 |
new = parts[2] # like +12,4 or +12 |
| 41 |
def pr(r: str) -> Tuple[int, int]: |
| 42 |
r = r[1:] |
| 43 |
if ',' in r: |
| 44 |
a, b = r.split(',', 1) |
| 45 |
return int(a), int(b) |
| 46 |
return int(r), 1 |
| 47 |
old_s, old_c = pr(old) |
| 48 |
new_s, new_c = pr(new) |
| 49 |
return old_s, old_c, new_s, new_c |
| 50 |
|
| 51 |
|
| 52 |
def _write_new_file(file_path: pathlib.Path, body_lines): |
| 53 |
lines = [ln[1:] for ln in body_lines if ln and ln[0] == "+"] |
| 54 |
_write_file(file_path, lines) |
| 55 |
return |
| 56 |
|
| 57 |
|
| 58 |
def _apply_hunk(source_path: pathlib.Path, target_path: pathlib.Path, body_lines: List[str]) -> None: |
| 59 |
""" |
| 60 |
Parse and apply a single patch section. |
| 61 |
|
| 62 |
- body_lines: lines between the +++ header and the next --- header (raw diff lines). |
| 63 |
""" |
| 64 |
# Modification: apply contiguous delete-blocks then insert-blocks |
| 65 |
with open(source_path, "r", encoding="utf-8", newline="") as f: |
| 66 |
orig = f.read().splitlines() |
| 67 |
|
| 68 |
result_lines: List[str] = [] |
| 69 |
orig_idx = 0 # 0-based index into orig |
| 70 |
|
| 71 |
# process hunk by hunk |
| 72 |
patch_lines = iter(body_lines) |
| 73 |
for line in patch_lines: |
| 74 |
if not line.startswith('@@ '): |
| 75 |
continue |
| 76 |
# parse hunk header |
| 77 |
old_start, old_count, _, new_count = _parse_hunk_header(line) |
| 78 |
# append unchanged lines before this hunk (old_start is 1-based) |
| 79 |
before = old_start - 1 - orig_idx |
| 80 |
if before > 0: |
| 81 |
result_lines.extend(orig[orig_idx: orig_idx + before]) |
| 82 |
orig_idx += before |
| 83 |
|
| 84 |
# now process hunk body: consume exactly old_count deletions ('-') and new_count additions ('+') |
| 85 |
deleted = 0 |
| 86 |
added = 0 |
| 87 |
|
| 88 |
# first consume body lines until we've seen old_count deletions and new_count additions |
| 89 |
# but we process sequentially and append additions immediately |
| 90 |
while deleted < old_count or added < new_count: |
| 91 |
line = next(patch_lines) |
| 92 |
if not line or line[0] not in '+-': |
| 93 |
continue |
| 94 |
if line[0] == '-': |
| 95 |
if deleted < old_count: |
| 96 |
# consume one original line (drop it) |
| 97 |
assert line[1:] == orig[orig_idx], f"Deleted line mismatches: {line[1:]!r} != {orig[orig_idx]!r}" |
| 98 |
orig_idx += 1 |
| 99 |
deleted += 1 |
| 100 |
else: |
| 101 |
if added < new_count: |
| 102 |
result_lines.append(line[1:]) |
| 103 |
added += 1 |
| 104 |
|
| 105 |
# append remainder of original |
| 106 |
if orig_idx < len(orig): |
| 107 |
result_lines.extend(orig[orig_idx:]) |
| 108 |
|
| 109 |
_write_file(target_path, result_lines) |
| 110 |
|
| 111 |
|
| 112 |
def apply_patch(lines, root: str = ".") -> None: |
| 113 |
root_path = pathlib.Path(root) |
| 114 |
it = iter(lines) |
| 115 |
|
| 116 |
for line in it: |
| 117 |
if not line.startswith("--- "): |
| 118 |
continue |
| 119 |
source = _parse_patch_file_path(line[4:-1]) |
| 120 |
line = next(it) |
| 121 |
assert line.startswith('+++ '), line |
| 122 |
target = _parse_patch_file_path(line[4:-1]) |
| 123 |
|
| 124 |
# collect body for this file until next '--- ' or EOF |
| 125 |
body: List[str] = [] |
| 126 |
for line in it: |
| 127 |
if not line or line[0] not in '+-@ ': |
| 128 |
break |
| 129 |
body.append(line.rstrip('\n')) |
| 130 |
|
| 131 |
if body: |
| 132 |
if source: |
| 133 |
print(f"Patching file {target}") |
| 134 |
_apply_hunk(root_path / source, root_path / target, body) |
| 135 |
else: |
| 136 |
print(f"Creating file {target}") |
| 137 |
_write_new_file(root_path / target, body) |
| 138 |
|
| 139 |
|
| 140 |
def apply_patch_file(patch_file: str, root: str = ".") -> None: |
| 141 |
with open(patch_file) as f: |
| 142 |
patch_lines = f.readlines() |
| 143 |
apply_patch(patch_lines, root) |