|
| 1 | +import os |
| 2 | +import re |
| 3 | + |
| 4 | + |
| 5 | +class PatchTool: |
| 6 | + @staticmethod |
| 7 | + def apply_patch(file_path: str, patch_content: str) -> str: |
| 8 | + """ |
| 9 | + Applies a unified diff patch to a file. |
| 10 | + Returns the new content of the file. |
| 11 | + """ |
| 12 | + if not os.path.exists(file_path): |
| 13 | + content = [] |
| 14 | + else: |
| 15 | + with open(file_path, "r", encoding="utf-8") as f: |
| 16 | + content = f.readlines() |
| 17 | + |
| 18 | + patch_lines = patch_content.splitlines(keepends=True) |
| 19 | + hunk_re = re.compile(r"^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@") |
| 20 | + |
| 21 | + hunks = [] |
| 22 | + current_hunk = None |
| 23 | + |
| 24 | + for line in patch_lines: |
| 25 | + if line.startswith("---") or line.startswith("+++"): |
| 26 | + continue |
| 27 | + |
| 28 | + match = hunk_re.match(line) |
| 29 | + if match: |
| 30 | + if current_hunk: |
| 31 | + hunks.append(current_hunk) |
| 32 | + current_hunk = { |
| 33 | + "start_old": int(match.group(1)), |
| 34 | + "len_old": int(match.group(2) or 1), |
| 35 | + "start_new": int(match.group(3)), |
| 36 | + "len_new": int(match.group(4) or 1), |
| 37 | + "lines": [], |
| 38 | + } |
| 39 | + elif current_hunk: |
| 40 | + current_hunk["lines"].append(line) |
| 41 | + |
| 42 | + if current_hunk: |
| 43 | + hunks.append(current_hunk) |
| 44 | + |
| 45 | + result_lines = list(content) |
| 46 | + offset = 0 |
| 47 | + |
| 48 | + for hunk in hunks: |
| 49 | + start_in_file = hunk["start_old"] - 1 + offset |
| 50 | + old_len = hunk["len_old"] |
| 51 | + |
| 52 | + new_hunk_lines = [] |
| 53 | + for h_line in hunk["lines"]: |
| 54 | + if h_line.startswith(" "): |
| 55 | + new_hunk_lines.append(h_line[1:]) |
| 56 | + elif h_line.startswith("+"): |
| 57 | + new_hunk_lines.append(h_line[1:]) |
| 58 | + elif h_line.startswith("-"): |
| 59 | + pass |
| 60 | + |
| 61 | + # Pad result_lines if the patch references lines beyond current EOF |
| 62 | + while len(result_lines) < start_in_file: |
| 63 | + result_lines.append("\n") |
| 64 | + |
| 65 | + result_lines[start_in_file : start_in_file + old_len] = new_hunk_lines |
| 66 | + offset += len(new_hunk_lines) - old_len |
| 67 | + |
| 68 | + return "".join(result_lines) |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + import sys |
| 73 | + |
| 74 | + if len(sys.argv) == 3: |
| 75 | + path, patch_file = sys.argv[1], sys.argv[2] |
| 76 | + with open(patch_file, "r") as pf: |
| 77 | + patch = pf.read() |
| 78 | + new_text = PatchTool.apply_patch(path, patch) |
| 79 | + with open(path, "w") as f: |
| 80 | + f.write(new_text) |
| 81 | + print(f"Applied patch to {path}") |
0 commit comments