From 0a4e7e25308011632598922121b910e422c77d19 Mon Sep 17 00:00:00 2001 From: yuzhang Date: Fri, 4 Dec 2026 21:35:54 +0800 Subject: [PATCH] Allow fs.edit to match the final newline --- src/bub/builtin/tools.py | 11 +++-------- tests/test_environment.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/bub/builtin/tools.py b/src/bub/builtin/tools.py index 6e69ca90..dd9c6df6 100644 --- a/src/bub/builtin/tools.py +++ b/src/bub/builtin/tools.py @@ -363,16 +363,11 @@ async def fs_edit(path: str, old: str, new: str, start: int = 0, *, context: Too environment = environment_from_state(context.state) resolved_path = environment.resolve_path(path) text = await environment.read_text(resolved_path) - lines = text.splitlines() - prev, to_replace = "\n".join(lines[:start]), "\n".join(lines[start:]) + lines = text.splitlines(keepends=True) + prefix, to_replace = "".join(lines[:start]), "".join(lines[start:]) if old not in to_replace: raise ValueError(f"'{old}' not found in {resolved_path} from line {start}") - replaced = to_replace.replace(old, new) - if start > 0: - replaced = prev + "\n" + replaced - if text.endswith(("\n", "\r")): - replaced += "\n" - await environment.write_text(resolved_path, replaced) + await environment.write_text(resolved_path, prefix + to_replace.replace(old, new)) return f"edited: {resolved_path}" diff --git a/tests/test_environment.py b/tests/test_environment.py index e2264d08..db8b414f 100644 --- a/tests/test_environment.py +++ b/tests/test_environment.py @@ -93,6 +93,17 @@ async def test_fs_edit_preserves_trailing_newline(tmp_path: Path) -> None: assert environment.files == {"/environment/work/a.py": "x = 1\ny = 3\n"} +@pytest.mark.asyncio +async def test_fs_edit_matches_an_old_block_with_the_final_newline(tmp_path: Path) -> None: + context = _context(tmp_path, LocalEnvironment(tmp_path)) + path = tmp_path / "a.py" + path.write_text("y = 2\ny = 2\n", encoding="utf-8") + + await builtin_tools.fs_edit.run(path="a.py", old="y = 2\n", new="y = 3", start=1, context=context) + + assert path.read_text(encoding="utf-8") == "y = 2\ny = 3" + + @pytest.mark.asyncio async def test_fs_edit_preserves_leading_blank_line_when_start_is_one(tmp_path: Path) -> None: environment = MemoryEnvironment()