Skip to content

Commit 804ed75

Browse files
author
patched.codes[bot]
committed
Patched patchwork/steps/ModifyCode/ModifyCode.py
1 parent 4eb9946 commit 804ed75

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

patchwork/steps/ModifyCode/ModifyCode.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
def save_file_contents(file_path, content):
99
"""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
1111
file.write(content)
1212

1313

@@ -39,23 +39,43 @@ def replace_code_in_file(
3939
new_code: str,
4040
) -> None:
4141
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 = ""
4549

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'
4957

58+
# Split lines while preserving line endings
59+
if text:
5060
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+
]
5169

70+
if path.exists() and start_line is not None and end_line is not None:
5271
# Insert the new code at the start line after converting it into a list of lines
5372
lines[start_line:end_line] = handle_indent(lines, new_code_lines, start_line, end_line)
5473
else:
5574
lines = new_code_lines
5675

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))
5979

6080

6181
class ModifyCode(Step):

0 commit comments

Comments
 (0)