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]

WIP on adding flake8 linting to search/replace

Kilian Lieretdbba0a1766db
diff --git a/tests/tools/test_default_utils.py b/tests/tools/test_default_utils.py
index a52cee55..bdf06914 100644
--- a/tests/tools/test_default_utils.py
+++ b/tests/tools/test_default_utils.py
@@ -139,6 +139,8 @@ def test_print_window_new_file(with_tmp_env_file, capsys):
new_file = with_tmp_env_file.parent.joinpath(registry["CURRENT_FILE"])
new_file.write_text("\n")
wfile = default_utils.WindowedFile()
+ assert wfile.n_lines == 1
+ assert wfile.line_range == (0, 0)
wfile.print_window()
captured = capsys.readouterr()
print(captured.out)
diff --git a/tools/defaults/lib/default_utils.py b/tools/defaults/lib/default_utils.py
index 54ed1a7a..9579964e 100644
--- a/tools/defaults/lib/default_utils.py
+++ b/tools/defaults/lib/default_utils.py
@@ -1,5 +1,7 @@
import json
import os
+from collections.abc import Generator
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal
@@ -46,6 +48,31 @@ class TextNotFound(Exception):
"""Raised when the text is not found in the window."""
+def _find_all(a_str: str, sub: str) -> Generator[int, None, None]:
+ start = 0
+ while True:
+ start = a_str.find(sub, start)
+ if start == -1:
+ return
+ yield start
+ start += len(sub)
+
+
+@dataclass
+class ReplacementInfo:
+ first_replaced_line: int
+ """Line number of the beginning of the first search hit."""
+
+ n_search_lines: int
+ """Number of lines of search string"""
+
+ n_replace_lines: int
+ """Number of lines of replace string"""
+
+ n_replacements: int
+ """Number of replacements made."""
+
+
class WindowedFile:
def __init__(
self,
@@ -97,6 +124,7 @@ class WindowedFile:
)
)
self.offset_multiplier = 1 / 6
+ self._original_text = self.text
@property
def first_line(self) -> int:
@@ -114,30 +142,47 @@ class WindowedFile:
@text.setter
def text(self, new_text: str):
+ self._original_text = self.text
self.path.write_text(new_text)
@property
def n_lines(self) -> int:
- return self.text.count("\n") + 1
+ return len(self.text.splitlines())
@property
def line_range(self) -> tuple[int, int]:
- """Return current line +/- window/2.
+ """Return first and last line (inclusive) of the window.
`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.window
+ return self.first_line, min(self.first_line + self.window, self.n_lines - 1)
- def get_window_text(self) -> str:
+ def get_window_text(
+ self, *, line_numbers: bool = False, status_line: bool = False, pre_post_line: bool = False
+ ) -> str:
start_line, end_line = self.line_range
- return "\n".join(self.text.splitlines()[start_line:end_line])
+ lines = self.text.splitlines()[start_line : end_line + 1]
+ out_lines = []
+ if status_line:
+ out_lines.append(f"[File: {self.path} ({self.n_lines} lines total)]")
+ if pre_post_line:
+ if start_line > 0:
+ out_lines.append(f"({start_line} more lines above)")
+ if line_numbers:
+ out_lines.extend(f"{i+start_line+1}:{line}" for i, line in enumerate(lines))
+ else:
+ out_lines.extend(lines)
+ if pre_post_line:
+ if end_line < self.n_lines - 1:
+ out_lines.append(f"({self.n_lines - end_line - 1} more lines below)")
+ return "\n".join(out_lines)
def set_window_text(self, new_text: str) -> None:
"""Set window text."""
text = self.text.splitlines()
start, stop = self.line_range
- text[start:stop] = new_text.splitlines()
+ text[start : stop + 1] = new_text.splitlines()
self.text = "\n".join(text)
def replace_in_window(
@@ -146,17 +191,14 @@ class WindowedFile:
replace: str,
*,
reset_first_line: Literal["top", "keep"] = "top",
- n_replacements=1,
- ) -> None:
+ ) -> ReplacementInfo:
"""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_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.
+ reset_first_line: If "keep", we keep the current line. Otherwise, we
+ `goto` the line where the replacement started with this mode.
"""
window_text = self.get_window_text()
# Update line number
@@ -166,43 +208,46 @@ class WindowedFile:
print(f"Text not found: {search}")
exit(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)
+ replace_start_line = window_start_line + len(window_text[:index].splitlines())
+ new_window_text = window_text.replace(search, replace, 1)
self.set_window_text(new_window_text)
if reset_first_line == "keep":
pass
else:
self.goto(replace_start_line, mode=reset_first_line)
+ return ReplacementInfo(
+ first_replaced_line=replace_start_line,
+ n_search_lines=len(search.splitlines()) + 1,
+ n_replace_lines=len(replace.splitlines()) + 1,
+ n_replacements=1,
+ )
- def replace(self, search: str, replace: str, *, reset_first_line: Literal["top", "keep"] = "top"):
- index = self.text.find(search)
- if index == -1:
+ def replace(
+ self, search: str, replace: str, *, reset_first_line: Literal["top", "keep"] = "top"
+ ) -> ReplacementInfo:
+ indices = list(_find_all(self.text, search))
+ if not indices:
if self._exit_on_exception:
print(f"Text not found: {search}")
exit(1)
raise TextNotFound
- replace_start_line = self.text[:index].count("\n")
+ replace_start_line = len(self.text[: indices[0]].splitlines())
new_text = self.text.replace(search, replace)
self.text = new_text
if reset_first_line == "keep":
pass
else:
self.goto(replace_start_line, mode=reset_first_line)
+ return ReplacementInfo(
+ first_replaced_line=replace_start_line,
+ n_search_lines=len(search.splitlines()) + 1,
+ n_replace_lines=len(replace.splitlines()) + 1,
+ n_replacements=len(indices),
+ )
- def print_window(self):
- lines = self.text.splitlines()
- start_line, end_line = self.line_range
- assert start_line >= 0, start_line
- 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 print_window(self, *, line_numbers: bool = True, status_line: bool = True, pre_post_line: bool = True):
+ print(self.get_window_text(line_numbers=line_numbers, status_line=status_line, pre_post_line=pre_post_line))
def goto(self, line: int, mode: Literal["top"] = "top"):
if mode == "top":
@@ -215,3 +260,6 @@ class WindowedFile:
self.first_line += n_lines - self.overlap
elif n_lines < 0:
self.first_line += n_lines + self.overlap
+
+ def undo_edit(self):
+ self.text = self._original_text
diff --git a/tools/edit_replace/bin/_split_string b/tools/defaults/lib/flake8_utils.py
similarity index 78%
rename from tools/edit_replace/bin/_split_string
rename to tools/defaults/lib/flake8_utils.py
index b4a4a780..20b30478 100644
--- a/tools/edit_replace/bin/_split_string
+++ b/tools/defaults/lib/flake8_utils.py
@@ -1,25 +1,16 @@
#!/usr/bin/env python3
-"""This helper command is used to print flake8 output
-
-Usage:
- python _split_string.py <flake8_output>
- python _split_string.py <flake8_output> <previous_errors> <edit_window_start> <edit_window_end> <n_lines>
-
-Where:
- <flake8_output> is the output of flake8
- <previous_errors> is the previous errors as a string
- <edit_window_start> is the start of the edit window
- <edit_window_end> is the end of the edit window
- <n_lines> is the number of lines added in the edit
-"""
+"""This helper command is used to print flake8 output"""
# ruff: noqa: UP007 UP006 UP035
-import sys
+import subprocess
from dataclasses import dataclass
+from pathlib import Path
from typing import List, Optional, Tuple
+from default_utils import registry
+
@dataclass
class Flake8Error:
@@ -112,17 +103,9 @@ def format_flake8_output(
return "\n".join(lines)
-if __name__ == "__main__":
- if len(sys.argv) == 2:
- print(format_flake8_output(sys.argv[1]))
- elif len(sys.argv) == 6:
- window = (int(sys.argv[3]), int(sys.argv[4]))
- n_lines = int(sys.argv[5])
- print(
- format_flake8_output(
- sys.argv[1], previous_errors_string=sys.argv[2], replacement_window=window, replacement_n_lines=n_lines
- )
- )
- else:
- msg = "Invalid number of arguments. Must be 1 or 5."
- raise ValueError(msg)
+def flake8(file_path: str) -> str:
+ """Run flake8 on a given file and return the output as a string"""
+ if Path(file_path).suffix != ".py":
+ return ""
+ cmd = registry.get("LINT_COMMAND", "flake8 --isolated --select=F821,F822,F831,E111,E112,E113,E999,E902 {file_path}")
+ return subprocess.check_output(cmd.format(file_path=file_path), shell=True).decode("utf-8")
diff --git a/tools/edit_replace/bin/edit b/tools/edit_replace/bin/edit
index dd13f12a..3daaa19a 100644
--- a/tools/edit_replace/bin/edit
+++ b/tools/edit_replace/bin/edit
@@ -2,43 +2,123 @@
import argparse
-from default_utils import FileNotOpened, TextNotFound, WindowedFile # type: ignore
+try:
+ from sweagent import TOOLS_DIR
+except ImportError:
+ pass
+else:
+ import sys
-parser = argparse.ArgumentParser()
-parser.add_argument("search", type=str)
-parser.add_argument("replace", type=str)
-parser.add_argument("--replace-all", action="store_true")
-args = parser.parse_args()
+ default_lib = TOOLS_DIR / "defaults" / "lib"
+ assert default_lib.is_dir()
+ sys.path.append(str(default_lib))
+from default_utils import FileNotOpened, TextNotFound, WindowedFile # type: ignore
+from flake8_utils import flake8, format_flake8_output # type: ignore
-_NOT_FOUND_IN_WINDOW_MSG = f"""Text {args.search!r} not found in displayed lines.
+_NOT_FOUND_IN_WINDOW_MSG = """Text {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:
- wf = WindowedFile(exit_on_exception=False)
-except FileNotOpened:
- print("No file opened. Either `open` a file first.")
- exit(1)
+_SINGLE_EDIT_SUCCESS_MSG = """Text replaced. Please review the changes and make sure they are correct
+(correct indentation, no duplicate lines, etc). Edit the file again if necessary."""
-# Turn \\n into \n etc., i.e., undo the escaping
-# args.replace = args.replace.encode("utf8").decode("unicode_escape")
+_MULTIPLE_EDITS_SUCCESS_MSG = """Replaced {n_replacements} occurrences. Please review the changes and make sure they are correct
+(correct indentation, no duplicate lines, etc). Edit the file again if necessary."""
-if args.search == args.replace:
- print(_NO_CHANGES_MADE_MSG)
- exit(2)
+_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}
+------------------------------------------------
-if not args.replace_all:
+Your changes have NOT been applied. Please fix your edit command and try again.
+You either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.
+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("search", type=str)
+ parser.add_argument("replace", type=str)
+ parser.add_argument("--replace-all", action="store_true")
+ return parser
+
+
+def main(search: str, replace: str, replace_all: bool):
try:
- wf.replace_in_window(args.search, args.replace, n_replacements=1)
+ 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")
+
+ if search == replace:
+ print(_NO_CHANGES_MADE_MSG)
+ exit(2)
+
+ pre_edit_lint = flake8(wf.path)
+
+ try:
+ if not replace_all:
+ replacement_info = wf.replace_in_window(search, replace)
+ # todo: Should warn if more than one occurrence was found?
+ else:
+ # todo: Give overview of all replaced occurrences/number of replacements
+ replacement_info = wf.replace(search, replace)
except TextNotFound:
- print(_NOT_FOUND_IN_WINDOW_MSG)
+ print(_NOT_FOUND_IN_WINDOW_MSG.format(search=search))
exit(3)
-else:
- # todo: Give overview of all replaced occurrences
- wf.replace(args.search, args.replace)
-wf.print_window()
+ post_edit_lint = flake8(wf.path)
+
+ if not replace_all:
+ # Try to filter out pre-existing errors
+ replacement_window = (
+ replacement_info.first_replaced_line,
+ replacement_info.first_replaced_line + replacement_info.n_search_lines,
+ )
+ new_flake8_output = format_flake8_output(
+ post_edit_lint,
+ previous_errors_string=pre_edit_lint,
+ replacement_window=replacement_window,
+ replacement_n_lines=replacement_info.n_replace_lines,
+ )
+ else:
+ # Cannot easily compare the error strings, because line number changes are hard to keep track of
+ # So we show all linter errors.
+ new_flake8_output = format_flake8_output(post_edit_lint)
+
+ 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)
+ if not replace_all:
+ print(_SINGLE_EDIT_SUCCESS_MSG)
+ else:
+ print(_MULTIPLE_EDITS_SUCCESS_MSG.format(n_replacements=replacement_info.n_replacements))
+
+ wf.print_window()
+
+
+if __name__ == "__main__":
+ main(**vars(get_parser().parse_args()))