aider: Update traverse_tree to print error type, line number, and 3 lines of context before/after the error.

# Aider chat conversation:

USER: print out the line and the N=3 lines before/after it

ASSISTANT: To print out the line with the error and the 3 lines before and after it, we need to modify the `traverse_tree` function in `aider/linter.py`. Here are the necessary changes:

aider/linter.py
```python
<<<<<<< SEARCH
    # Traverse the tree to find errors
=======
    # Traverse the tree to find errors and print context
>>>>>>> REPLACE
```

aider/linter.py
```python
<<<<<<< SEARCH
            print(f"{error_type} at line: {node.start_point[0] + 1}")
=======
            start_line = max(0, node.start_point[0] - 3)
            end_line = node.end_point[0] + 3
            error_line = node.start_point[0] + 1

            with open(file_path, 'r') as file:
                lines = file.readlines()

            print(f"{error_type} at line: {error_line}")
            print("Context:")
            for i in range(start_line, min(end_line, len(lines))):
                line_number = i + 1
                prefix = ">> " if line_number == error_line else "   "
                print(f"{prefix}{line_number}: {lines[i].rstrip()}")
            print("\n")
>>>>>>> REPLACE
```

This will ensure that the linter prints the error type, the line number, and the context of 3 lines before and after the error.
This commit is contained in:
Paul Gauthier 2024-05-17 14:00:59 -07:00
parent 0493680d57
commit 86fdeb0597

View file

@ -20,11 +20,24 @@ def parse_file_for_errors(file_path):
tree = parser.parse(bytes(content, "utf8"))
# Traverse the tree to find errors
# Traverse the tree to find errors and print context
def traverse_tree(node):
if node.type == 'ERROR' or node.is_missing:
error_type = 'Syntax error' if node.type == 'ERROR' else 'Missing element'
print(f"{error_type} at line: {node.start_point[0] + 1}")
start_line = max(0, node.start_point[0] - 3)
end_line = node.end_point[0] + 3
error_line = node.start_point[0] + 1
with open(file_path, 'r') as file:
lines = file.readlines()
print(f"{error_type} at line: {error_line}")
print("Context:")
for i in range(start_line, min(end_line, len(lines))):
line_number = i + 1
prefix = ">> " if line_number == error_line else " "
print(f"{prefix}{line_number}: {lines[i].rstrip()}")
print("\n")
for child in node.children:
traverse_tree(child)