Elffuss BraidHub

kikocis/auto-code-rover public

6b89c7c64bd8 · 7.1 KiBRawPermalink
1"""
2Utility functions for parsing and applying the patch.
3
4Inspired by:
5https://github.com/gpt-engineer-org/gpt-engineer/blob/main/gpt_engineer/core/chat_to_files.py
6"""
7
8import re
9from dataclasses import dataclass
10from pprint import pformat
11from tempfile import NamedTemporaryFile
12from typing import TextIO
13
14from pylint.lint import Run
15from pylint.reporters.text import TextReporter
16
17
18@dataclass
19class Edit:
20 filename: str
21 before: str
22 after: str
23
24 def __str__(self):
25 return f"{self.filename}\nBefore:\n{pformat(self.before)}\nAfter:\n{pformat(self.after)}\n"
26
27 def __repr__(self):
28 return str(self)
29
30
31def parse_edits(chat_string: str) -> list[Edit]:
32 """
33 Parse edits from a chat string.
34
35 This function extracts code edits from a chat string and returns them as a list
36 of Edit objects.
37
38 Args:
39 chat_string (str): The chat content containing code edits.
40
41 Returns:
42 List[Edit]: A list of Edit objects representing the parsed code edits.
43 """
44
45 def parse_in_fence(lines: list[str]):
46 """
47 New version of parsing multiple edits within one fence.
48 """
49 # remove obviously suspicious lines
50 sus_contents = ["# Rest of the code..."]
51 lines = [line for line in lines if line.strip() not in sus_contents]
52
53 file_start = "<file>"
54 file_end = "</file>"
55 original_start = "<original>"
56 original_end = "</original>"
57 patched_start = "<patched>"
58 patched_end = "</patched>"
59
60 all_edits: list[Edit] = []
61 content = "\n".join(lines)
62
63 # use regex to find content between <file> and </file>
64 file_pattern = re.compile(f"{file_start}(.*?){file_end}", re.DOTALL)
65 original_pattern = re.compile(f"{original_start}(.*?){original_end}", re.DOTALL)
66 patched_pattern = re.compile(f"{patched_start}(.*?){patched_end}", re.DOTALL)
67
68 file_matches = file_pattern.findall(content)
69 original_matches = original_pattern.findall(content)
70 patched_matches = patched_pattern.findall(content)
71
72 for file, original, patched in zip(
73 file_matches, original_matches, patched_matches
74 ):
75 # for file, we strip all spaces
76 file = file.strip()
77 # for original and patched, keep the spaces, since removing spaces at beginning or end
78 # may mess up indentation level on some of the lines.
79 # However, we should remove the new lines at start and end. These new lines may be
80 # inserted by the model, but if in the original code there are no such new lines before
81 # the actual code, this can result in non-match
82 original = original.strip("\n")
83 patched = patched.strip("\n")
84 all_edits.append(Edit(file, original, patched))
85
86 return all_edits
87
88 edits = []
89 current_edit = []
90 in_fence = False
91
92 for line in chat_string.split("\n"):
93 if line.startswith("```") and in_fence:
94 edits.extend(parse_in_fence(current_edit))
95 current_edit = []
96 in_fence = False
97 continue
98 elif line.startswith("```") and not in_fence:
99 in_fence = True
100 continue
101 if in_fence:
102 current_edit.append(line)
103
104 return edits
105
106
107def apply_edit(edit: Edit, file_path: str) -> str | None:
108 """
109 Apply one Edit to a file. This function reads the file, tries to match
110 the before string (after stripping spaces in the original program and the
111 before string improve the chance of matching), and then replaces the matched region with the after string.
112 Returns:
113 - Path to the file containing updated content if successful;
114 None otherwise.
115 """
116 with open(file_path) as f:
117 orig_prog_lines = f.readlines()
118
119 before = edit.before
120 after = edit.after
121
122 # check whether before is in the original program
123 before_lines = before.split("\n")
124 # NOTE: These are just for matching; do not use to form back the program
125 cleaned_before_lines = [line.strip() for line in before_lines]
126 cleaned_orig_lines = [line.strip() for line in orig_prog_lines]
127 # match before in the original program
128 match_start = -1
129 match_end = -1
130 for i in range(len(cleaned_orig_lines) - len(cleaned_before_lines) + 1):
131 # check all possible starting positions in the orig program
132 if (
133 cleaned_orig_lines[i : i + len(cleaned_before_lines)]
134 == cleaned_before_lines
135 ):
136 match_start = i
137 match_end = i + len(cleaned_before_lines)
138 break
139 if match_start == -1:
140 # cound not find a match
141 return None
142
143 # found a match, replace the matched region with after
144
145 # First guess: in the patch, the indentation difference between the first line and
146 # subsequent lines are correct. In this case, first calculate the indentation difference
147 # between the first line of patch & original file; subsequent lines are all prepended with
148 # this difference.
149 matched_orig_region = orig_prog_lines[match_start:match_end]
150 after_lines = after.split("\n")
151
152 if before_lines[0] in matched_orig_region[0]:
153 abs_indent_of_first_line = matched_orig_region[0].index(before_lines[0])
154 fixed_after_lines = [
155 " " * abs_indent_of_first_line + line for line in after_lines
156 ]
157 else:
158 # will raise if cannot find
159 abs_indent_of_first_line = before_lines[0].index(
160 matched_orig_region[0].rstrip("\n")
161 )
162 fixed_after_lines = [line[abs_indent_of_first_line:] for line in after_lines]
163
164 # form the new program
165 prefix = "".join(orig_prog_lines[:match_start])
166 suffix = "".join(orig_prog_lines[match_end:])
167
168 new_prog_1 = prefix + "\n".join(fixed_after_lines) + "\n" + suffix
169
170 # Second guess: the absolute indentation of the second to last lines are correct. In this case,
171 # simply fix the indentation of the first line.
172 fixed_after_lines[1:] = after_lines[1:]
173 new_prog_2 = prefix + "\n".join(fixed_after_lines) + "\n" + suffix
174
175 if lint_python_content(new_prog_1):
176 new_prog = new_prog_1
177 elif lint_python_content(new_prog_2):
178 new_prog = new_prog_2
179 else:
180 return None
181
182 with open(file_path, "w") as f:
183 f.write(new_prog)
184
185 return file_path
186
187
188class Writable(TextIO):
189 "dummy output stream for pylint"
190
191 def __init__(self) -> None:
192 self.content: list[str] = []
193
194 def write(self, s: str) -> int:
195 self.content.append(s)
196 return len(s)
197
198 def read(self, n: int = 0) -> str:
199 return "\n".join(self.content)
200
201
202def lint_python_content(content: str) -> bool:
203 """Check if python content lints OK.
204
205 Args:
206 content: python file content
207
208 Returns: True if the contents passes linting, False otherwise.
209
210 """
211 pylint_out = Writable()
212 reporter = TextReporter(pylint_out)
213
214 with NamedTemporaryFile(buffering=0) as f:
215 f.write(content.encode())
216
217 _ = Run(["--errors-only", f.name], reporter=reporter, exit=False)
218
219 return not any(error.endswith("(syntax-error)") for error in pylint_out.content)