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]

Fix: Linting blocks for existing lint errors (#593)

Kilian Lieret2902f525a450
diff --git a/config/commands/_split_string.py b/config/commands/_split_string.py
index ecc363e7..6d1c8c79 100644
--- a/config/commands/_split_string.py
+++ b/config/commands/_split_string.py
@@ -1,19 +1,123 @@
#!/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
+"""
+
from __future__ import annotations
import sys
+from dataclasses import dataclass
+
+
+@dataclass
+class Flake8Error:
+ """A class to represent a single flake8 error"""
+
+ filename: str
+ line_number: int
+ col_number: int
+ problem: str
+
+ @classmethod
+ def from_line(cls, line: str):
+ prefix, _sep, problem = line.partition(": ")
+ filename, line_number, col_number = prefix.split(":")
+ return cls(filename, int(line_number), int(col_number), problem)
+
+
+def _update_previous_errors(
+ previous_errors: list[Flake8Error], replacement_window: tuple[int, int], replacement_n_lines: int
+) -> list[Flake8Error]:
+ """Update the line numbers of the previous errors to what they would be after the edit window.
+ This is a helper function for `_filter_previous_errors`.
+
+ All previous errors that are inside of the edit window should not be ignored,
+ so they are removed from the previous errors list.
+
+ Args:
+ previous_errors: list of errors with old line numbers
+ replacement_window: the window of the edit/lines that will be replaced
+ replacement_n_lines: the number of lines that will be used to replace the text
+
+ Returns:
+ list of errors with updated line numbers
+ """
+ updated = []
+ lines_added = replacement_n_lines - (replacement_window[1] - replacement_window[0] + 1)
+ for error in previous_errors:
+ if error.line_number < replacement_window[0]:
+ # no need to adjust the line number
+ updated.append(error)
+ continue
+ if replacement_window[0] <= error.line_number <= replacement_window[1]:
+ # The error is within the edit window, so let's not ignore it
+ # either way (we wouldn't know how to adjust the line number anyway)
+ continue
+ # We're out of the edit window, so we need to adjust the line number
+ updated.append(Flake8Error(error.filename, error.line_number + lines_added, error.col_number, error.problem))
+ return updated
+
+
+def format_flake8_output(
+ input_string: str,
+ show_line_numbers: bool = False,
+ *,
+ previous_errors_string: str = "",
+ replacement_window: tuple[int, int] | None = None,
+ replacement_n_lines: int | None = None,
+) -> str:
+ """Filter flake8 output for previous errors and print it for a given file.
+ Args:
+ input_string: The flake8 output as a string
+ show_line_numbers: Whether to show line numbers in the output
+ previous_errors_string: The previous errors as a string
+ replacement_window: The window of the edit (lines that will be replaced)
+ replacement_n_lines: The number of lines used to replace the text
-def print_flake8_output(input_string, show_line_numbers=False):
- for value in input_string.split("\n"):
- parts = value.split()
+ Returns:
+ The filtered flake8 output as a string
+ """
+ errors = [Flake8Error.from_line(line.strip()) for line in input_string.split("\n") if line.strip()]
+ lines = []
+ if previous_errors_string:
+ assert replacement_window is not None
+ assert replacement_n_lines is not None
+ previous_errors = [
+ Flake8Error.from_line(line.strip()) for line in previous_errors_string.split("\n") if line.strip()
+ ]
+ previous_errors = _update_previous_errors(previous_errors, replacement_window, replacement_n_lines)
+ errors = [error for error in errors if error not in previous_errors]
+ for error in errors:
if not show_line_numbers:
- print(f"- {' '.join(parts[1:])}")
+ lines.append(f"- {error.problem}")
else:
- line_nums = ":".join(parts[0].split(":")[1:])
- print(f"- {line_nums} {' '.join(parts[1:])}")
+ lines.append(f"- {error.line_number}:{error.col_number} {error.problem}")
+ return "\n".join(lines)
if __name__ == "__main__":
- lint_output = sys.argv[1]
- print_flake8_output(lint_output)
+ 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)
diff --git a/config/commands/edit_linting.sh b/config/commands/edit_linting.sh
index e7547611..0c190a88 100644
--- a/config/commands/edit_linting.sh
+++ b/config/commands/edit_linting.sh
@@ -46,6 +46,9 @@ edit() {
return
fi
+ local linter_cmd="flake8 --isolated --select=F821,F822,F831,E111,E112,E113,E999,E902"
+ local linter_before_edit=$($linter_cmd "$CURRENT_FILE" 2>&1)
+
# Bash array starts at 0, so let's adjust
local start_line=$((start_line - 1))
local end_line=$((end_line))
@@ -69,7 +72,8 @@ edit() {
# Run linter
if [[ $CURRENT_FILE == *.py ]]; then
- lint_output=$(flake8 --isolated --select=F821,F822,F831,E111,E112,E113,E999,E902 "$CURRENT_FILE" 2>&1)
+ _lint_output=$($linter_cmd "$CURRENT_FILE" 2>&1)
+ lint_output=$(_split_string "$_lint_output" "$linter_before_edit" "$((start_line+1))" "$end_line" "$line_count")
else
# do nothing
lint_output=""
@@ -86,7 +90,7 @@ edit() {
echo "Your proposed edit has introduced new syntax error(s). Please read this error message carefully and then retry editing the file."
echo ""
echo "ERRORS:"
- _split_string "$lint_output"
+ echo "$lint_output"
echo ""
# Save original values
diff --git a/tests/test_commands.py b/tests/test_commands.py
new file mode 100644
index 00000000..876b4a14
--- /dev/null
+++ b/tests/test_commands.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+import sys
+
+sys.path.append("config/commands")
+
+
+from _split_string import Flake8Error, _update_previous_errors, format_flake8_output
+
+
+def test_partition_flake8_line():
+ assert Flake8Error.from_line("existing_lint error.py:12:41: E999 SyntaxError: invalid syntax") == Flake8Error(
+ "existing_lint error.py", 12, 41, "E999 SyntaxError: invalid syntax"
+ )
+
+
+def test_update_previous_errors():
+ previous_errors = [
+ Flake8Error("existing_lint_error.py", 12, 41, "E999 SyntaxError: invalid syntax"),
+ Flake8Error("existing_lint_error.py", 15, 41, "E999 SyntaxError: invalid syntax"),
+ Flake8Error("existing_lint_error.py", 20, 41, "E999 SyntaxError: invalid syntax"),
+ ]
+ assert _update_previous_errors(previous_errors, (15, 18), 3) == [
+ Flake8Error("existing_lint_error.py", 12, 41, "E999 SyntaxError: invalid syntax"),
+ Flake8Error("existing_lint_error.py", 19, 41, "E999 SyntaxError: invalid syntax"),
+ ]
+ assert _update_previous_errors([], (15, 18), 3) == []
+
+
+def test_flake8_format_no_error_1():
+ assert (
+ format_flake8_output(
+ "a:12:41: e", previous_errors_string="a:12:41: e", replacement_window=(50, 51), replacement_n_lines=10
+ )
+ == ""
+ )
+
+
+def test_flake8_format_no_error_2():
+ assert (
+ format_flake8_output(
+ "a:12:41: e", previous_errors_string="a:13:41: e", replacement_window=(1, 2), replacement_n_lines=1
+ )
+ == ""
+ )
+
+
+def test_flake8_format_no_error_3():
+ assert (
+ format_flake8_output(
+ "a:12:41: e", previous_errors_string="a:13:41: e", replacement_window=(1, 2), replacement_n_lines=1
+ )
+ == ""
+ )
+
+
+def test_flake8_format_error_1():
+ assert (
+ format_flake8_output(
+ "a:12:41: e", previous_errors_string="a:13:41: e", replacement_window=(12, 13), replacement_n_lines=10
+ )
+ == "- e"
+ )
+
+
+def test_flake8_format_error_1_linenumbers():
+ assert (
+ format_flake8_output(
+ "a:12:41: e",
+ previous_errors_string="a:13:41: e",
+ replacement_window=(12, 13),
+ replacement_n_lines=10,
+ show_line_numbers=True,
+ )
+ == "- 12:41 e"
+ )