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]
Replace most default utils with python implementation
Kilian Lieret22e2cb6f7763
diff --git a/tests/tools/test_default_utils.py b/tests/tools/test_default_utils.pyindex 76587780..a52cee55 100644--- a/tests/tools/test_default_utils.py+++ b/tests/tools/test_default_utils.py@@ -4,9 +4,13 @@ from pathlib import Pathimport pytest+from sweagent import TOOLS_DIRfrom tests.utils import make_python_tool_importable-make_python_tool_importable("tools/defaults/lib/default_utils.py", "default_utils")+DEFAULT_TOOLS_DIR = TOOLS_DIR / "defaults"+DEFAULT_TOOLS_BIN = DEFAULT_TOOLS_DIR / "bin"++make_python_tool_importable(DEFAULT_TOOLS_DIR / "lib/default_utils.py", "default_utils")import default_utils # type: ignore@@ -19,54 +23,124 @@ def windowed_file(with_tmp_env_file):test_path = with_tmp_env_file.parent.joinpath("test.py")registry = {"CURRENT_FILE": str(test_path),- "CURRENT_LINE": "10",+ "FIRST_LINE": "10","WINDOW": "10",}with_tmp_env_file.write_text(json.dumps(registry))test_path.write_text("\n".join(map(str, range(100))))- return default_utils.WindowedFile()+ wf = default_utils.WindowedFile(exit_on_exception=False)+ wf.offset_multiplier = 1 / 4+ return wfdef test_windowed_file(windowed_file):wfile = windowed_file- assert wfile.current_line == 10+ assert wfile.first_line == 10assert wfile.window == 10assert wfile.n_lines == 100a, b = wfile.line_rangeassert b - a == wfile.window- assert wfile.line_range == (5, 15)+ assert wfile.line_range == (10, 20)wfile.print_window()wfile.replace_in_window("10", "Hello, world!")assert wfile.n_lines == 100assert wfile.line_range == (7, 17)- wfile.current_line = 50+ wfile.first_line = 50wfile.print_window()wfile.replace_in_window("50", "Hello, world!")wfile.print_window()# Line 50 is now the 2nd line of the new window- print(wfile.current_line)assert wfile.line_range == (47, 57)+ with pytest.raises(default_utils.TextNotFound):+ wfile.replace_in_window("asdf", "Hello, world!")def test_windowed_file_goto(windowed_file):wfile = windowed_file- assert wfile.current_line == 10+ assert wfile.first_line == 10wfile.goto(0, mode="top")assert wfile.line_range[0] == 0wfile.goto(50, mode="top")# first line is 50 - 10//4 = 47assert wfile.line_range[0] == 47- wfile.goto(50, mode="exact")- assert wfile.current_line == 50def test_windowed_file_scroll(windowed_file):wfile = windowed_file- assert wfile.current_line == 10+ assert wfile.first_line == 10wfile.scroll(10)- assert wfile.current_line == 20+ assert wfile.first_line == 20wfile.scroll(-10)- assert wfile.current_line == 10+ assert wfile.first_line == 10wfile.scroll(-100)# Can't go lower than the middle of the lowest window- assert wfile.current_line == 5+ assert wfile.first_line == 0+++# def test_goto_command(windowed_file):+# wfile = windowed_file+# assert wfile.current_line == 10+# assert (DEFAULT_TOOLS_BIN / "goto").exists()++# # Use sys.executable to get the correct Python interpreter+# import sys+# cmd = f"{sys.executable} {DEFAULT_TOOLS_BIN}/goto 50"+# print(+# subprocess.check_output(+# cmd,+# shell=True,+# universal_newlines=True,+# stderr=subprocess.STDOUT,+# env=os.environ.copy(), # Ensure we pass the current environment+# )+# )+# assert wfile.current_line == 50+++_DEFAULT_WINDOW_OUTPUT = """[File: {path} (100 lines total)]+(10 more lines above)+11:10+12:11+13:12+14:13+15:14+16:15+17:16+18:17+19:18+20:19+21:20+(79 more lines below)+"""+++def test_print_window(windowed_file, capsys):+ wfile = windowed_file+ wfile.print_window()+ captured = capsys.readouterr()+ print(captured.out)+ expected = _DEFAULT_WINDOW_OUTPUT.format(path=wfile.path.resolve())+ assert captured.out == expected+++_DEFAULT_WINDOW_OUTPUT_NEW_FILE = """[File: {path} (1 lines total)]+1:+"""+++def test_print_window_new_file(with_tmp_env_file, capsys):+ test_path = with_tmp_env_file.parent.joinpath("new_test.py")+ registry = {+ "CURRENT_FILE": str(test_path),+ "FIRST_LINE": "10",+ "WINDOW": "10",+ }+ with_tmp_env_file.write_text(json.dumps(registry))+ new_file = with_tmp_env_file.parent.joinpath(registry["CURRENT_FILE"])+ new_file.write_text("\n")+ wfile = default_utils.WindowedFile()+ wfile.print_window()+ captured = capsys.readouterr()+ print(captured.out)+ expected = _DEFAULT_WINDOW_OUTPUT_NEW_FILE.format(path=new_file.resolve())+ assert captured.out == expecteddiff --git a/tools/defaults/bin/create b/tools/defaults/bin/createindex 9a4f7b2e..894977bc 100644--- a/tools/defaults/bin/create+++ b/tools/defaults/bin/create@@ -1,24 +1,27 @@-#!/usr/bin/env bash-set -euo pipefail--main() {- local filename="${1:-}"- if [ -z "${filename}" ]; then- echo "Usage: create <filename>"- exit 1- fi-- # Check if the file already exists- if [ -e "${filename}" ]; then- echo "Error: File '${filename}' already exists."- open "${filename}" || exit 1- exit 1- fi-- # Create the file an empty new line- printf "\n" > "${filename}"- # Use the existing open command to open the created file- open "${filename}" || exit 1-}--main "$@"+#!/usr/bin/env python3+import sys+from pathlib import Path++from default_utils import WindowedFile # type: ignore+++def main():+ if len(sys.argv) < 2:+ print("Usage: create <filename>")+ sys.exit(1)++ path = Path(sys.argv[1])++ if path.exists():+ print(f"Warning: File '{path}' already exists.")+ sys.exit(1)++ path.write_text("\n")++ wfile = WindowedFile(path=path)+ wfile.current_line = 0+ wfile.print_window()+++if __name__ == "__main__":+ main()diff --git a/tools/defaults/bin/goto b/tools/defaults/bin/gotoindex 6d84a929..2c1c7d3f 100644--- a/tools/defaults/bin/goto+++ b/tools/defaults/bin/goto@@ -1,43 +1,36 @@-#!/usr/bin/env bash-set -euo pipefail-source /root/tools/defaults/lib/utils.sh--main() {- local CURRENT_FILE=$(_read_env CURRENT_FILE)- local WINDOW=$(_read_env WINDOW)-- if [ $# -gt 1 ]; then- echo "goto allows only one line number at a time."- exit 1- fi- if [ -z "$CURRENT_FILE" ]- then- echo "No file open. Use the open command first."- exit 1- fi- if [ -z "$1" ]- then- echo "Usage: goto <line>"- exit 1- fi- if ! [[ $1 =~ ^[0-9]+$ ]]- then- echo "Usage: goto <line>"- echo "Error: <line> must be a number"- exit 1- fi- local max_line=$(awk 'END {print NR}' "$CURRENT_FILE")- if [ $1 -gt $max_line ]- then- echo "Error: <line> must be less than or equal to $max_line"- exit 1- fi- local OFFSET=$((WINDOW / 6))- local line_number=$(( $1 + WINDOW / 2 - OFFSET ))- line_number=$(( line_number > 1 ? line_number : 1 )) # Ensure line_number is at least 1- _write_env CURRENT_LINE $line_number || exit 1- _constrain_line || exit 1- _print || exit 1-}--main "$@"\ No newline at end of file+#!/usr/bin/env python3+import sys++from default_utils import WindowedFile # type: ignore+++def main(args: list[str]) -> int:+ if len(args) > 1:+ print("goto allows only one line number at a time.")+ return 1++ if not args:+ print("Usage: goto <line>")+ return 1++ try:+ line_number = int(args[0])+ except ValueError:+ print("Usage: goto <line>")+ print("Error: <line> must be a number")+ return 1++ wf = WindowedFile()++ if line_number > wf.n_lines:+ print(f"Error: <line> must be less than or equal to {wf.n_lines}")+ return 1++ # Convert from 1-based line numbers (user input) to 0-based (internal representation)+ wf.goto(line_number - 1, mode="top")+ wf.print_window()+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tools/defaults/bin/open b/tools/defaults/bin/openindex 500b4b32..8585242e 100644--- a/tools/defaults/bin/open+++ b/tools/defaults/bin/open@@ -1,52 +1,51 @@-#!/usr/bin/env bash-set -euo pipefail-source /root/tools/defaults/lib/utils.sh--main() {- local WINDOW=$(_read_env WINDOW)-- if [ $# -eq 0 ]; then- echo "Usage: open \"<file>\""- exit 1- fi- if [ -d "$1" ]; then- echo "Error: $1 is a directory. You can only open files. Use cd or ls to navigate directories."- exit 1- elif [ ! -f "$1" ]; then- echo "File $1 not found"- exit 1- fi-- # Check if the second argument is provided- if [ $# -ge 2 ]; then- # Check if the provided argument is a valid number- if ! [[ $2 =~ ^[0-9]+$ ]]; then- echo "Usage: open \"<file>\" [<line_number>]"- echo "Error: <line_number> must be a number"- exit 1- fi- local max_line=$(awk 'END {print NR}' "$1")- if [ $2 -gt $max_line ]; then- echo "Warning: <line_number> ($2) is greater than the number of lines in the file ($max_line)"- echo "Warning: Setting <line_number> to $max_line"- local line_number=$max_line # Set line number to max if greater than max- elif [ $2 -lt 1 ]; then- echo "Warning: <line_number> ($2) is less than 1"- echo "Warning: Setting <line_number> to 1"- local line_number=1 # Set line number to 1 if less than 1- else- local OFFSET=$((WINDOW / 6))- local line_number=$(( $2 + WINDOW / 2 - OFFSET ))- line_number=$(( line_number > 1 ? line_number : 1 )) # Ensure line_number is at least 1- fi- else- local line_number=$((WINDOW / 2)) # Set default line number if not provided- fi-- _write_env CURRENT_FILE $(realpath "$1") || exit 1- _write_env CURRENT_LINE $line_number || exit 1- _constrain_line || exit 1- _print || exit 1-}--main "$@"+#!/usr/bin/env python3+import sys+from pathlib import Path+from typing import Optional++from default_utils import FileNotOpened, WindowedFile # type: ignore+++def main(path: Optional[str] = None, line_number: Optional[str] = None) -> None:+ if path is None:+ try:+ WindowedFile(exit_on_exception=False).print_window()+ # If this passes, then there was already a file open and we just show it again+ sys.exit(0)+ except FileNotOpened:+ print('Usage: open "<file>"')+ sys.exit(1)++ assert path is not None++ wf = WindowedFile(path=path)++ if line_number is not None:+ try:+ line_num = int(line_number)+ except ValueError:+ print('Usage: open "<file>" [<line_number>]')+ print("Error: <line_number> must be a number")+ sys.exit(1)+ if line_num > wf.n_lines:+ print(f"Warning: <line_number> ({line_num}) is greater than the number of lines in the file ({wf.n_lines})")+ print(f"Warning: Setting <line_number> to {wf.n_lines}")+ line_num = wf.n_lines+ elif line_num < 1:+ print(f"Warning: <line_number> ({line_num}) is less than 1")+ print("Warning: Setting <line_number> to 1")+ line_num = 1++ else:+ # Default to middle of window if no line number provided+ line_num = wf.window // 2++ wf.current_line = line_num - 1+ wf.print_window()+++if __name__ == "__main__":+ args = sys.argv[1:]+ file_path = args[0] if args else None+ line_number = args[1] if len(args) > 1 else None+ main(file_path, line_number)diff --git a/tools/defaults/bin/scroll_down b/tools/defaults/bin/scroll_downindex 52be8bec..cd9e44f3 100644--- a/tools/defaults/bin/scroll_down+++ b/tools/defaults/bin/scroll_down@@ -1,22 +1,12 @@-#!/usr/bin/env bash-set -euo pipefail-source /root/tools/defaults/lib/utils.sh+#!/usr/bin/env python3-main() {- local CURRENT_FILE=$(_read_env CURRENT_FILE)- local CURRENT_LINE=$(_read_env CURRENT_LINE)- local WINDOW=$(_read_env WINDOW)- local OVERLAP=$(_read_env OVERLAP)+from default_utils import WindowedFile # type: ignore- if [ -z "$CURRENT_FILE" ]- then- echo "No file open. Use the open command first."- exit 1- fi- _write_env CURRENT_LINE $((CURRENT_LINE + WINDOW - OVERLAP)) || exit 1- _constrain_line || exit 1- _print || exit 1- _scroll_warning_message || exit 1-}-main "$@"+def main():+ wf = WindowedFile()+ wf.scroll(wf.window)+ wf.print_window()++if __name__ == "__main__":+ main()diff --git a/tools/defaults/bin/scroll_up b/tools/defaults/bin/scroll_upindex 5c6efafb..9a632317 100644--- a/tools/defaults/bin/scroll_up+++ b/tools/defaults/bin/scroll_up@@ -1,22 +1,13 @@-#!/usr/bin/env bash-set -euo pipefail-source /root/tools/defaults/lib/utils.sh+#!/usr/bin/env python3-main() {- local CURRENT_FILE=$(_read_env CURRENT_FILE)- local CURRENT_LINE=$(_read_env CURRENT_LINE)- local WINDOW=$(_read_env WINDOW)- local OVERLAP=$(_read_env OVERLAP)+from default_utils import WindowedFile # type: ignore- if [ -z "$CURRENT_FILE" ]- then- echo "No file open. Use the open command first."- exit 1- fi- _write_env CURRENT_LINE $((CURRENT_LINE - WINDOW + OVERLAP)) || exit 1- _constrain_line || exit 1- _print || exit 1- _scroll_warning_message || exit 1-}-main "$@"+def main():+ wf = WindowedFile()+ wf.scroll(-wf.window)+ wf.print_window()+++if __name__ == "__main__":+ main()diff --git a/tools/defaults/install.sh b/tools/defaults/install.shindex b03d2258..bed25702 100644--- a/tools/defaults/install.sh+++ b/tools/defaults/install.sh@@ -10,7 +10,7 @@ export PYTHONPATH="$bundle_dir/lib"# Write default environment variables into the environment storage_write_env "WINDOW" "${WINDOW:-100}"_write_env "OVERLAP" "${OVERLAP:-2}"-_write_env "CURRENT_LINE" "${CURRENT_LINE:-0}"+_write_env "FIRST_LINE" "${FIRST_LINE:-0}"_write_env "CURRENT_FILE" "${CURRENT_FILE:-}"# install jqdiff --git a/tools/defaults/lib/default_utils.py b/tools/defaults/lib/default_utils.pyindex e6f61827..54ed1a7a 100644--- a/tools/defaults/lib/default_utils.py+++ b/tools/defaults/lib/default_utils.py@@ -47,33 +47,66 @@ class TextNotFound(Exception):class WindowedFile:- def __init__(self, path: Path | None = None, *, current_line: int | None = None, window: int | None = None):+ def __init__(+ self,+ path: Path | None = None,+ *,+ first_line: int | None = None,+ window: int | None = None,+ exit_on_exception: bool = True,+ ):"""- Convention: All line numbers are 0-indexed.+ Args:+ exit_on_exception: If False, will raise exception.+ If true, will print an error message and exit.++ Will create file if not found.++ Internal convention: All line numbers are 0-indexed."""_path = registry.get_if_none(path, "CURRENT_FILE")+ self._exit_on_exception = exit_on_exceptionif _path is None:+ if self._exit_on_exception:+ print("No file open. Use the open command first.")+ exit(1)raise FileNotOpenedself.path = Path(_path)+ if self.path.is_dir():+ msg = f"Error: {self.path} is a directory. You can only open files. Use cd or ls to navigate directories."+ if self._exit_on_exception:+ print(msg)+ exit(1)+ raise IsADirectoryError(msg)+ if not self.path.exists():+ msg = f"File {self.path} not found"+ if self._exit_on_exception:+ print(msg)+ exit(1)+ raise FileNotFoundError(msg)+ registry["CURRENT_FILE"] = str(self.path.resolve())self.window = int(registry.get_if_none(window, "WINDOW"))- self._current_line = 0+ self.overlap = int(registry.get("OVERLAP", 0))# Ensure that we get a valid current line by using the setter- self.current_line = int(+ self.first_line = int(registry.get_if_none(- current_line,- "CURRENT_LINE",+ first_line,+ "FIRST_LINE",+ 0,))+ self.offset_multiplier = 1 / 6@property- def current_line(self) -> int:- return self._current_line+ def first_line(self) -> int:+ return self._first_line- @current_line.setter- def current_line(self, value: int):- self._current_line = min(max(value, self.window // 2), self.n_lines - 1 - self.window // 2)- registry["CURRENT_LINE"] = self.current_line+ @first_line.setter+ def first_line(self, value: int | float):+ value = int(value)+ self._first_line = max(0, min(value, self.n_lines - 1 - self.window))+ registry["FIRST_LINE"] = self.first_line@propertydef text(self) -> str:@@ -89,16 +122,18 @@ class WindowedFile:@propertydef line_range(self) -> tuple[int, int]:- return (- max(0, self.current_line - self.window // 2),- min(self.current_line + (self.window - self.window // 2), self.n_lines),- )+ """Return current line +/- window/2.+ `line_range[1] - line_range[0] == window` as long as there are+ at least `window` lines in the file. `first_line` does the handling+ of making sure that we don't go out of bounds.+ """+ return self.first_line, self.first_line + self.windowdef get_window_text(self) -> str:start_line, end_line = self.line_rangereturn "\n".join(self.text.splitlines()[start_line:end_line])- def set_window_text(self, new_text: str):+ def set_window_text(self, new_text: str) -> None:"""Set window text."""text = self.text.splitlines()start, stop = self.line_range@@ -110,22 +145,26 @@ class WindowedFile:search: str,replace: str,*,- reset_current_line: Literal["move_top", "keep"] = "move_top",+ reset_first_line: Literal["top", "keep"] = "top",n_replacements=1,- ):+ ) -> None:"""Search and replace in the window.Args:search: The string to search for (can be multi-line).replace: The string to replace it with (can be multi-line).- reset_current_line: If set to "move_top", we set the current line to the 25%*window_size-th line of the new window.- If set to "keep", we keep the current line.+ reset_first_line: If set to "keep", we keep the current line. Otherwise+ we `goto` the line where the replacement started with goto mode equal+ to this setting.n_replacements: The number of replacements to make."""window_text = self.get_window_text()# Update line numberindex = window_text.find(search)if index == -1:+ if self._exit_on_exception:+ print(f"Text not found: {search}")+ exit(1)raise TextNotFound# This line should now be the `25%*window_size`-th line of the new windowwindow_start_line, _ = self.line_range@@ -133,20 +172,30 @@ class WindowedFile:print("rsl", replace_start_line)new_window_text = window_text.replace(search, replace, n_replacements)self.set_window_text(new_window_text)- if reset_current_line == "keep":+ if reset_first_line == "keep":+ pass+ else:+ self.goto(replace_start_line, mode=reset_first_line)++ def replace(self, search: str, replace: str, *, reset_first_line: Literal["top", "keep"] = "top"):+ index = self.text.find(search)+ if index == -1:+ if self._exit_on_exception:+ print(f"Text not found: {search}")+ exit(1)+ raise TextNotFound+ replace_start_line = self.text[:index].count("\n")+ new_text = self.text.replace(search, replace)+ self.text = new_text+ if reset_first_line == "keep":pass- elif reset_current_line == "move_top":- # wstart = rstart - w//4- # wend = wstart + w- # c = (wend + wstart)//2 = (wstart + w + rstart - w//4)//2 = (rstart - w//4 + w + rstart - w//4)//2 = rstart + w//4- self.current_line = replace_start_line + self.window // 4else:- msg = f"Invalid value for reset_current_line: {reset_current_line}"- raise ValueError(msg)+ self.goto(replace_start_line, mode=reset_first_line)def print_window(self):- lines = self.path.read_text().splitlines()+ lines = self.text.splitlines()start_line, end_line = self.line_range+ assert start_line >= 0, start_lineprint(f"[File: {self.path} ({len(lines)} lines total)]")if start_line > 0:print(f"({start_line} more lines above)")@@ -155,14 +204,14 @@ class WindowedFile:if end_line < len(lines) - 1:print(f"({len(lines) - end_line - 1} more lines below)")- def goto(self, line: int, mode: Literal["top", "exact"] = "top"):- if mode == "exact":- self.current_line = line- elif mode == "top":- # line is gonna be the 25%*window_size-th line of the new window- self.current_line = line + self.window // 4+ def goto(self, line: int, mode: Literal["top"] = "top"):+ if mode == "top":+ self.first_line = line - self.window * self.offset_multiplierelse:raise NotImplementedErrordef scroll(self, n_lines: int):- self.current_line += n_lines+ if n_lines > 0:+ self.first_line += n_lines - self.overlap+ elif n_lines < 0:+ self.first_line += n_lines + self.overlapdiff --git a/tools/edit_replace/bin/edit b/tools/edit_replace/bin/editindex 229b347a..dd13f12a 100644--- a/tools/edit_replace/bin/edit+++ b/tools/edit_replace/bin/edit@@ -2,7 +2,7 @@import argparse-from default_utils import FileNotOpened, WindowedFile # type: ignore+from default_utils import FileNotOpened, TextNotFound, WindowedFile # type: ignoreparser = argparse.ArgumentParser()parser.add_argument("search", type=str)@@ -11,27 +11,34 @@ parser.add_argument("--replace-all", action="store_true")args = parser.parse_args()+_NOT_FOUND_IN_WINDOW_MSG = f"""Text {args.search!r} not found in displayed lines.+Note: By default, we only replace the first occurrence in the lines that are currently visible in the editor.+If you want to replace all occurrences in and outside of the visible lines, use the `--replace-all` flag.+"""++_NO_CHANGES_MADE_MSG = """Your search and replace strings are the same. No changes were made."""+try:- current_file = WindowedFile()+ wf = WindowedFile(exit_on_exception=False)except FileNotOpened:print("No file opened. Either `open` a file first.")exit(1)# Turn \\n into \n etc., i.e., undo the escaping-args.replace = args.replace.encode("utf8").decode("unicode_escape")+# args.replace = args.replace.encode("utf8").decode("unicode_escape")++if args.search == args.replace:+ print(_NO_CHANGES_MADE_MSG)+ exit(2)+if not args.replace_all:- text_in_window = current_file.get_window_text()- new_text_in_window = text_in_window.replace(args.search, args.replace, 1)- if text_in_window == new_text_in_window:- print(- "No changes made. Please make sure that your search and replace strings are correct. "- "Note: By default, we only replace the first occurrence in the lines that are currently visible in the editor. "- "If you want to replace all occurrences, use the `--replace-all` flag."- )- exit(0)- current_file.set_window_text(new_text_in_window)+ try:+ wf.replace_in_window(args.search, args.replace, n_replacements=1)+ except TextNotFound:+ print(_NOT_FOUND_IN_WINDOW_MSG)+ exit(3)else:- new_text = current_file.text.replace(args.search, args.replace)- current_file.text = new_text+ # todo: Give overview of all replaced occurrences+ wf.replace(args.search, args.replace)-current_file.print_window()+wf.print_window()