|
| 1 | +import re |
| 2 | +import sys |
| 3 | +import os |
| 4 | + |
| 5 | + |
| 6 | +def convert_rej_to_patch(rej_file_path, output_patch_path=None): |
| 7 | + # Check if the .rej file exists |
| 8 | + if not os.path.exists(rej_file_path): |
| 9 | + print(f"Error: File {rej_file_path} not found.") |
| 10 | + sys.exit(1) |
| 11 | + |
| 12 | + # Set the output file path |
| 13 | + if not output_patch_path: |
| 14 | + output_patch_path = rej_file_path.replace(".rej", ".patch") |
| 15 | + |
| 16 | + # Regular expressions to match diff and hunk lines |
| 17 | + hunk_header_regex = re.compile(r"^@@\s") |
| 18 | + |
| 19 | + # Process the .rej file and convert to .patch |
| 20 | + with open(rej_file_path, "r") as rej_file, open( |
| 21 | + output_patch_path, "w" |
| 22 | + ) as patch_file: |
| 23 | + inside_hunk = False |
| 24 | + file_a, file_b = None, None |
| 25 | + |
| 26 | + for line in rej_file: |
| 27 | + # Look for the first diff header |
| 28 | + if line.startswith("diff"): |
| 29 | + # Extract the file names (assuming `diff a/file b/file`) |
| 30 | + parts = line.split() |
| 31 | + file_a = parts[1] |
| 32 | + file_b = parts[2] |
| 33 | + inside_hunk = False # Reset flag |
| 34 | + patch_file.write(line) |
| 35 | + |
| 36 | + # Detect hunk headers (@@ -start,length +start,length @@) |
| 37 | + elif hunk_header_regex.match(line): |
| 38 | + inside_hunk = True |
| 39 | + # Add the diff header if it's missing |
| 40 | + if file_a and file_b: |
| 41 | + patch_file.write(f"--- {file_a}\n") |
| 42 | + patch_file.write(f"+++ {file_b}\n") |
| 43 | + file_a, file_b = None, None |
| 44 | + patch_file.write(line) |
| 45 | + # Write the patch lines that follow the hunk headers (+, -) |
| 46 | + elif inside_hunk: |
| 47 | + patch_file.write(line) |
| 48 | + |
| 49 | + print(f"Conversion complete: {output_patch_path}") |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + if len(sys.argv) != 2: |
| 54 | + print("Usage: python rej_to_patch.py <path_to_rej_file>") |
| 55 | + sys.exit(1) |
| 56 | + |
| 57 | + rej_file_path = sys.argv[1] |
| 58 | + convert_rej_to_patch(rej_file_path) |
0 commit comments