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

Method str_replace

trae_agent/tools/edit_tool.py:197–236  ·  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

195 )
196
197 def str_replace(self, path: Path, old_str: str, new_str: str | None) -> ToolExecResult:
198 """Implement the str_replace command, which replaces old_str with new_str in the file content"""
199 # Read the file content
200 file_content = self.read_file(path).expandtabs()
201 old_str = old_str.expandtabs()
202 new_str = new_str.expandtabs() if new_str is not None else ""
203
204 # Check if old_str is unique in the file
205 occurrences = file_content.count(old_str)
206 if occurrences == 0:
207 raise ToolError(
208 f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}."
209 )
210 elif occurrences > 1:
211 file_content_lines = file_content.split("\n")
212 lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]
213 raise ToolError(
214 f"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique"
215 )
216
217 # Replace old_str with new_str
218 new_file_content = file_content.replace(old_str, new_str)
219
220 # Write the new content to the file
221 self.write_file(path, new_file_content)
222
223 # Create a snippet of the edited section
224 replacement_line = file_content.split(old_str)[0].count("\n")
225 start_line = max(0, replacement_line - SNIPPET_LINES)
226 end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
227 snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
228
229 # Prepare the success message
230 success_msg = f"The file {path} has been edited. "
231 success_msg += self._make_output(snippet, f"a snippet of {path}", start_line + 1)
232 success_msg += "Review the changes and make sure they are as expected. Edit the file again if necessary."
233
234 return ToolExecResult(
235 output=success_msg,
236 )
237
238 def _insert(self, path: Path, insert_line: int, new_str: str) -> ToolExecResult:
239 """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
ToolErrorClass · 0.90
ToolExecResultClass · 0.90
replaceMethod · 0.80

Tested by

no test coverage detected