MCPcopy Create free account
hub / github.com/bytedance/trae-agent / str_replace

Method str_replace

trae_agent/tools/edit_tool_cli.py:241–280  ·  view source on GitHub ↗

Implement the str_replace command, which replaces old_str with new_str in the file content

(self, path: Path, old_str: str, new_str: str | None)

Source from the content-addressed store, hash-verified

239 )
240
241 def str_replace(self, path: Path, old_str: str, new_str: str | None) -> ToolExecResult:
242 """Implement the str_replace command, which replaces old_str with new_str in the file content"""
243 # Read the file content
244 file_content = self.read_file(path).expandtabs()
245 old_str = old_str.expandtabs()
246 new_str = new_str.expandtabs() if new_str is not None else ""
247
248 # Check if old_str is unique in the file
249 occurrences = file_content.count(old_str)
250 if occurrences == 0:
251 raise ToolError(
252 f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}."
253 )
254 elif occurrences > 1:
255 file_content_lines = file_content.split("\n")
256 lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]
257 raise ToolError(
258 f"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique"
259 )
260
261 # Replace old_str with new_str
262 new_file_content = file_content.replace(old_str, new_str)
263
264 # Write the new content to the file
265 self.write_file(path, new_file_content)
266
267 # Create a snippet of the edited section
268 replacement_line = file_content.split(old_str)[0].count("\n")
269 start_line = max(0, replacement_line - SNIPPET_LINES)
270 end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
271 snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
272
273 # Prepare the success message
274 success_msg = f"The file {path} has been edited. "
275 success_msg += self._make_output(snippet, f"a snippet of {path}", start_line + 1)
276 success_msg += "Review the changes and make sure they are as expected. Edit the file again if necessary."
277
278 return ToolExecResult(
279 output=success_msg,
280 )
281
282 def _insert(self, path: Path, insert_line: int, new_str: str) -> ToolExecResult:
283 """Implement the insert command, which inserts new_str at the specified line in the file content."""

Callers 1

_str_replace_handlerMethod · 0.95

Calls 6

read_fileMethod · 0.95
write_fileMethod · 0.95
_make_outputMethod · 0.95
replaceMethod · 0.80
ToolErrorClass · 0.70
ToolExecResultClass · 0.70

Tested by

no test coverage detected