| 1 | import ast |
| 2 | import glob |
| 3 | import pathlib |
| 4 | import re |
| 5 | from dataclasses import dataclass |
| 6 | from os.path import join as pjoin |
| 7 | |
| 8 | from app import utils as apputils |
| 9 | |
| 10 | |
| 11 | @dataclass |
| 12 | class 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 | |
| 89 | def 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 | |
| 133 | def 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 | function_nodes_in_class = [] |
| 153 | for node in ast.walk(tree): |
| 154 | if isinstance(node, ast.ClassDef): |
| 155 | ## class part (1): collect class info |
| 156 | class_name = node.name |
| 157 | start_lineno = node.lineno |
| 158 | end_lineno = node.end_lineno |
| 159 | # line numbers are 1-based |
| 160 | classes.append((class_name, start_lineno, end_lineno)) |
| 161 | |
| 162 | ## class part (2): collect function info inside this class |
| 163 | class_funcs = [] |
| 164 | for n in ast.walk(node): |
| 165 | if isinstance(n, ast.FunctionDef): |
| 166 | class_funcs.append((n.name, n.lineno, n.end_lineno)) |
| 167 | function_nodes_in_class.append(n) |
| 168 | class_to_funcs[class_name] = class_funcs |
| 169 | |
| 170 | # top-level functions, excluding functions defined in classes |
| 171 | elif isinstance(node, ast.FunctionDef) and node not in function_nodes_in_class: |
| 172 | function_name = node.name |
| 173 | start_lineno = node.lineno |
| 174 | end_lineno = node.end_lineno |
| 175 | # line numbers are 1-based |
| 176 | top_level_funcs.append((function_name, start_lineno, end_lineno)) |
| 177 | |
| 178 | return classes, class_to_funcs, top_level_funcs |
| 179 | |
| 180 | |
| 181 | def get_func_snippet_in_class( |
| 182 | file_full_path: str, class_name: str, func_name: str, include_lineno=False |
| 183 | ) -> str | None: |
| 184 | """Get actual function source code in class. |
| 185 | |
| 186 | All source code of the function is returned. |
| 187 | Assumption: the class and function exist. |
| 188 | """ |
| 189 | with open(file_full_path) as f: |
| 190 | file_content = f.read() |
| 191 | |
| 192 | tree = ast.parse(file_content) |
| 193 | for node in ast.walk(tree): |
| 194 | if isinstance(node, ast.ClassDef) and node.name == class_name: |
| 195 | for n in ast.walk(node): |
| 196 | if isinstance(n, ast.FunctionDef) and n.name == func_name: |
| 197 | start_lineno = n.lineno |
| 198 | end_lineno = n.end_lineno |
| 199 | assert end_lineno is not None, "end_lineno is None" |
| 200 | if include_lineno: |
| 201 | return get_code_snippets_with_lineno( |
| 202 | file_full_path, start_lineno, end_lineno |
| 203 | ) |
| 204 | else: |
| 205 | return get_code_snippets( |
| 206 | file_full_path, start_lineno, end_lineno |
| 207 | ) |
| 208 | # In this file, cannot find either the class, or a function within the class |
| 209 | return None |
| 210 | |
| 211 | |
| 212 | def get_code_region_containing_code( |
| 213 | file_full_path: str, code_str: str |
| 214 | ) -> list[tuple[int, str]]: |
| 215 | """In a file, get the region of code that contains a specific string. |
| 216 | |
| 217 | Args: |
| 218 | - file_full_path: Path to the file. (absolute path) |
| 219 | - code_str: The string that the function should contain. |
| 220 | Returns: |
| 221 | - A list of tuple, each of them is a pair of (line_no, code_snippet). |
| 222 | line_no is the starting line of the matched code; code snippet is the |
| 223 | source code of the searched region. |
| 224 | """ |
| 225 | with open(file_full_path) as f: |
| 226 | file_content = f.read() |
| 227 | |
| 228 | context_size = 3 |
| 229 | # since the code_str may contain multiple lines, let's not split the source file. |
| 230 | |
| 231 | # we want a few lines before and after the matched string. Since the matched string |
| 232 | # can also contain new lines, this is a bit trickier. |
| 233 | pattern = re.compile(re.escape(code_str)) |
| 234 | # each occurrence is a tuple of (line_no, code_snippet) (1-based line number) |
| 235 | occurrences: list[tuple[int, str]] = [] |
| 236 | for match in pattern.finditer(file_content): |
| 237 | matched_start_pos = match.start() |
| 238 | # first, find the line number of the matched start position (1-based) |
| 239 | matched_line_no = file_content.count("\n", 0, matched_start_pos) + 1 |
| 240 | # next, get a few surrounding lines as context |
| 241 | search_start = match.start() - 1 |
| 242 | search_end = match.end() + 1 |
| 243 | # from the matched position, go left to find 5 new lines. |
| 244 | for _ in range(context_size): |
| 245 | # find the \n to the left |
| 246 | left_newline = file_content.rfind("\n", 0, search_start) |
| 247 | if left_newline == -1: |
| 248 | # no more new line to the left |
| 249 | search_start = 0 |
| 250 | break |
| 251 | else: |
| 252 | search_start = left_newline |
| 253 | # go right to fine 5 new lines |
| 254 | for _ in range(context_size): |
| 255 | right_newline = file_content.find("\n", search_end + 1) |
| 256 | if right_newline == -1: |
| 257 | # no more new line to the right |
| 258 | search_end = len(file_content) |
| 259 | break |
| 260 | else: |
| 261 | search_end = right_newline |
| 262 | |
| 263 | start = max(0, search_start) |
| 264 | end = min(len(file_content), search_end) |
| 265 | context = file_content[start:end] |
| 266 | occurrences.append((matched_line_no, context)) |
| 267 | |
| 268 | return occurrences |
| 269 | |
| 270 | |
| 271 | def get_func_snippet_with_code_in_file(file_full_path: str, code_str: str) -> list[str]: |
| 272 | """In a file, get the function code, for which the function contains a specific string. |
| 273 | |
| 274 | Args: |
| 275 | file_full_path (str): Path to the file. (absolute path) |
| 276 | code_str (str): The string that the function should contain. |
| 277 | |
| 278 | Returns: |
| 279 | A list of code snippets, each of them is the source code of the searched function. |
| 280 | """ |
| 281 | with open(file_full_path) as f: |
| 282 | file_content = f.read() |
| 283 | |
| 284 | tree = ast.parse(file_content) |
| 285 | all_snippets = [] |
| 286 | for node in ast.walk(tree): |
| 287 | if not isinstance(node, ast.FunctionDef): |
| 288 | continue |
| 289 | func_start_lineno = node.lineno |
| 290 | func_end_lineno = node.end_lineno |
| 291 | assert func_end_lineno is not None |
| 292 | func_code = get_code_snippets( |
| 293 | file_full_path, func_start_lineno, func_end_lineno |
| 294 | ) |
| 295 | # This func code is a raw concatenation of source lines which contains new lines and tabs. |
| 296 | # For the purpose of searching, we remove all spaces and new lines in the code and the |
| 297 | # search string, to avoid non-match due to difference in formatting. |
| 298 | stripped_func = " ".join(func_code.split()) |
| 299 | stripped_code_str = " ".join(code_str.split()) |
| 300 | if stripped_code_str in stripped_func: |
| 301 | all_snippets.append(func_code) |
| 302 | |
| 303 | return all_snippets |
| 304 | |
| 305 | |
| 306 | def get_code_snippets_with_lineno(file_full_path: str, start: int, end: int) -> str: |
| 307 | """Get the code snippet in the range in the file. |
| 308 | |
| 309 | The code snippet should come with line number at the beginning for each line. |
| 310 | |
| 311 | TODO: When there are too many lines, return only parts of the output. |
| 312 | For class, this should only involve the signatures. |
| 313 | For functions, maybe do slicing with dependency analysis? |
| 314 | |
| 315 | Args: |
| 316 | file_path (str): Path to the file. |
| 317 | start (int): Start line number. (1-based) |
| 318 | end (int): End line number. (1-based) |
| 319 | """ |
| 320 | with open(file_full_path) as f: |
| 321 | file_content = f.readlines() |
| 322 | |
| 323 | snippet = "" |
| 324 | for i in range(start - 1, end): |
| 325 | snippet += f"{i+1} {file_content[i]}" |
| 326 | return snippet |
| 327 | |
| 328 | |
| 329 | def get_code_snippets(file_full_path: str, start: int, end: int) -> str: |
| 330 | """Get the code snippet in the range in the file, without line numbers. |
| 331 | |
| 332 | Args: |
| 333 | file_path (str): Full path to the file. |
| 334 | start (int): Start line number. (1-based) |
| 335 | end (int): End line number. (1-based) |
| 336 | """ |
| 337 | with open(file_full_path) as f: |
| 338 | file_content = f.readlines() |
| 339 | snippet = "" |
| 340 | for i in range(start - 1, end): |
| 341 | snippet += file_content[i] |
| 342 | return snippet |
| 343 | |
| 344 | |
| 345 | def extract_func_sig_from_ast(func_ast: ast.FunctionDef) -> list[int]: |
| 346 | """Extract the function signature from the AST node. |
| 347 | |
| 348 | Includes the decorators, method name, and parameters. |
| 349 | |
| 350 | Args: |
| 351 | func_ast (ast.FunctionDef): AST of the function. |
| 352 | |
| 353 | Returns: |
| 354 | The source line numbers that contains the function signature. |
| 355 | """ |
| 356 | func_start_line = func_ast.lineno |
| 357 | if func_ast.decorator_list: |
| 358 | # has decorators |
| 359 | decorator_start_lines = [d.lineno for d in func_ast.decorator_list] |
| 360 | decorator_first_line = min(decorator_start_lines) |
| 361 | func_start_line = min(decorator_first_line, func_start_line) |
| 362 | # decide end line from body |
| 363 | if func_ast.body: |
| 364 | # has body |
| 365 | body_start_line = func_ast.body[0].lineno |
| 366 | end_line = body_start_line - 1 |
| 367 | else: |
| 368 | # no body |
| 369 | end_line = func_ast.end_lineno |
| 370 | assert end_line is not None |
| 371 | return list(range(func_start_line, end_line + 1)) |
| 372 | |
| 373 | |
| 374 | def extract_class_sig_from_ast(class_ast: ast.ClassDef) -> list[int]: |
| 375 | """Extract the class signature from the AST. |
| 376 | |
| 377 | Args: |
| 378 | class_ast (ast.ClassDef): AST of the class. |
| 379 | |
| 380 | Returns: |
| 381 | The source line numbers that contains the class signature. |
| 382 | """ |
| 383 | # STEP (1): extract the class signature |
| 384 | sig_start_line = class_ast.lineno |
| 385 | if class_ast.body: |
| 386 | # has body |
| 387 | body_start_line = class_ast.body[0].lineno |
| 388 | sig_end_line = body_start_line - 1 |
| 389 | else: |
| 390 | # no body |
| 391 | sig_end_line = class_ast.end_lineno |
| 392 | assert sig_end_line is not None |
| 393 | sig_lines = list(range(sig_start_line, sig_end_line + 1)) |
| 394 | |
| 395 | # STEP (2): extract the function signatures and assign signatures |
| 396 | for stmt in class_ast.body: |
| 397 | if isinstance(stmt, ast.FunctionDef): |
| 398 | sig_lines.extend(extract_func_sig_from_ast(stmt)) |
| 399 | elif isinstance(stmt, ast.Assign): |
| 400 | # for Assign, skip some useless cases where the assignment is to create docs |
| 401 | stmt_str_format = ast.dump(stmt) |
| 402 | if "__doc__" in stmt_str_format: |
| 403 | continue |
| 404 | # otherwise, Assign is easy to handle |
| 405 | assert stmt.end_lineno is not None |
| 406 | assign_range = list(range(stmt.lineno, stmt.end_lineno + 1)) |
| 407 | sig_lines.extend(assign_range) |
| 408 | |
| 409 | return sig_lines |
| 410 | |
| 411 | |
| 412 | def get_class_signature(file_full_path: str, class_name: str) -> str: |
| 413 | """Get the class signature. |
| 414 | |
| 415 | Args: |
| 416 | file_path (str): Path to the file. |
| 417 | class_name (str): Name of the class. |
| 418 | """ |
| 419 | with open(file_full_path) as f: |
| 420 | file_content = f.read() |
| 421 | |
| 422 | tree = ast.parse(file_content) |
| 423 | relevant_lines = [] |
| 424 | for node in ast.walk(tree): |
| 425 | if isinstance(node, ast.ClassDef) and node.name == class_name: |
| 426 | # we reached the target class |
| 427 | relevant_lines = extract_class_sig_from_ast(node) |
| 428 | break |
| 429 | if not relevant_lines: |
| 430 | return "" |
| 431 | else: |
| 432 | with open(file_full_path) as f: |
| 433 | file_content = f.readlines() |
| 434 | result = "" |
| 435 | for line in relevant_lines: |
| 436 | line_content: str = file_content[line - 1] |
| 437 | if line_content.strip().startswith("#"): |
| 438 | # this kind of comment could be left until this stage. |
| 439 | # reason: # comments are not part of func body if they appear at beginning of func |
| 440 | continue |
| 441 | result += line_content |
| 442 | return result |