Skip to content

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 windowed things in WindowedFile

Kilian Lieret42b6ef68c43a
diff --git a/tests/tools/test_default_utils.py b/tests/tools/test_default_utils.py
index 3c4b1f32..76587780 100644
--- a/tests/tools/test_default_utils.py
+++ b/tests/tools/test_default_utils.py
@@ -2,21 +2,20 @@ import json
import os
from pathlib import Path
+import pytest
+
from tests.utils import make_python_tool_importable
make_python_tool_importable("tools/defaults/lib/default_utils.py", "default_utils")
import default_utils # type: ignore
-from default_utils import ( # type: ignore
- get_current_file_with_line_range,
-)
def test_env_file_override(with_tmp_env_file):
assert Path(os.getenv("SWE_AGENT_ENV_FILE")).name == ".swe-agent-env" # type: ignore
-def test_get_current_file_with_line_range(with_tmp_env_file):
- default_utils.SWE_AGENT_ENV_FILE = with_tmp_env_file # type: ignore
+def windowed_file(with_tmp_env_file):
test_path = with_tmp_env_file.parent.joinpath("test.py")
registry = {
"CURRENT_FILE": str(test_path),
@@ -24,9 +23,50 @@ def test_get_current_file_with_line_range(with_tmp_env_file):
"WINDOW": "10",
}
with_tmp_env_file.write_text(json.dumps(registry))
- test_path.write_text("\n".join(map(str, range(20))))
- file_path, start_line, end_line = get_current_file_with_line_range()
- print(file_path, start_line, end_line)
- assert file_path == test_path
- assert start_line == 4
- assert end_line == 14
+ test_path.write_text("\n".join(map(str, range(100))))
+ return default_utils.WindowedFile()
+
+
+def test_windowed_file(windowed_file):
+ wfile = windowed_file
+ assert wfile.current_line == 10
+ assert wfile.window == 10
+ assert wfile.n_lines == 100
+ a, b = wfile.line_range
+ assert b - a == wfile.window
+ assert wfile.line_range == (5, 15)
+ wfile.print_window()
+ wfile.replace_in_window("10", "Hello, world!")
+ assert wfile.n_lines == 100
+ assert wfile.line_range == (7, 17)
+ wfile.current_line = 50
+ wfile.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)
+
+
+def test_windowed_file_goto(windowed_file):
+ wfile = windowed_file
+ assert wfile.current_line == 10
+ wfile.goto(0, mode="top")
+ assert wfile.line_range[0] == 0
+ wfile.goto(50, mode="top")
+ # first line is 50 - 10//4 = 47
+ assert wfile.line_range[0] == 47
+ wfile.goto(50, mode="exact")
+ assert wfile.current_line == 50
+
+
+def test_windowed_file_scroll(windowed_file):
+ wfile = windowed_file
+ assert wfile.current_line == 10
+ wfile.scroll(10)
+ assert wfile.current_line == 20
+ wfile.scroll(-10)
+ assert wfile.current_line == 10
+ wfile.scroll(-100)
+ # Can't go lower than the middle of the lowest window
+ assert wfile.current_line == 5
diff --git a/tools/defaults/lib/default_utils.py b/tools/defaults/lib/default_utils.py
index ab5823d6..e6f61827 100644
--- a/tools/defaults/lib/default_utils.py
+++ b/tools/defaults/lib/default_utils.py
@@ -1,7 +1,7 @@
import json
import os
-from pathlib import Path, PurePath
-from typing import Any
+from pathlib import Path
+from typing import Any, Literal
class EnvRegistry:
@@ -24,6 +24,11 @@ class EnvRegistry:
def get(self, key: str, default_value: Any = None) -> Any:
return json.loads(self.env_file.read_text()).get(key, default_value)
+ def get_if_none(self, value: Any, key: str, default_value: Any = None) -> Any:
+ if value is not None:
+ return value
+ return self.get(key, default_value)
+
def __setitem__(self, key: str, value: Any):
env = json.loads(self.env_file.read_text())
env[key] = value
@@ -33,45 +38,131 @@ class EnvRegistry:
registry = EnvRegistry()
-def get_current_file():
- return Path(registry["CURRENT_FILE"]) # type: ignore
-
-
-def get_current_line():
- return int(registry["CURRENT_LINE"]) # type: ignore
-
-
-def get_current_file_with_line_range(file_path: str | PurePath | None = None) -> tuple[Path, int, int]:
- """Returns 0-based index of the first and last line to print."""
- if file_path is None:
- _spec = registry["CURRENT_FILE"]
- assert _spec, "CURRENT_FILE is not set"
- file_path = Path(_spec)
- else:
- file_path = Path(file_path)
- current_line = int(registry["CURRENT_LINE"]) # type: ignore
- window = int(registry["WINDOW"]) # type: ignore
- n_lines = file_path.read_text().count("\n") + 1
- return (
- file_path,
- max(0, current_line - 1 - window // 2),
- min(current_line - 1 + window // 2, n_lines - 1),
- )
-
-
-def print_window(file_path: str | PurePath | None = None, start_line: int | None = None, end_line: int | None = None):
- """
-
- Args:
- start_line: 0-indexed line number
- end_line: 0-indexed line number (inclusive)
- """
- file_path, start_line, end_line = get_current_file_with_line_range(file_path)
- lines = Path(file_path).read_text().splitlines()
- print(f"[File: {file_path} ({len(lines)} lines total)]")
- if start_line > 0:
- print(f"({start_line} more lines above)")
- for i, line in enumerate(lines[start_line : end_line + 1]):
- print(f"{i+1}:{line}")
- if end_line < len(lines) - 1:
- print(f"({len(lines) - end_line - 1} more lines below)")
+class FileNotOpened(Exception):
+ """Raised when no file is opened."""
+
+
+class TextNotFound(Exception):
+ """Raised when the text is not found in the window."""
+
+
+class WindowedFile:
+ def __init__(self, path: Path | None = None, *, current_line: int | None = None, window: int | None = None):
+ """
+
+ Convention: All line numbers are 0-indexed.
+ """
+ _path = registry.get_if_none(path, "CURRENT_FILE")
+ if _path is None:
+ raise FileNotOpened
+ self.path = Path(_path)
+ self.window = int(registry.get_if_none(window, "WINDOW"))
+ self._current_line = 0
+ # Ensure that we get a valid current line by using the setter
+ self.current_line = int(
+ registry.get_if_none(
+ current_line,
+ "CURRENT_LINE",
+ )
+ )
+
+ @property
+ def current_line(self) -> int:
+ return self._current_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
+
+ @property
+ def text(self) -> str:
+ return self.path.read_text()
+
+ @text.setter
+ def text(self, new_text: str):
+ self.path.write_text(new_text)
+
+ @property
+ def n_lines(self) -> int:
+ return self.text.count("\n") + 1
+
+ @property
+ def 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),
+ )
+
+ def get_window_text(self) -> str:
+ start_line, end_line = self.line_range
+ return "\n".join(self.text.splitlines()[start_line:end_line])
+
+ def set_window_text(self, new_text: str):
+ """Set window text."""
+ text = self.text.splitlines()
+ start, stop = self.line_range
+ text[start:stop] = new_text.splitlines()
+ self.text = "\n".join(text)
+
+ def replace_in_window(
+ self,
+ search: str,
+ replace: str,
+ *,
+ reset_current_line: Literal["move_top", "keep"] = "move_top",
+ n_replacements=1,
+ ):
+ """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.
+ n_replacements: The number of replacements to make.
+ """
+ window_text = self.get_window_text()
+ # Update line number
+ index = window_text.find(search)
+ if index == -1:
+ raise TextNotFound
+ # This line should now be the `25%*window_size`-th line of the new window
+ window_start_line, _ = self.line_range
+ replace_start_line = window_start_line + window_text[:index].count("\n")
+ 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":
+ 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 // 4
+ else:
+ msg = f"Invalid value for reset_current_line: {reset_current_line}"
+ raise ValueError(msg)
+
+ def print_window(self):
+ lines = self.path.read_text().splitlines()
+ start_line, end_line = self.line_range
+ print(f"[File: {self.path} ({len(lines)} lines total)]")
+ if start_line > 0:
+ print(f"({start_line} more lines above)")
+ for i, line in enumerate(lines[start_line : end_line + 1]):
+ print(f"{i+start_line+1}:{line}")
+ 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
+ else:
+ raise NotImplementedError
+
+ def scroll(self, n_lines: int):
+ self.current_line += n_lines
diff --git a/tools/edit_replace/bin/edit b/tools/edit_replace/bin/edit
index 44e12908..229b347a 100644
--- a/tools/edit_replace/bin/edit
+++ b/tools/edit_replace/bin/edit
@@ -1,33 +1,26 @@
#!/usr/bin/env python3
import argparse
-from pathlib import Path
-from default_utils import get_current_file, get_current_file_with_line_range, print_window # type: ignore
-
-current_file = get_current_file()
+from default_utils import FileNotOpened, WindowedFile # type: ignore
parser = argparse.ArgumentParser()
parser.add_argument("search", type=str)
parser.add_argument("replace", type=str)
-parser.add_argument("-f", "--file", type=Path, default=Path(current_file))
parser.add_argument("--replace-all", action="store_true")
args = parser.parse_args()
-# Turn \\n into \n etc., i.e., undo the escaping
-args.replace = args.replace.encode("utf8").decode("unicode_escape")
-if not args.file:
- print("No file specified. Either `open` a file first or specify a file with `-f`.")
+try:
+ current_file = WindowedFile()
+except FileNotOpened:
+ print("No file opened. Either `open` a file first.")
exit(1)
-
-text = args.file.read_text()
-lines = text.splitlines()
-_, first_window_line, last_window_line = get_current_file_with_line_range(args.file)
-
+# Turn \\n into \n etc., i.e., undo the escaping
+args.replace = args.replace.encode("utf8").decode("unicode_escape")
if not args.replace_all:
- text_in_window = "\n".join(lines[first_window_line : last_window_line + 1])
+ 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(
@@ -36,12 +29,9 @@ if not args.replace_all:
"If you want to replace all occurrences, use the `--replace-all` flag."
)
exit(0)
- new_text = "\n".join(lines[:first_window_line] + [new_text_in_window] + lines[last_window_line + 1 :])
+ current_file.set_window_text(new_text_in_window)
else:
- new_text = text.replace(args.search, args.replace)
-
-args.file.write_text(new_text)
+ new_text = current_file.text.replace(args.search, args.replace)
+ current_file.text = new_text
-# Recompute the current window, since we might have more/less lines now
-_, first_window_line, last_window_line = get_current_file_with_line_range(args.file)
-print_window(args.file, first_window_line, last_window_line)
+current_file.print_window()