64 lines
2 KiB
Python
64 lines
2 KiB
Python
"""WriteTool — create or overwrite a file with given content.
|
|
|
|
Creates parent directories as needed.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from typing import Any, ClassVar
|
|
|
|
from ..base import Tool, ToolParameter, ToolResult
|
|
|
|
|
|
class WriteTool(Tool):
|
|
"""Create or overwrite a file with the provided content.
|
|
|
|
Parent directories are created automatically if they do not exist.
|
|
"""
|
|
|
|
name: ClassVar[str] = "write"
|
|
description: ClassVar[str] = (
|
|
"Write content to a file, creating it if it does not exist. "
|
|
"Creates parent directories as needed."
|
|
)
|
|
parameters: ClassVar[list[ToolParameter]] = [
|
|
ToolParameter(
|
|
name="file_path",
|
|
type="string",
|
|
description="Absolute path to the file to write",
|
|
),
|
|
ToolParameter(
|
|
name="content",
|
|
type="string",
|
|
description="Content to write to the file",
|
|
),
|
|
]
|
|
|
|
async def execute(self, **kwargs: Any) -> ToolResult:
|
|
file_path = Path(kwargs["file_path"])
|
|
content: str = kwargs["content"]
|
|
|
|
if not file_path.is_absolute():
|
|
return ToolResult.fail(f"Path must be absolute: {file_path}")
|
|
|
|
created = not file_path.exists()
|
|
|
|
try:
|
|
file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
file_path.write_text(content, encoding="utf-8")
|
|
except PermissionError:
|
|
return ToolResult.fail(f"Permission denied: {file_path}")
|
|
except OSError as exc:
|
|
return ToolResult.fail(f"Write failed: {exc}")
|
|
|
|
action = "Created" if created else "Overwrote"
|
|
byte_count = len(content.encode("utf-8"))
|
|
line_count = content.count("\n") + (1 if content and not content.endswith("\n") else 0)
|
|
|
|
return ToolResult.success(
|
|
f"{action} {file_path} ({byte_count} bytes, {line_count} lines)",
|
|
file_path=str(file_path),
|
|
created=created,
|
|
bytes_written=byte_count,
|
|
)
|