Apply a diff to the original code using the specified SEARCH/REPLACE format. Args: original_code: The original source code string. diff_text: The text containing one or more diff blocks. diff_pattern: The regex pattern to identify the SEARCH/REPLACE format. Ret
(
original_code: str,
diff_text: str,
diff_pattern: str = r"<<<<<<< SEARCH\n(.*?)=======\n(.*?)>>>>>>> REPLACE",
)
| 46 | |
| 47 | |
| 48 | def apply_diff( |
| 49 | original_code: str, |
| 50 | diff_text: str, |
| 51 | diff_pattern: str = r"<<<<<<< SEARCH\n(.*?)=======\n(.*?)>>>>>>> REPLACE", |
| 52 | ) -> str: |
| 53 | """ |
| 54 | Apply a diff to the original code using the specified SEARCH/REPLACE format. |
| 55 | |
| 56 | Args: |
| 57 | original_code: The original source code string. |
| 58 | diff_text: The text containing one or more diff blocks. |
| 59 | diff_pattern: The regex pattern to identify the SEARCH/REPLACE format. |
| 60 | |
| 61 | Returns: |
| 62 | The modified code string after applying all diffs. |
| 63 | """ |
| 64 | # Split into lines for easier processing and replacement |
| 65 | original_lines = original_code.split("\n") |
| 66 | result_lines = original_lines.copy() |
| 67 | |
| 68 | # Extract all diff blocks from the provided text |
| 69 | diff_blocks = extract_diffs(diff_text, diff_pattern) |
| 70 | |
| 71 | # Apply each diff block sequentially |
| 72 | for search_text, replace_text in diff_blocks: |
| 73 | search_lines = search_text.split("\n") |
| 74 | replace_lines = replace_text.split("\n") |
| 75 | |
| 76 | # Find where the search pattern starts in the current version of the code |
| 77 | # We iterate through the `result_lines` which may have been modified by previous diffs |
| 78 | for i in range(len(result_lines) - len(search_lines) + 1): |
| 79 | # Check if the slice of lines matches the search lines exactly |
| 80 | if result_lines[i : i + len(search_lines)] == search_lines: |
| 81 | # If a match is found, replace that slice with the replacement lines |
| 82 | result_lines[i : i + len(search_lines)] = replace_lines |
| 83 | # Break after the first match to avoid applying the same diff multiple times |
| 84 | break |
| 85 | |
| 86 | # Join the modified lines back into a single string |
| 87 | return "\n".join(result_lines) |
| 88 | |
| 89 | |
| 90 | def extract_diffs( |
no test coverage detected