SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Add insert function
Kilian Lieret603030621683
diff --git a/tools/defaults/lib/default_utils.py b/tools/defaults/lib/default_utils.pyindex a2cddd4c..8048c591 100644--- a/tools/defaults/lib/default_utils.py+++ b/tools/defaults/lib/default_utils.py@@ -73,6 +73,15 @@ class ReplacementInfo:"""Number of replacements made."""+@dataclass+class InsertInfo:+ first_inserted_line: int+ """Line number of the beginning of the first search hit."""++ n_lines_added: int+ """Number of lines added."""++class WindowedFile:def __init__(self,@@ -102,7 +111,7 @@ class WindowedFile:"""_path = registry.get_if_none(path, "CURRENT_FILE")self._exit_on_exception = exit_on_exception- if _path is None:+ if not _path:if self._exit_on_exception:print("No file open. Use the open command first.")exit(1)@@ -124,6 +133,7 @@ class WindowedFile:self.window = int(registry.get_if_none(window, "WINDOW"))self.overlap = int(registry.get("OVERLAP", 0))# Ensure that we get a valid current line by using the setter+ self._first_line = 0self.first_line = int(registry.get_if_none(first_line,@@ -283,3 +293,26 @@ class WindowedFile:def undo_edit(self):self.text = self._original_textself.first_line = self._original_first_line++ def insert(+ self, text: str, line: int | None = None, *, reset_first_line: Literal["top", "keep"] = "top"+ ) -> InsertInfo:+ if line is None:+ if self.text.endswith("\n"):+ line = self.n_lines+ new_text = self.text + text+ else:+ line = self.n_lines + 1+ new_text = self.text + "\n" + text+ elif line < 0:+ new_text = text + "\n" + self.text+ else:+ _lines = self.text.splitlines()+ lines = _lines[: line + 1] + text.splitlines() + _lines[line + 1 :]+ new_text = "\n".join(lines)+ self.text = new_text+ if reset_first_line == "keep":+ pass+ else:+ self.goto(line, mode=reset_first_line)+ return InsertInfo(first_inserted_line=line, n_lines_added=len(text.splitlines()))diff --git a/tools/edit_replace/bin/edit b/tools/edit_replace/bin/editindex f2fb327f..6a4920f2 100644--- a/tools/edit_replace/bin/edit+++ b/tools/edit_replace/bin/edit@@ -54,7 +54,7 @@ def get_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser()parser.add_argument("search", type=str)parser.add_argument("replace", type=str)- parser.add_argument("--replace-all", action="store_true")+ parser.add_argument("replace_all", type=bool, nargs="?", default=False)return parserdiff --git a/tools/edit_replace/bin/insert b/tools/edit_replace/bin/insertnew file mode 100644index 00000000..d46e55f9--- /dev/null+++ b/tools/edit_replace/bin/insert@@ -0,0 +1,73 @@+#!/usr/bin/env python3++import argparse++from default_utils import FileNotOpened, WindowedFile # type: ignore+from flake8_utils import flake8, format_flake8_output # type: ignore++_SINGLE_EDIT_SUCCESS_MSG = """Text appended. Please review the changes and make sure they are correct+(correct indentation, no duplicate lines, etc). Edit the file again if necessary."""++_LINT_ERROR_TEMPLATE = """ Your proposed edit has introduced new syntax error(s). Please read this error message carefully and then retry editing the file.++ERRORS:++{errors}+This is how your edit would have looked if applied+------------------------------------------------+{window_applied}+------------------------------------------------++This is the original code before your edit+------------------------------------------------+{window_original}+------------------------------------------------++Your changes have NOT been applied. Please fix your edit command and try again.+DO NOT re-run the same failed edit command. Running it again will lead to the same error.+"""+++def get_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser()+ parser.add_argument("text", type=str)+ parser.add_argument("line", type=int, nargs="?", default=None)+ return parser+++def main(text: str, line: int | None = None):+ try:+ wf = WindowedFile(exit_on_exception=False)+ except FileNotOpened:+ print("No file opened. Use the `create` or `open` command first.")+ exit(1)++ pre_edit_lint = flake8(wf.path)+ insert_info = wf.insert(text, line=line - 1 if line is not None else None)+ post_edit_lint = flake8(wf.path)++ # Try to filter out pre-existing errors+ replacement_window = (insert_info.first_inserted_line, insert_info.first_inserted_line)+ new_flake8_output = format_flake8_output(+ post_edit_lint,+ previous_errors_string=pre_edit_lint,+ replacement_window=replacement_window,+ replacement_n_lines=insert_info.n_lines_added,+ )++ if new_flake8_output:+ with_edits = wf.get_window_text(line_numbers=True, status_line=True, pre_post_line=True)+ wf.undo_edit()+ without_edits = wf.get_window_text(line_numbers=True, status_line=True, pre_post_line=True)+ print(+ _LINT_ERROR_TEMPLATE.format(+ errors=new_flake8_output, window_applied=with_edits, window_original=without_edits+ )+ )+ exit(4)++ wf.print_window()+++if __name__ == "__main__":+ main(**vars(get_parser().parse_args()))diff --git a/tools/edit_replace/config.yaml b/tools/edit_replace/config.yamlindex ac2a29e9..72768f4b 100644--- a/tools/edit_replace/config.yaml+++ b/tools/edit_replace/config.yaml@@ -1,9 +1,10 @@tools:edit:signature: |- edit <search> <replace>+ edit <search> <replace> [<replace-all>]docstring: >- asdf asdf+ Replace first occurrence of <search> with <replace> in the currently displayed lines.+ If --replace-all is specified, replace all occurrences of <search> with <replace>.arguments:- name: searchtype: string@@ -12,4 +13,22 @@ tools:- name: replacetype: stringdescription: "the text to replace the search with"- required: true\ No newline at end of file+ required: true+ - name: replace-all+ type: boolean+ description: "replace all occurrences rather than the first occurrence within the displayed lines"+ required: false+ insert:+ signature: |+ insert <text> [--line <line>]+ docstring: >+ Insert <text> at the end of the currently opened file or after <line> if specified.+ arguments:+ - name: text+ type: string+ description: "the text to insert"+ required: true+ - name: line+ type: integer+ description: "the line number to insert the text as new lines after"+ required: false\ No newline at end of file