-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_simple_diff.py
More file actions
188 lines (154 loc) · 7.04 KB
/
Copy pathtest_simple_diff.py
File metadata and controls
188 lines (154 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python3
"""
Simple test to verify diff parsing with the correct file structure
"""
def apply_unified_diff_to_content(original_content: str, diff_content: str) -> str:
"""
Applies a unified diff or git diff string to the original content string.
Returns the patched content.
Raises ValueError if the patch cannot be applied cleanly.
"""
diff_content = diff_content.strip()
# Check if this is a git diff format (starts with diff --git)
if diff_content.startswith("diff --git") or diff_content.startswith("---"):
try:
# Parse the unified diff properly
lines = diff_content.split('\n')
original_lines = original_content.split('\n')
new_lines = original_lines.copy()
# Find all hunks in the diff
hunks = []
current_hunk = None
for line in lines:
if line.startswith('@@ '):
# Parse the hunk header: @@ -start,count +start,count @@
# Example: @@ -69,7 +69,9 @@
parts = line.split(' ')
if len(parts) >= 3:
old_range = parts[1] # -69,7
new_range = parts[2] # +69,9
old_start = int(old_range.split(',')[0][1:]) # 69
new_start = int(new_range.split(',')[0][1:]) # 69
current_hunk = {
'old_start': old_start,
'new_start': new_start,
'lines': []
}
hunks.append(current_hunk)
elif current_hunk is not None:
current_hunk['lines'].append(line)
# Apply hunks in reverse order to maintain line numbers
for hunk in reversed(hunks):
old_start = hunk['old_start'] - 1 # Convert to 0-based index
new_start = hunk['new_start'] - 1 # Convert to 0-based index
# Calculate how many lines to remove
lines_to_remove = 0
lines_to_add = []
for line in hunk['lines']:
if line.startswith('-'):
lines_to_remove += 1
elif line.startswith('+'):
lines_to_add.append(line[1:])
elif line.startswith(' '):
# Context line, skip
pass
# Apply the changes
if lines_to_remove > 0:
del new_lines[old_start:old_start + lines_to_remove]
if lines_to_add:
new_lines[old_start:old_start] = lines_to_add
# Join the lines back together
new_content = '\n'.join(new_lines)
return new_content
except Exception as e:
raise ValueError(f"Failed to parse unified diff: {str(e)}")
raise ValueError("Could not parse diff content. Ensure it's in the correct format.")
def test_diff_parsing():
"""Test the diff parsing with a simple file structure"""
# This is the file structure that the diff expects
original_content = '''from flask import Flask, request, jsonify
import os
app = Flask(__name__)
@app.route('/trigger-error', methods=['GET'])
def trigger_error():
error_enabled = request.args.get('error', 'false').lower() == 'true'
if error_enabled:
# INTENTIONAL ERROR: This will cause a NameError because 'undefined_variable' is not defined
# This is the error that can be fixed in a PR
result = undefined_variable + "This should cause an error"
return jsonify({'result': result})
else:
return jsonify({
'message': 'Error not triggered. Add ?error=true to trigger the error.',
'status': 'ok'
})
@app.route('/health', methods=['GET'])
def health_check():
return jsonify({'status': 'healthy'})
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal server error'}), 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True) '''
# The actual diff from the user's curl command
diff_content = '''diff --git a/app.py b/app.py
index c8cba05..d3349e5 100644
--- a/app.py
+++ b/app.py
@@ -69,7 +69,9 @@ def trigger_error():
if error_enabled:
# INTENTIONAL ERROR: This will cause a NameError because 'undefined_variable' is not defined
# This is the error that can be fixed in a PR
+ #result = undefined_variable + "This should cause an error"
result = undefined_variable + "This should cause an error"
+ result1 = undefined_variable + "This should cause an error"
return jsonify({'result': result})
else:
return jsonify({
@@ -117,4 +119,4 @@ def internal_error(error):
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
- app.run(host='0.0.0.0', port=port, debug=True) \n\\ No newline at end of file
+ app.run(host='0.0.0.0', port=port, debug=True) "'''
print("Testing diff parsing with correct file structure...")
print("=" * 60)
try:
# Apply the diff
result = apply_unified_diff_to_content(original_content, diff_content)
print("✅ Diff applied successfully!")
print(f"Original content length: {len(original_content)} characters")
print(f"Modified content length: {len(result)} characters")
# Show the differences
original_lines = original_content.split('\n')
result_lines = result.split('\n')
print(f"\nOriginal file has {len(original_lines)} lines")
print(f"Modified file has {len(result_lines)} lines")
# Show the specific changes around line 69-77
print("\nChanges around line 69-77:")
print("-" * 30)
for i in range(68, 80):
if i < len(original_lines):
print(f"Original {i+1:3d}: {original_lines[i]}")
if i < len(result_lines):
print(f"Modified {i+1:3d}: {result_lines[i]}")
print()
# Show the end of file changes
print("End of file changes:")
print("-" * 30)
for i in range(max(0, len(original_lines)-5), len(original_lines)):
if i < len(original_lines):
print(f"Original {i+1:3d}: {original_lines[i]}")
print()
for i in range(max(0, len(result_lines)-5), len(result_lines)):
if i < len(result_lines):
print(f"Modified {i+1:3d}: {result_lines[i]}")
except Exception as e:
print(f"❌ Error applying diff: {str(e)}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
test_diff_parsing()