Skip to content
Merged
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
4 changes: 4 additions & 0 deletions aider/tools/insert_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,10 @@ def execute(
new_lines = lines[:insertion_line_idx] + content_lines + lines[insertion_line_idx:]
new_content = "\n".join(new_lines)

# Restore trailing newline if original file had one
if original_content.endswith("\n"):
new_content += "\n"

if original_content == new_content:
coder.io.tool_warning("No changes made: insertion would not change file")
return "Warning: No changes made (insertion would not change file)"
Expand Down
32 changes: 32 additions & 0 deletions tests/tools/test_insert_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,35 @@ def test_mutually_exclusive_parameters_raise(coder_with_file):
assert result.startswith("Error: Must specify exactly one of")
assert file_path.read_text().startswith("first line")
coder.io.tool_error.assert_called()


def test_trailing_newline_preservation(coder_with_file):
coder, file_path = coder_with_file
insert_block.Tool.execute(
coder,
file_path="example.txt",
content="inserted line",
position="top",
)

content = file_path.read_text()
assert content.endswith("\n"), "File should preserve trailing newline"
coder.io.tool_error.assert_not_called()


def test_no_trailing_newline_preservation(coder_with_file):
coder, file_path = coder_with_file

content_without_trailing_newline = "first line\nsecond line"
file_path.write_text(content_without_trailing_newline)

insert_block.Tool.execute(
coder,
file_path="example.txt",
content="inserted line",
position="top",
)

content = file_path.read_text()
assert not content.endswith("\n"), "File should preserve lack of trailing newline"
coder.io.tool_error.assert_not_called()
Loading