Skip to content

Commit

Permalink
Patched patchwork/steps/ModifyCode/ModifyCode.py
Browse files Browse the repository at this point in the history
  • Loading branch information
patched.codes[bot] committed Jan 8, 2025
1 parent 3e81f25 commit 81e23d8
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions patchwork/steps/ModifyCode/ModifyCode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 81e23d8

Please sign in to comment.