File size: 22,784 Bytes
2a9dc4c 48f2b75 2a9dc4c 48f2b75 ba784dc 2a9dc4c 48f2b75 2a9dc4c 48f2b75 2a9dc4c 48f2b75 2a9dc4c e1de134 ba784dc e1de134 ba784dc e1de134 ba784dc e1de134 f4952b6 2a9dc4c e1de134 2a9dc4c f4952b6 ba784dc f4952b6 ba784dc f4952b6 ba784dc f4952b6 2a9dc4c f4952b6 2a9dc4c f4952b6 2a9dc4c f4952b6 2a9dc4c f628309 2a9dc4c ba784dc 2a9dc4c | 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | """Python AST symbol, import, inheritance, and call graph extractor.
Nothing here executes user code or writes bytecode to disk. Files that fail
to parse are skipped so the syntax gate owns syntax diagnostics.
"""
from __future__ import annotations
import ast
import os
import stat
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
IGNORED_DIRS: frozenset[str] = frozenset(
{
".git",
".hg",
".svn",
"__pycache__",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".tox",
".nox",
".venv",
"venv",
"env",
"node_modules",
"build",
"dist",
}
)
def _is_ignored(rel_parts: Sequence[str]) -> bool:
for part in rel_parts[:-1]:
if part in IGNORED_DIRS or part.endswith(".egg-info"):
return True
return False
def is_linked_path(path: Path) -> bool:
"""True when the path is a symlink or, on Windows, any reparse point such as a junction.
Since Python 3.12 a Windows junction is no longer reported as a symlink, yet a
directory walk still descends into it. The reparse attribute is the honest test.
"""
if path.is_symlink():
return True
if os.name == "nt":
try:
attributes = path.lstat().st_file_attributes
except OSError:
return False
return bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT)
return False
def hardlinked_file(path: Path) -> bool:
"""True when one file stands under two names (its link count is above one).
A hard link is not a reparse point: both names are real, both lead to the
same bytes on the disk. A copy of one name makes two files out of what the
disk held as one, and a commit through the other name leaves the first at
the old bytes. The tree is honest about links only if it also counts names.
"""
try:
return path.stat().st_nlink > 1
except OSError:
return False
def discover_python_files(workspace: Path) -> List[str]:
"""Return sorted POSIX relative paths for all Python source files in workspace.
Links are pruned rather than followed: a graph that quietly crossed a
junction would describe files that are not part of the workspace. A session
asked to change such a workspace refuses and names the link instead.
"""
root = workspace.resolve()
found: List[str] = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(
d
for d in dirnames
if d not in IGNORED_DIRS
and not d.endswith(".egg-info")
and not is_linked_path(Path(dirpath) / d)
)
rel_dir = Path(dirpath).resolve().relative_to(root)
for filename in sorted(filenames):
if not filename.endswith(".py"):
continue
if is_linked_path(Path(dirpath) / filename):
continue
rel_path = (rel_dir / filename).as_posix() if rel_dir.parts else filename
if not _is_ignored(rel_path.split("/")):
found.append(rel_path)
return sorted(found)
def module_names_for_file(rel_posix: str) -> List[str]:
"""Return candidate dotted module names for a relative Python path."""
parts = [p for p in rel_posix.replace("\\", "/").split("/") if p]
if not parts:
return []
if parts[-1] == "__init__.py":
base_parts = parts[:-1]
elif parts[-1].endswith(".py"):
base_parts = [*parts[:-1], parts[-1][:-3]]
else:
base_parts = parts
candidates: List[str] = []
for start in range(len(base_parts)):
dotted = ".".join(base_parts[start:])
if dotted and dotted not in candidates:
candidates.append(dotted)
if len(base_parts) > 1 and base_parts[0] in ("src", "lib", "python"):
stripped = ".".join(base_parts[1:])
if stripped and stripped not in candidates:
candidates.append(stripped)
return candidates
def importers_of(workspace: Path, files: Sequence[str], target_rel: str) -> List[str]:
"""Return the files whose import statements could bind to the module at target_rel.
This is a naming check over the import lines, not full import resolution: a
surviving file that names a module the target could provide is a candidate for
the break a delete can cause, which is exactly the evidence a delete gate wants.
"""
wanted = set(module_names_for_file(target_rel))
if not wanted:
return []
found: List[str] = []
for rel in files:
if rel == target_rel:
continue
source = _read_source(workspace, rel)
if source is None:
continue
try:
tree = ast.parse(source, filename=rel)
except (SyntaxError, ValueError):
continue
modules, _ = _extract_imports(rel, tree)
hit = False
for name in modules:
if name in wanted or name.rsplit(".", 1)[0] in wanted:
hit = True
break
if not hit:
# The file binds a name the package re-exports from the target.
for dotted in _reexport_dotted_names(workspace, tree):
if dotted in wanted:
hit = True
break
if hit:
found.append(rel)
return found
def build_reverse_index(workspace: Path, files: Sequence[str]) -> Dict[str, Set[str]]:
"""Map every dotted module name to the files whose imports could bind it.
importers_of asks this question one target at a time and parses the whole tree
for each question. A caller that reads the same workspace once and asks about
many files parses every file once here instead, and answers each later question
from the buckets.
"""
index: Dict[str, Set[str]] = {}
for rel in files:
source = _read_source(workspace, rel)
if source is None:
continue
try:
tree = ast.parse(source, filename=rel)
except (SyntaxError, ValueError):
continue
modules, _ = _extract_imports(rel, tree)
buckets = list(modules)
buckets.extend(name.rsplit(".", 1)[0] for name in modules if "." in name)
buckets.extend(_reexport_dotted_names(workspace, tree))
for name in buckets:
if name:
index.setdefault(name, set()).add(rel)
return index
def importers_from_index(index: Dict[str, Set[str]], target_rel: str) -> List[str]:
"""Answer importers_of from an index built once for the workspace."""
wanted = set(module_names_for_file(target_rel))
if not wanted:
return []
found: Set[str] = set()
for name in wanted:
found.update(index.get(name, set()))
found.discard(target_rel)
return sorted(found)
def _read_source(workspace: Path, rel_posix: str) -> Optional[str]:
target = workspace / Path(*rel_posix.replace("\\", "/").split("/"))
if not target.is_file() or target.is_symlink():
return None
try:
# utf-8-sig: a source file that starts with a byte-order mark is still the
# UTF-8 text the compiler would read, and the mark is not part of the code.
return target.read_text(encoding="utf-8-sig")
except (OSError, UnicodeDecodeError):
# A file that is not decodable text carries no syntax tree to extract, and
# guessing it with replacement characters would invent symbols.
return None
def _collect_definitions(
tree: ast.Module,
) -> Tuple[List[str], Dict[str, List[str]], Dict[str, Set[str]]]:
"""Return symbol names, class-to-base-names map, and call map."""
symbols: List[str] = []
bases_by_class: Dict[str, List[str]] = {}
calls_by_symbol: Dict[str, Set[str]] = {}
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
symbols.append(node.name)
calls_by_symbol[node.name] = _called_names(node)
elif isinstance(node, ast.ClassDef):
symbols.append(node.name)
bases_by_class[node.name] = [_expr_name(base) for base in node.bases if _expr_name(base)]
for item in node.body:
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
qualified = f"{node.name}.{item.name}"
symbols.append(qualified)
calls_by_symbol[qualified] = _called_names(item)
return symbols, bases_by_class, calls_by_symbol
def _expr_name(node: ast.AST) -> str:
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Attribute):
prefix = _expr_name(node.value)
return f"{prefix}.{node.attr}" if prefix else node.attr
return ""
def _called_names(func_node: ast.AST) -> Set[str]:
called: Set[str] = set()
for inner in ast.walk(func_node):
if isinstance(inner, ast.Call):
if isinstance(inner.func, ast.Name):
called.add(inner.func.id)
elif isinstance(inner.func, ast.Attribute):
called.add(inner.func.attr)
full = _expr_name(inner.func)
if full:
called.add(full)
return called
def _resolve_relative_module(rel_posix: str, level: int, module: Optional[str]) -> str:
parts = rel_posix.replace("\\", "/").split("/")
package_parts = parts[:-1]
if level > len(package_parts):
base_parts: List[str] = []
else:
base_parts = package_parts[: len(package_parts) - (level - 1)]
if module:
return ".".join([*base_parts, *module.split(".")])
return ".".join(base_parts)
def _module_public_names(workspace: Path, dotted_module: str) -> List[str]:
"""Names a `from module import *` would hand to the importer.
Star imports are an explicit contract when the module writes __all__:
those strings, and only those. Without __all__ the honest expansion is
the module's own top-level public names, since star skips underscored
names and never re-imports a name the module never defined.
"""
rel = dotted_module.replace(".", "/") + ".py"
source = _read_source(workspace, rel)
if source is None:
return []
try:
tree = ast.parse(source, filename=rel)
except (SyntaxError, ValueError):
return []
for node in tree.body:
if isinstance(node, ast.Assign) and any(
isinstance(t, ast.Name) and t.id == "__all__" for t in node.targets
):
if isinstance(node.value, (ast.List, ast.Tuple)):
return [
elt.value
for elt in node.value.elts
if isinstance(elt, ast.Constant) and isinstance(elt.value, str)
]
return []
names: List[str] = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
name = node.name
elif (
isinstance(node, ast.Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], ast.Name)
):
name = node.targets[0].id
else:
continue
if not name.startswith("_"):
names.append(name)
return names
def reexported_names(workspace: Path, init_rel: str) -> Dict[str, List[str]]:
"""External name -> dotted candidates, for a package __init__ that re-exports names.
A package that answers for a function living in another file is ordinary and
honest: the __init__ imports the name from where it stands. A caller binding
to pkg.name never names the file holding the code, so the naming check
follows this table and still credits the file the code lives in.
"""
source = _read_source(workspace, init_rel)
if source is None:
return {}
try:
tree = ast.parse(source, filename=init_rel)
except (SyntaxError, ValueError):
return {}
parts = [p for p in init_rel.replace("\\", "/").split("/") if p]
prefix = ".".join(parts[:-1]) # empty for a package sitting at the workspace root
table: Dict[str, List[str]] = {}
for node in tree.body:
if not isinstance(node, ast.ImportFrom) or node.level != 1:
continue
if node.module:
base = f"{prefix}.{node.module}" if prefix else node.module
elif prefix:
base = prefix # from . import name: name may be a sibling module
else:
continue
for alias in node.names:
if alias.name == "*":
if not node.module:
continue
for public in _module_public_names(workspace, base):
options = table.setdefault(public, [])
dotted = f"{base}.{public}"
if dotted not in options:
options.append(dotted)
continue
key = alias.asname or alias.name
options = table.setdefault(key, [])
# The from-import can name a submodule (pkg.deep) or a name defined
# inside one (pkg.deep.thing), and the two resolve to different files.
for dotted in (base, f"{base}.{alias.name}"):
if dotted not in options:
options.append(dotted)
return table
def _reexport_dotted_names(workspace: Path, tree: ast.Module) -> List[str]:
"""Dotted submodules a file reaches through a package __init__ re-export."""
reached: List[str] = []
for node in ast.walk(tree):
if not isinstance(node, ast.ImportFrom) or node.level > 0 or not node.module:
continue
table = reexported_names(workspace, node.module.replace(".", "/") + "/__init__.py")
for alias in node.names:
if alias.name == "*":
for options in table.values():
for dotted in options:
# The module holding the name is the candidate the naming
# check can match; the name inside it cannot be a file.
for candidate in (dotted.rsplit(".", 1)[0], dotted):
if candidate and candidate not in reached:
reached.append(candidate)
continue
key = alias.asname or alias.name
for dotted in table.get(key, ()):
if dotted not in reached:
reached.append(dotted)
return reached
def _literal_module_name(node: Optional[ast.expr]) -> Optional[str]:
if isinstance(node, ast.Constant) and isinstance(node.value, str) and node.value:
if node.value.startswith("."):
# A relative name handed to import_module needs the package argument
# to be resolved, and that argument is code we do not evaluate.
return None
return node.value
return None
def _extract_imports(
rel_posix: str, tree: ast.Module
) -> Tuple[List[str], Dict[str, Tuple[str, str]]]:
"""Return imported module names and local-alias -> (module, imported_name) map.
A literal name passed to import_module or __import__ is an import written as
a call: the string is as fixed as the one after the import keyword, so the
graph treats it as an edge too. Anything that is not a plain string literal
stays invisible, which is why the graph is a naming check and not a trace.
"""
modules: List[str] = []
alias_map: Dict[str, Tuple[str, str]] = {}
def add_module(name: str) -> None:
if name and name not in modules:
modules.append(name)
for node in ast.walk(tree):
if isinstance(node, ast.Call):
called = node.func
dynamic = None
if isinstance(called, ast.Attribute) and called.attr == "import_module":
dynamic = _literal_module_name(node.args[0] if node.args else None)
elif isinstance(called, ast.Name) and called.id == "__import__":
dynamic = _literal_module_name(node.args[0] if node.args else None)
if dynamic:
add_module(dynamic)
elif isinstance(node, ast.Import):
for alias in node.names:
if alias.name not in modules:
modules.append(alias.name)
local = alias.asname or alias.name.split(".")[0]
alias_map[local] = (alias.name, "")
elif isinstance(node, ast.ImportFrom):
if node.level > 0:
mod_name = _resolve_relative_module(rel_posix, node.level, node.module)
else:
mod_name = node.module or ""
if mod_name and mod_name not in modules:
modules.append(mod_name)
for alias in node.names:
if alias.name == "*":
continue
local = alias.asname or alias.name
if mod_name:
alias_map[local] = (mod_name, alias.name)
# A from-import can pull in a submodule rather than a name,
# and it does so whether or not the importer renames it:
# `from app.core import engine` and `from app.core import
# engine as eng` bind the same file, so both record the edge.
sub_mod = f"{mod_name}.{alias.name}"
if sub_mod not in modules:
modules.append(sub_mod)
return modules, alias_map
def _match_module_file(
module_name: str,
files_by_module: Dict[str, str],
all_files: Sequence[str],
current_file: str,
) -> Optional[str]:
if module_name in files_by_module and files_by_module[module_name] != current_file:
return files_by_module[module_name]
leaf = module_name.split(".")[-1]
for other in all_files:
if other == current_file:
continue
if Path(other).stem == leaf:
return other
return None
def extract_python_graph(
workspace: Path, files: Sequence[str]
) -> Tuple[List[str], List[Tuple[str, str]]]:
"""Extract qualified Python symbols and dependency edges over workspace files."""
normalized_files = [f.replace("\\", "/") for f in files if f]
files_by_module: Dict[str, str] = {}
for rel in normalized_files:
for mod in module_names_for_file(rel):
files_by_module.setdefault(mod, rel)
parsed: Dict[str, ast.Module] = {}
defs_by_file: Dict[str, List[str]] = {}
bases_by_file: Dict[str, Dict[str, List[str]]] = {}
calls_by_file: Dict[str, Dict[str, Set[str]]] = {}
imports_by_file: Dict[str, Tuple[List[str], Dict[str, Tuple[str, str]]]] = {}
symbols: Set[str] = set()
edges: Set[Tuple[str, str]] = set()
for rel in normalized_files:
source = _read_source(workspace, rel)
if source is None:
symbols.add(rel)
continue
try:
tree = ast.parse(source, filename=rel)
except SyntaxError:
symbols.add(rel)
continue
parsed[rel] = tree
names, bases, calls = _collect_definitions(tree)
defs_by_file[rel] = names
bases_by_file[rel] = bases
calls_by_file[rel] = calls
imports_by_file[rel] = _extract_imports(rel, tree)
if names:
for name in names:
symbols.add(f"{rel}::{name}")
else:
symbols.add(rel)
for rel in parsed:
local_names = set(defs_by_file.get(rel, ()))
modules, alias_map = imports_by_file.get(rel, ([], {}))
# File-level import edges
for mod in modules:
target_file = _match_module_file(mod, files_by_module, normalized_files, rel)
if target_file:
edges.add((rel, target_file))
# Re-export edges: a package __init__ can hand a name over to the file
# that defines it, and the caller never names that file itself.
for dotted in _reexport_dotted_names(workspace, parsed[rel]):
target_file = _match_module_file(dotted, files_by_module, normalized_files, rel)
if target_file:
edges.add((rel, target_file))
# Inheritance edges
for cls_name, base_list in bases_by_file.get(rel, {}).items():
src_sym = f"{rel}::{cls_name}"
for base_name in base_list:
short = base_name.split(".")[-1]
if base_name in local_names and base_name != cls_name:
edges.add((src_sym, f"{rel}::{base_name}"))
elif short in alias_map:
mod_name, imported_sym = alias_map[short]
target_file = _match_module_file(mod_name, files_by_module, normalized_files, rel)
if target_file:
sym_name = imported_sym or short
if sym_name in defs_by_file.get(target_file, ()):
edges.add((src_sym, f"{target_file}::{sym_name}"))
else:
edges.add((src_sym, target_file))
# Intra-file and cross-file call edges
for caller, called_set in calls_by_file.get(rel, {}).items():
src_sym = f"{rel}::{caller}"
owner_class = caller.split(".")[0] if "." in caller else ""
for called in called_set:
if called in local_names and called != caller:
edges.add((src_sym, f"{rel}::{called}"))
elif owner_class and f"{owner_class}.{called}" in local_names:
target_method = f"{owner_class}.{called}"
if target_method != caller:
edges.add((src_sym, f"{rel}::{target_method}"))
else:
head = called.split(".")[0]
if head in alias_map:
mod_name, imported_sym = alias_map[head]
target_file = _match_module_file(
mod_name, files_by_module, normalized_files, rel
)
if target_file:
candidate = imported_sym or (
called.split(".", 1)[1] if "." in called else ""
)
if candidate and candidate in defs_by_file.get(target_file, ()):
edges.add((src_sym, f"{target_file}::{candidate}"))
else:
edges.add((src_sym, target_file))
return sorted(symbols), sorted(edges)
|