Implement the insert command, which inserts new_str at the specified line in the file content.
(self, path: Path, insert_line: int, new_str: str)
| 202 | return CLIResult(output=success_msg) |
| 203 | |
| 204 | def insert(self, path: Path, insert_line: int, new_str: str): |
| 205 | """Implement the insert command, which inserts new_str at the specified line in the file content.""" |
| 206 | file_text = self.read_file(path).expandtabs() |
| 207 | new_str = new_str.expandtabs() |
| 208 | file_text_lines = file_text.split("\n") |
| 209 | n_lines_file = len(file_text_lines) |
| 210 | |
| 211 | if insert_line < 0 or insert_line > n_lines_file: |
| 212 | raise ToolError( |
| 213 | f"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: {[0, n_lines_file]}" |
| 214 | ) |
| 215 | |
| 216 | new_str_lines = new_str.split("\n") |
| 217 | new_file_text_lines = ( |
| 218 | file_text_lines[:insert_line] |
| 219 | + new_str_lines |
| 220 | + file_text_lines[insert_line:] |
| 221 | ) |
| 222 | snippet_lines = ( |
| 223 | file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line] |
| 224 | + new_str_lines |
| 225 | + file_text_lines[insert_line : insert_line + SNIPPET_LINES] |
| 226 | ) |
| 227 | |
| 228 | new_file_text = "\n".join(new_file_text_lines) |
| 229 | snippet = "\n".join(snippet_lines) |
| 230 | |
| 231 | self.write_file(path, new_file_text) |
| 232 | self._file_history[path].append(file_text) |
| 233 | |
| 234 | success_msg = f"The file {path} has been edited. " |
| 235 | success_msg += self._make_output( |
| 236 | snippet, |
| 237 | "a snippet of the edited file", |
| 238 | max(1, insert_line - SNIPPET_LINES + 1), |
| 239 | ) |
| 240 | success_msg += "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary." |
| 241 | return CLIResult(output=success_msg) |
| 242 | |
| 243 | def undo_edit(self, path: Path): |
| 244 | """Implement the undo_edit command.""" |
no test coverage detected