|
6 | 6 |
|
7 | 7 |
|
8 | 8 | def save_file_contents(file_path, content): |
9 | | - """Utility function to save content to a file.""" |
10 | | - with open(file_path, "w") as file: |
| 9 | + """Utility function to save content to a file while preserving line endings.""" |
| 10 | + with open(file_path, "w", newline="") as file: |
11 | 11 | file.write(content) |
12 | 12 |
|
13 | 13 |
|
@@ -38,17 +38,27 @@ def replace_code_in_file( |
38 | 38 | end_line: int | None, |
39 | 39 | new_code: str, |
40 | 40 | ) -> None: |
| 41 | + from patchwork.common.utils.utils import detect_newline, open_with_chardet |
| 42 | + |
41 | 43 | path = Path(file_path) |
| 44 | + original_newline = "\n" # default if file doesn't exist |
| 45 | + |
| 46 | + if path.exists(): |
| 47 | + original_newline = detect_newline(path) or "\n" |
| 48 | + with open_with_chardet(path, newline="") as f: |
| 49 | + text = f.read() |
| 50 | + lines = text.splitlines(keepends=True) |
| 51 | + else: |
| 52 | + lines = [] |
| 53 | + |
42 | 54 | new_code_lines = new_code.splitlines(keepends=True) |
43 | | - if len(new_code_lines) > 0 and not new_code_lines[-1].endswith("\n"): |
44 | | - new_code_lines[-1] += "\n" |
| 55 | + # Ensure consistent line endings in the new code |
| 56 | + new_code_lines = [line.rstrip("\r\n") + original_newline for line in new_code_lines] |
| 57 | + if len(new_code_lines) > 0 and not new_code_lines[-1].endswith(original_newline): |
| 58 | + new_code_lines[-1] += original_newline |
45 | 59 |
|
46 | 60 | if path.exists() and start_line is not None and end_line is not None: |
47 | 61 | """Replaces specified lines in a file with new code.""" |
48 | | - text = path.read_text() |
49 | | - |
50 | | - lines = text.splitlines(keepends=True) |
51 | | - |
52 | 62 | # Insert the new code at the start line after converting it into a list of lines |
53 | 63 | lines[start_line:end_line] = handle_indent(lines, new_code_lines, start_line, end_line) |
54 | 64 | else: |
|
0 commit comments