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
11 changes: 3 additions & 8 deletions src/bub/builtin/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"


Expand Down
11 changes: 11 additions & 0 deletions tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading