tailot's picture
Upload folder using huggingface_hub
f628309 verified
Raw History Blame
13.9 kB
"""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 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)
for name in modules:
if name in wanted or name.rsplit(".", 1)[0] in wanted:
found.append(rel)
break
return 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 _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."""
modules: List[str] = []
alias_map: Dict[str, Tuple[str, str]] = {}
for node in ast.walk(tree):
if 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))
# 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)