From 81e23d86176e55dde5f9faf6aea0c6a357e413d4 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Wed, 8 Jan 2025 13:14:25 +0000 Subject: [PATCH] Patched patchwork/steps/ModifyCode/ModifyCode.py --- patchwork/steps/ModifyCode/ModifyCode.py | 26 ++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/patchwork/steps/ModifyCode/ModifyCode.py b/patchwork/steps/ModifyCode/ModifyCode.py index f7c6d7e4f..2bdd9f3df 100644 --- a/patchwork/steps/ModifyCode/ModifyCode.py +++ b/patchwork/steps/ModifyCode/ModifyCode.py @@ -6,8 +6,8 @@ def save_file_contents(file_path, content): - """Utility function to save content to a file.""" - with open(file_path, "w") as file: + """Utility function to save content to a file while preserving line endings.""" + with open(file_path, "w", newline="") as file: file.write(content) @@ -38,17 +38,27 @@ def replace_code_in_file( end_line: int | None, new_code: str, ) -> None: + from patchwork.common.utils.utils import detect_newline, open_with_chardet + path = Path(file_path) + original_newline = "\n" # default if file doesn't exist + + if path.exists(): + original_newline = detect_newline(path) or "\n" + with open_with_chardet(path, newline="") as f: + text = f.read() + lines = text.splitlines(keepends=True) + else: + lines = [] + new_code_lines = new_code.splitlines(keepends=True) - if len(new_code_lines) > 0 and not new_code_lines[-1].endswith("\n"): - new_code_lines[-1] += "\n" + # Ensure consistent line endings in the new code + new_code_lines = [line.rstrip("\r\n") + original_newline for line in new_code_lines] + if len(new_code_lines) > 0 and not new_code_lines[-1].endswith(original_newline): + new_code_lines[-1] += original_newline if path.exists() and start_line is not None and end_line is not None: """Replaces specified lines in a file with new code.""" - text = path.read_text() - - lines = text.splitlines(keepends=True) - # Insert the new code at the start line after converting it into a list of lines lines[start_line:end_line] = handle_indent(lines, new_code_lines, start_line, end_line) else: