Skip to content

Commit 81e23d8

Browse files
author
patched.codes[bot]
committed
Patched patchwork/steps/ModifyCode/ModifyCode.py
1 parent 3e81f25 commit 81e23d8

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

patchwork/steps/ModifyCode/ModifyCode.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77

88
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:
1111
file.write(content)
1212

1313

@@ -38,17 +38,27 @@ def replace_code_in_file(
3838
end_line: int | None,
3939
new_code: str,
4040
) -> None:
41+
from patchwork.common.utils.utils import detect_newline, open_with_chardet
42+
4143
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+
4254
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
4559

4660
if path.exists() and start_line is not None and end_line is not None:
4761
"""Replaces specified lines in a file with new code."""
48-
text = path.read_text()
49-
50-
lines = text.splitlines(keepends=True)
51-
5262
# Insert the new code at the start line after converting it into a list of lines
5363
lines[start_line:end_line] = handle_indent(lines, new_code_lines, start_line, end_line)
5464
else:

0 commit comments

Comments
 (0)