Elffuss BraidHub

kikocis/auto-code-rover public

0f4e2e4e2ecb · 15.8 KiBRawPermalink
1import ast
2import glob
3import pathlib
4import re
5from dataclasses import dataclass
6from os.path import join as pjoin
7
8from app import utils as apputils
9
10
11@dataclass
12class SearchResult:
13 """Dataclass to hold search results."""
14
15 file_path: str # this is absolute path
16 class_name: str | None
17 func_name: str | None
18 code: str
19
20 def to_tagged_upto_file(self, project_root: str):
21 """Convert the search result to a tagged string, upto file path."""
22 rel_path = apputils.to_relative_path(self.file_path, project_root)
23 file_part = f"<file>{rel_path}</file>"
24 return file_part
25
26 def to_tagged_upto_class(self, project_root: str):
27 """Convert the search result to a tagged string, upto class."""
28 prefix = self.to_tagged_upto_file(project_root)
29 class_part = (
30 f"<class>{self.class_name}</class>" if self.class_name is not None else ""
31 )
32 return f"{prefix}\n{class_part}"
33
34 def to_tagged_upto_func(self, project_root: str):
35 """Convert the search result to a tagged string, upto function."""
36 prefix = self.to_tagged_upto_class(project_root)
37 func_part = (
38 f" <func>{self.func_name}</func>" if self.func_name is not None else ""
39 )
40 return f"{prefix}{func_part}"
41
42 def to_tagged_str(self, project_root: str):
43 """Convert the search result to a tagged string."""
44 prefix = self.to_tagged_upto_func(project_root)
45 code_part = f"<code>\n{self.code}\n</code>"
46 return f"{prefix}\n{code_part}"
47
48 @staticmethod
49 def collapse_to_file_level(lst, project_root: str) -> str:
50 """Collapse search results to file level."""
51 res = dict() # file -> count
52 for r in lst:
53 if r.file_path not in res:
54 res[r.file_path] = 1
55 else:
56 res[r.file_path] += 1
57 res_str = ""
58 for file_path, count in res.items():
59 rel_path = apputils.to_relative_path(file_path, project_root)
60 file_part = f"<file>{rel_path}</file>"
61 res_str += f"- {file_part} ({count} matches)\n"
62 return res_str
63
64 @staticmethod
65 def collapse_to_method_level(lst, project_root: str) -> str:
66 """Collapse search results to method level."""
67 res = dict() # file -> dict(method -> count)
68 for r in lst:
69 if r.file_path not in res:
70 res[r.file_path] = dict()
71 func_str = r.func_name if r.func_name is not None else "Not in a function"
72 if func_str not in res[r.file_path]:
73 res[r.file_path][func_str] = 1
74 else:
75 res[r.file_path][func_str] += 1
76 res_str = ""
77 for file_path, funcs in res.items():
78 rel_path = apputils.to_relative_path(file_path, project_root)
79 file_part = f"<file>{rel_path}</file>"
80 for func, count in funcs.items():
81 if func == "Not in a function":
82 func_part = func
83 else:
84 func_part = f" <func>{func}</func>"
85 res_str += f"- {file_part}{func_part} ({count} matches)\n"
86 return res_str
87
88
89def find_python_files(dir_path: str) -> list[str]:
90 """Get all .py files recursively from a directory.
91
92 Skips files that are obviously not from the source code, such third-party library code.
93
94 Args:
95 dir_path (str): Path to the directory.
96 Returns:
97 List[str]: List of .py file paths. These paths are ABSOLUTE path!
98 """
99
100 py_files = glob.glob(pjoin(dir_path, "**/*.py"), recursive=True)
101 res = []
102 for file in py_files:
103 rel_path = file[len(dir_path) + 1 :]
104 if rel_path.startswith("build"):
105 continue
106 if rel_path.startswith("doc"):
107 # discovered this issue in 'pytest-dev__pytest'
108 continue
109 if rel_path.startswith("requests/packages"):
110 # to walkaround issue in 'psf__requests'
111 continue
112 if (
113 rel_path.startswith("tests/regrtest_data")
114 or rel_path.startswith("tests/input")
115 or rel_path.startswith("tests/functional")
116 ):
117 # to walkaround issue in 'pylint-dev__pylint'
118 continue
119 if rel_path.startswith("tests/roots") or rel_path.startswith(
120 "sphinx/templates/latex"
121 ):
122 # to walkaround issue in 'sphinx-doc__sphinx'
123 continue
124 if rel_path.startswith("tests/test_runner_apps/tagged/") or rel_path.startswith(
125 "django/conf/app_template/"
126 ):
127 # to walkaround issue in 'django__django'
128 continue
129 res.append(file)
130 return res
131
132
133def parse_python_file(file_full_path: str) -> tuple[list, dict, list] | None:
134 """
135 Main method to parse AST and build search index.
136 Handles complication where python ast module cannot parse a file.
137 """
138 try:
139 file_content = pathlib.Path(file_full_path).read_text()
140 tree = ast.parse(file_content)
141 except Exception:
142 # failed to read/parse one file, we should ignore it
143 return None
144
145 # (1) get all classes defined in the file
146 classes = []
147 # (2) for each class in the file, get all functions defined in the class.
148 class_to_funcs = {}
149 # (3) get top-level functions in the file (exclues functions defined in classes)
150 top_level_funcs = []
151
152 for node in ast.walk(tree):
153 if isinstance(node, ast.ClassDef):
154 ## class part (1): collect class info
155 class_name = node.name
156 start_lineno = node.lineno
157 end_lineno = node.end_lineno
158 # line numbers are 1-based
159 classes.append((class_name, start_lineno, end_lineno))
160
161 ## class part (2): collect function info inside this class
162 class_funcs = [
163 (n.name, n.lineno, n.end_lineno)
164 for n in ast.walk(node)
165 if isinstance(n, ast.FunctionDef)
166 ]
167 class_to_funcs[class_name] = class_funcs
168
169 elif isinstance(node, ast.FunctionDef):
170 function_name = node.name
171 start_lineno = node.lineno
172 end_lineno = node.end_lineno
173 # line numbers are 1-based
174 top_level_funcs.append((function_name, start_lineno, end_lineno))
175
176 return classes, class_to_funcs, top_level_funcs
177
178
179def get_func_snippet_in_class(
180 file_full_path: str, class_name: str, func_name: str, include_lineno=False
181) -> str | None:
182 """Get actual function source code in class.
183
184 All source code of the function is returned.
185 Assumption: the class and function exist.
186 """
187 with open(file_full_path) as f:
188 file_content = f.read()
189
190 tree = ast.parse(file_content)
191 for node in ast.walk(tree):
192 if isinstance(node, ast.ClassDef) and node.name == class_name:
193 for n in ast.walk(node):
194 if isinstance(n, ast.FunctionDef) and n.name == func_name:
195 start_lineno = n.lineno
196 end_lineno = n.end_lineno
197 assert end_lineno is not None, "end_lineno is None"
198 if include_lineno:
199 return get_code_snippets_with_lineno(
200 file_full_path, start_lineno, end_lineno
201 )
202 else:
203 return get_code_snippets(
204 file_full_path, start_lineno, end_lineno
205 )
206 # In this file, cannot find either the class, or a function within the class
207 return None
208
209
210def get_code_region_containing_code(
211 file_full_path: str, code_str: str
212) -> list[tuple[int, str]]:
213 """In a file, get the region of code that contains a specific string.
214
215 Args:
216 - file_full_path: Path to the file. (absolute path)
217 - code_str: The string that the function should contain.
218 Returns:
219 - A list of tuple, each of them is a pair of (line_no, code_snippet).
220 line_no is the starting line of the matched code; code snippet is the
221 source code of the searched region.
222 """
223 with open(file_full_path) as f:
224 file_content = f.read()
225
226 context_size = 3
227 # since the code_str may contain multiple lines, let's not split the source file.
228
229 # we want a few lines before and after the matched string. Since the matched string
230 # can also contain new lines, this is a bit trickier.
231 pattern = re.compile(re.escape(code_str))
232 # each occurrence is a tuple of (line_no, code_snippet) (1-based line number)
233 occurrences: list[tuple[int, str]] = []
234 for match in pattern.finditer(file_content):
235 matched_start_pos = match.start()
236 # first, find the line number of the matched start position (1-based)
237 matched_line_no = file_content.count("\n", 0, matched_start_pos) + 1
238 # next, get a few surrounding lines as context
239 search_start = match.start() - 1
240 search_end = match.end() + 1
241 # from the matched position, go left to find 5 new lines.
242 for _ in range(context_size):
243 # find the \n to the left
244 left_newline = file_content.rfind("\n", 0, search_start)
245 if left_newline == -1:
246 # no more new line to the left
247 search_start = 0
248 break
249 else:
250 search_start = left_newline
251 # go right to fine 5 new lines
252 for _ in range(context_size):
253 right_newline = file_content.find("\n", search_end + 1)
254 if right_newline == -1:
255 # no more new line to the right
256 search_end = len(file_content)
257 break
258 else:
259 search_end = right_newline
260
261 start = max(0, search_start)
262 end = min(len(file_content), search_end)
263 context = file_content[start:end]
264 occurrences.append((matched_line_no, context))
265
266 return occurrences
267
268
269def get_func_snippet_with_code_in_file(file_full_path: str, code_str: str) -> list[str]:
270 """In a file, get the function code, for which the function contains a specific string.
271
272 Args:
273 file_full_path (str): Path to the file. (absolute path)
274 code_str (str): The string that the function should contain.
275
276 Returns:
277 A list of code snippets, each of them is the source code of the searched function.
278 """
279 with open(file_full_path) as f:
280 file_content = f.read()
281
282 tree = ast.parse(file_content)
283 all_snippets = []
284 for node in ast.walk(tree):
285 if not isinstance(node, ast.FunctionDef):
286 continue
287 func_start_lineno = node.lineno
288 func_end_lineno = node.end_lineno
289 assert func_end_lineno is not None
290 func_code = get_code_snippets(
291 file_full_path, func_start_lineno, func_end_lineno
292 )
293 # This func code is a raw concatenation of source lines which contains new lines and tabs.
294 # For the purpose of searching, we remove all spaces and new lines in the code and the
295 # search string, to avoid non-match due to difference in formatting.
296 stripped_func = " ".join(func_code.split())
297 stripped_code_str = " ".join(code_str.split())
298 if stripped_code_str in stripped_func:
299 all_snippets.append(func_code)
300
301 return all_snippets
302
303
304def get_code_snippets_with_lineno(file_full_path: str, start: int, end: int) -> str:
305 """Get the code snippet in the range in the file.
306
307 The code snippet should come with line number at the beginning for each line.
308
309 TODO: When there are too many lines, return only parts of the output.
310 For class, this should only involve the signatures.
311 For functions, maybe do slicing with dependency analysis?
312
313 Args:
314 file_path (str): Path to the file.
315 start (int): Start line number. (1-based)
316 end (int): End line number. (1-based)
317 """
318 with open(file_full_path) as f:
319 file_content = f.readlines()
320
321 snippet = ""
322 for i in range(start - 1, end):
323 snippet += f"{i+1} {file_content[i]}"
324 return snippet
325
326
327def get_code_snippets(file_full_path: str, start: int, end: int) -> str:
328 """Get the code snippet in the range in the file, without line numbers.
329
330 Args:
331 file_path (str): Full path to the file.
332 start (int): Start line number. (1-based)
333 end (int): End line number. (1-based)
334 """
335 with open(file_full_path) as f:
336 file_content = f.readlines()
337 snippet = ""
338 for i in range(start - 1, end):
339 snippet += file_content[i]
340 return snippet
341
342
343def extract_func_sig_from_ast(func_ast: ast.FunctionDef) -> list[int]:
344 """Extract the function signature from the AST node.
345
346 Includes the decorators, method name, and parameters.
347
348 Args:
349 func_ast (ast.FunctionDef): AST of the function.
350
351 Returns:
352 The source line numbers that contains the function signature.
353 """
354 func_start_line = func_ast.lineno
355 if func_ast.decorator_list:
356 # has decorators
357 decorator_start_lines = [d.lineno for d in func_ast.decorator_list]
358 decorator_first_line = min(decorator_start_lines)
359 func_start_line = min(decorator_first_line, func_start_line)
360 # decide end line from body
361 if func_ast.body:
362 # has body
363 body_start_line = func_ast.body[0].lineno
364 end_line = body_start_line - 1
365 else:
366 # no body
367 end_line = func_ast.end_lineno
368 assert end_line is not None
369 return list(range(func_start_line, end_line + 1))
370
371
372def extract_class_sig_from_ast(class_ast: ast.ClassDef) -> list[int]:
373 """Extract the class signature from the AST.
374
375 Args:
376 class_ast (ast.ClassDef): AST of the class.
377
378 Returns:
379 The source line numbers that contains the class signature.
380 """
381 # STEP (1): extract the class signature
382 sig_start_line = class_ast.lineno
383 if class_ast.body:
384 # has body
385 body_start_line = class_ast.body[0].lineno
386 sig_end_line = body_start_line - 1
387 else:
388 # no body
389 sig_end_line = class_ast.end_lineno
390 assert sig_end_line is not None
391 sig_lines = list(range(sig_start_line, sig_end_line + 1))
392
393 # STEP (2): extract the function signatures and assign signatures
394 for stmt in class_ast.body:
395 if isinstance(stmt, ast.FunctionDef):
396 sig_lines.extend(extract_func_sig_from_ast(stmt))
397 elif isinstance(stmt, ast.Assign):
398 # for Assign, skip some useless cases where the assignment is to create docs
399 stmt_str_format = ast.dump(stmt)
400 if "__doc__" in stmt_str_format:
401 continue
402 # otherwise, Assign is easy to handle
403 assert stmt.end_lineno is not None
404 assign_range = list(range(stmt.lineno, stmt.end_lineno + 1))
405 sig_lines.extend(assign_range)
406
407 return sig_lines
408
409
410def get_class_signature(file_full_path: str, class_name: str) -> str:
411 """Get the class signature.
412
413 Args:
414 file_path (str): Path to the file.
415 class_name (str): Name of the class.
416 """
417 with open(file_full_path) as f:
418 file_content = f.read()
419
420 tree = ast.parse(file_content)
421 relevant_lines = []
422 for node in ast.walk(tree):
423 if isinstance(node, ast.ClassDef) and node.name == class_name:
424 # we reached the target class
425 relevant_lines = extract_class_sig_from_ast(node)
426 break
427 if not relevant_lines:
428 return ""
429 else:
430 with open(file_full_path) as f:
431 file_content = f.readlines()
432 result = ""
433 for line in relevant_lines:
434 line_content: str = file_content[line - 1]
435 if line_content.strip().startswith("#"):
436 # this kind of comment could be left until this stage.
437 # reason: # comments are not part of func body if they appear at beginning of func
438 continue
439 result += line_content
440 return result