Execute edit file.
(self, path: str, old_str: str, new_str: str)
| 254 | } |
| 255 | |
| 256 | async def execute(self, path: str, old_str: str, new_str: str) -> ToolResult: |
| 257 | """Execute edit file.""" |
| 258 | try: |
| 259 | file_path = Path(path) |
| 260 | # Resolve relative paths relative to workspace_dir |
| 261 | if not file_path.is_absolute(): |
| 262 | file_path = self.workspace_dir / file_path |
| 263 | |
| 264 | if not file_path.exists(): |
| 265 | return ToolResult( |
| 266 | success=False, |
| 267 | content="", |
| 268 | error=f"File not found: {path}", |
| 269 | ) |
| 270 | |
| 271 | content = file_path.read_text(encoding="utf-8") |
| 272 | |
| 273 | if old_str not in content: |
| 274 | return ToolResult( |
| 275 | success=False, |
| 276 | content="", |
| 277 | error=f"Text not found in file: {old_str}", |
| 278 | ) |
| 279 | |
| 280 | new_content = content.replace(old_str, new_str) |
| 281 | file_path.write_text(new_content, encoding="utf-8") |
| 282 | |
| 283 | return ToolResult(success=True, content=f"Successfully edited {file_path}") |
| 284 | except Exception as e: |
| 285 | return ToolResult(success=False, content="", error=str(e)) |