Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion patchwork/common/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def defered_temp_file(
return tempfile_fp


def open_with_chardet(file, mode="r", buffering=-1, errors=None, newline=None, closefd=True, opener=None):
def open_with_chardet(file, mode="r", buffering=-1, errors=None, newline="", closefd=True, opener=None):
detector = UniversalDetector()
with open(
file=file, mode="rb", buffering=buffering, errors=errors, newline=newline, closefd=closefd, opener=opener
Expand Down
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
Loading