Skip to content
Open
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: 3 additions & 1 deletion src/bub/builtin/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,8 @@ async def fs_write(path: str, content: str, *, context: ToolContext) -> str:
@tool(context=True, name="fs.edit", exposure="direct")
async def fs_edit(path: str, old: str, new: str, start: int = 0, *, context: ToolContext) -> str:
"""Edit a text file by replacing old text with new text. You can specify the line number to start searching for the old text."""
if start < 0:
raise ValueError("start must be non-negative")
environment = environment_from_state(context.state)
resolved_path = environment.resolve_path(path)
text = await environment.read_text(resolved_path)
Expand All @@ -366,7 +368,7 @@ async def fs_edit(path: str, old: str, new: str, start: int = 0, *, context: Too
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 prev:
if start > 0:
replaced = prev + "\n" + replaced
if text.endswith(("\n", "\r")):
replaced += "\n"
Expand Down
21 changes: 21 additions & 0 deletions tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,27 @@ 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_preserves_leading_blank_line_when_start_is_one(tmp_path: Path) -> None:
environment = MemoryEnvironment()
context = _context(tmp_path, environment)

await builtin_tools.fs_write.run(path="a.py", content="\ny = 2\n", context=context)
await builtin_tools.fs_edit.run(path="a.py", old="y = 2", new="y = 3", start=1, context=context)

assert environment.files == {"/environment/work/a.py": "\ny = 3\n"}


@pytest.mark.asyncio
async def test_fs_edit_rejects_negative_start(tmp_path: Path) -> None:
environment = MemoryEnvironment()
context = _context(tmp_path, environment)

await builtin_tools.fs_write.run(path="a.py", content="x = 1\ny = 2\n", context=context)
with pytest.raises(ValueError, match="non-negative"):
await builtin_tools.fs_edit.run(path="a.py", old="y = 2", new="y = 3", start=-1, context=context)


@pytest.mark.asyncio
async def test_bash_spawns_in_the_session_environment_with_cwd_resolved_there(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setattr(builtin_tools, "shell_manager", ShellManager())
Expand Down
Loading