|
7 | 7 |
|
8 | 8 | def save_file_contents(file_path, content): |
9 | 9 | """Utility function to save content to a file.""" |
10 | | - with open(file_path, "w") as file: |
| 10 | + with open(file_path, "w", newline="") as file: # Add newline="" parameter |
11 | 11 | file.write(content) |
12 | 12 |
|
13 | 13 |
|
@@ -39,23 +39,43 @@ def replace_code_in_file( |
39 | 39 | new_code: str, |
40 | 40 | ) -> None: |
41 | 41 | path = Path(file_path) |
42 | | - 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" |
| 42 | + |
| 43 | + # Read file in binary mode to preserve line endings |
| 44 | + if path.exists(): |
| 45 | + with open(file_path, 'rb') as f: |
| 46 | + text = f.read().decode('utf-8') |
| 47 | + else: |
| 48 | + text = "" |
45 | 49 |
|
46 | | - if path.exists() and start_line is not None and end_line is not None: |
47 | | - """Replaces specified lines in a file with new code.""" |
48 | | - text = path.read_text() |
| 50 | + # Detect original line ending style |
| 51 | + if '\r\n' in text: |
| 52 | + line_ending = '\r\n' |
| 53 | + elif '\r' in text: |
| 54 | + line_ending = '\r' |
| 55 | + else: |
| 56 | + line_ending = '\n' |
49 | 57 |
|
| 58 | + # Split lines while preserving line endings |
| 59 | + if text: |
50 | 60 | lines = text.splitlines(keepends=True) |
| 61 | + else: |
| 62 | + lines = [] |
| 63 | + |
| 64 | + # Convert new code to match original line endings |
| 65 | + new_code_lines = [ |
| 66 | + line + line_ending if not line.endswith(('\r\n', '\r', '\n')) else line |
| 67 | + for line in new_code.splitlines(keepends=True) |
| 68 | + ] |
51 | 69 |
|
| 70 | + if path.exists() and start_line is not None and end_line is not None: |
52 | 71 | # Insert the new code at the start line after converting it into a list of lines |
53 | 72 | lines[start_line:end_line] = handle_indent(lines, new_code_lines, start_line, end_line) |
54 | 73 | else: |
55 | 74 | lines = new_code_lines |
56 | 75 |
|
57 | | - # Save the modified contents back to the file |
58 | | - save_file_contents(file_path, "".join(lines)) |
| 76 | + # Save with preserved line endings |
| 77 | + with open(file_path, 'w', newline='') as f: |
| 78 | + f.write(''.join(lines)) |
59 | 79 |
|
60 | 80 |
|
61 | 81 | class ModifyCode(Step): |
|
0 commit comments