fix(tools): preserve supplied newlines when creating files
This commit is contained in:
1 parent
042bcbbe46
commit
ae6801d3eb
2 files changed
+25
-3
No files matched your search
@@ -579,7 +579,7 @@ class WriteFileTool(_FsTool):
|
||||
raise ValueError("Unknown content")
|
||||
fp = self._resolve_write(path)
|
||||
fp.parent.mkdir(parents=True, exist_ok=True)
|
||||
fp.write_text(content, encoding="utf-8")
|
||||
fp.write_text(content, encoding="utf-8", newline="")
|
||||
self._file_states.record_write(fp)
|
||||
return f"Successfully wrote {len(content)} characters to {fp}"
|
||||
except PermissionError as e:
|
||||
@@ -948,7 +948,7 @@ class EditFileTool(_FsTool):
|
||||
if not file_exists:
|
||||
if old_text == "":
|
||||
fp.parent.mkdir(parents=True, exist_ok=True)
|
||||
fp.write_text(new_text, encoding="utf-8")
|
||||
fp.write_text(new_text, encoding="utf-8", newline="")
|
||||
self._file_states.record_write(fp)
|
||||
return self._format_summary(fp, "", fp.read_bytes().decode("utf-8"), created=True)
|
||||
return self._file_not_found_msg(path, fp)
|
||||
@@ -967,7 +967,7 @@ class EditFileTool(_FsTool):
|
||||
content = raw.decode("utf-8")
|
||||
if content.strip():
|
||||
return ToolResult.error(f"Error: Cannot create file — {path} already exists and is not empty.")
|
||||
fp.write_text(new_text, encoding="utf-8")
|
||||
fp.write_text(new_text, encoding="utf-8", newline="")
|
||||
self._file_states.record_write(fp)
|
||||
return self._format_summary(fp, content, fp.read_bytes().decode("utf-8"))
|
||||
|
||||
|
||||
@@ -10,6 +10,28 @@ from nanobot.agent.tools.filesystem import (
|
||||
WriteFileTool,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("newline", ["\n", "\r\n", "\r"])
|
||||
@pytest.mark.parametrize("operation", ["write", "edit_new", "edit_empty"])
|
||||
async def test_file_creation_preserves_provided_newlines(tmp_path, newline, operation):
|
||||
target = tmp_path / "nested" / "script.py"
|
||||
content = f"first = 1{newline}second = 2{newline}"
|
||||
if operation == "write":
|
||||
result = await WriteFileTool(workspace=tmp_path).execute(
|
||||
path=str(target), content=content,
|
||||
)
|
||||
else:
|
||||
if operation == "edit_empty":
|
||||
target.parent.mkdir()
|
||||
target.touch()
|
||||
result = await EditFileTool(workspace=tmp_path).execute(
|
||||
path=str(target), old_text="", new_text=content,
|
||||
)
|
||||
|
||||
assert "Error" not in result
|
||||
assert target.read_bytes() == content.encode("utf-8")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ReadFileTool
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user