File size: 13,597 Bytes
2a9dc4c
 
 
 
 
 
 
 
 
 
48f2b75
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
48f2b75
 
 
 
 
 
2a9dc4c
 
 
 
48f2b75
 
 
 
 
2a9dc4c
 
 
 
 
48f2b75
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
e1de134
 
 
 
 
 
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
"""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)
                    if not alias.asname:
                        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)