graphlore 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- graphlore/__init__.py +7 -0
- graphlore/__main__.py +12 -0
- graphlore/agents_md.py +96 -0
- graphlore/algorithms.py +311 -0
- graphlore/apis.py +617 -0
- graphlore/cli.py +133 -0
- graphlore/clients.py +260 -0
- graphlore/config.py +68 -0
- graphlore/embed.py +233 -0
- graphlore/engine.py +379 -0
- graphlore/graph.py +1643 -0
- graphlore/history.py +198 -0
- graphlore/imports.py +581 -0
- graphlore/oauth.py +169 -0
- graphlore/resolve.py +332 -0
- graphlore/review.py +1121 -0
- graphlore/routes.py +1417 -0
- graphlore/scope.py +362 -0
- graphlore/search.py +1070 -0
- graphlore/server.py +8152 -0
- graphlore/spans.py +1254 -0
- graphlore/viewer.html +1649 -0
- graphlore/viz.py +381 -0
- graphlore-0.7.0.dist-info/METADATA +379 -0
- graphlore-0.7.0.dist-info/RECORD +28 -0
- graphlore-0.7.0.dist-info/WHEEL +4 -0
- graphlore-0.7.0.dist-info/entry_points.txt +2 -0
- graphlore-0.7.0.dist-info/licenses/LICENSE +21 -0
graphlore/imports.py
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
"""Import statements read from the source: what each can mean, and when it runs.
|
|
2
|
+
|
|
3
|
+
graphify resolves an import to a graph node by name, which goes wrong when a
|
|
4
|
+
first-party module shares its name with an installed package: ``import yaml``
|
|
5
|
+
(PyYAML) becomes an import of ``pkg/adapters/export/yaml.py``. And an import edge
|
|
6
|
+
does not say whether the statement runs when the module is imported, sits under
|
|
7
|
+
``if TYPE_CHECKING:``, or inside a function — the difference between a cycle that
|
|
8
|
+
breaks start-up and two modules that merely know each other.
|
|
9
|
+
|
|
10
|
+
:class:`ImportChecker` answers both from the importing file's own statements, per
|
|
11
|
+
language, like the extractors in :mod:`graphlore.apis`:
|
|
12
|
+
|
|
13
|
+
* **Python** — stdlib ``ast``: module-level, inside a function (deferred),
|
|
14
|
+
under ``if TYPE_CHECKING:``.
|
|
15
|
+
* **JS / TS** — tree-sitter: a top-level ``import`` / ``export ... from`` /
|
|
16
|
+
``require`` is module-level, an ``import()`` or ``require`` inside a function
|
|
17
|
+
is deferred, ``import type`` is type-only. A relative specifier is resolved
|
|
18
|
+
to its file; a bare one-word specifier is an npm package.
|
|
19
|
+
* **Go, Java, Kotlin, Scala, C#, Rust, Swift** — imports are resolved at
|
|
20
|
+
compile time: always module-level, nothing to read.
|
|
21
|
+
|
|
22
|
+
Anything else is kept and reported as unclassified, unless the graph says more:
|
|
23
|
+
a ``dynamic_import`` relation, or an import edge that leaves a function node.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import ast
|
|
28
|
+
import posixpath
|
|
29
|
+
import re
|
|
30
|
+
from typing import Any, NamedTuple
|
|
31
|
+
|
|
32
|
+
from .apis import _js_internal_source, _strip_quotes
|
|
33
|
+
from .graph import (
|
|
34
|
+
IMPORT_DEFERRED,
|
|
35
|
+
IMPORT_MODULE_LEVEL,
|
|
36
|
+
IMPORT_TYPE_CHECKING,
|
|
37
|
+
IMPORT_UNCLASSIFIED,
|
|
38
|
+
_rel,
|
|
39
|
+
)
|
|
40
|
+
from .spans import _cached_file_analysis, _norm_relpath, _resolve_in_project, _ts_parser_for
|
|
41
|
+
|
|
42
|
+
# When an import statement runs (the values live in graph.py, which tiers cycles
|
|
43
|
+
# by them): at import time; when its function is called; never — it sits under
|
|
44
|
+
# `if TYPE_CHECKING:`; or unknown, the source not being readable as Python.
|
|
45
|
+
MODULE_LEVEL, DEFERRED = IMPORT_MODULE_LEVEL, IMPORT_DEFERRED
|
|
46
|
+
TYPE_CHECKING, UNCLASSIFIED = IMPORT_TYPE_CHECKING, IMPORT_UNCLASSIFIED
|
|
47
|
+
_RUNTIME_RANK = {MODULE_LEVEL: 0, UNCLASSIFIED: 0, DEFERRED: 1, TYPE_CHECKING: 2}
|
|
48
|
+
|
|
49
|
+
# Directory names that are source roots by convention.
|
|
50
|
+
_ROOT_DIR_NAMES = frozenset({"src", "lib", "python", "source", "sources"})
|
|
51
|
+
# A directory holding one of these is the root of an installable distribution.
|
|
52
|
+
_ROOT_MARKERS = ("pyproject.toml", "setup.py", "setup.cfg")
|
|
53
|
+
_TS_TYPE_IMPORT = re.compile(r"^\s*(?:import|export)\s+type\b")
|
|
54
|
+
# The JS family, longest extension first so `.d.ts` is stripped whole.
|
|
55
|
+
_JS_EXTS = (".d.ts", ".tsx", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".ts", ".js")
|
|
56
|
+
# Languages whose imports are resolved at compile time: an import cannot be
|
|
57
|
+
# deferred or conditional, so every one of them is module-level by definition.
|
|
58
|
+
# A C-family `#include` / `#import` is resolved earlier still, by the preprocessor,
|
|
59
|
+
# and a PHP `use` only aliases a name (the file loads on first use, by autoload).
|
|
60
|
+
# Ruby needs nothing: graphify records no file-level import edge for `require`.
|
|
61
|
+
_COMPILED_EXTS = (
|
|
62
|
+
".go", ".java", ".kt", ".kts", ".scala", ".cs", ".rs", ".swift",
|
|
63
|
+
".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm", ".php",
|
|
64
|
+
)
|
|
65
|
+
# How many re-exporting entry files (`index.ts` barrels) a JS/TS import is
|
|
66
|
+
# followed through before the edge counts as contradicted by the source.
|
|
67
|
+
_BARREL_DEPTH = 3
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _Import(NamedTuple):
|
|
71
|
+
line: int
|
|
72
|
+
kind: str # MODULE_LEVEL / DEFERRED / TYPE_CHECKING
|
|
73
|
+
level: int # 0 = absolute, n = number of leading dots
|
|
74
|
+
module: tuple[str, ...] # dotted module path of the statement
|
|
75
|
+
names: tuple[str, ...] # names of a from-import (each may be a submodule)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _is_type_checking_test(test: ast.expr) -> bool:
|
|
79
|
+
"""``TYPE_CHECKING`` or ``typing.TYPE_CHECKING`` (also ``t.TYPE_CHECKING``)."""
|
|
80
|
+
if isinstance(test, ast.Name):
|
|
81
|
+
return test.id == "TYPE_CHECKING"
|
|
82
|
+
return isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _python_imports(src: bytes) -> list[_Import] | None:
|
|
86
|
+
"""Every import statement of a Python file, or None if it does not parse."""
|
|
87
|
+
try:
|
|
88
|
+
tree = ast.parse(src)
|
|
89
|
+
except Exception: # noqa: BLE001 - SyntaxError, ValueError (NUL bytes), RecursionError
|
|
90
|
+
return None
|
|
91
|
+
out: list[_Import] = []
|
|
92
|
+
|
|
93
|
+
def walk(node: ast.AST, kind: str) -> None:
|
|
94
|
+
for child in ast.iter_child_nodes(node):
|
|
95
|
+
if isinstance(child, ast.Import):
|
|
96
|
+
for a in child.names:
|
|
97
|
+
out.append(_Import(child.lineno, kind, 0, tuple(a.name.split(".")), ()))
|
|
98
|
+
elif isinstance(child, ast.ImportFrom):
|
|
99
|
+
module = tuple(child.module.split(".")) if child.module else ()
|
|
100
|
+
names = tuple(a.name for a in child.names if a.name != "*")
|
|
101
|
+
out.append(_Import(child.lineno, kind, child.level or 0, module, names))
|
|
102
|
+
elif isinstance(child, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):
|
|
103
|
+
# A function body runs when called, whatever it sits under.
|
|
104
|
+
walk(child, DEFERRED if kind == MODULE_LEVEL else kind)
|
|
105
|
+
elif isinstance(child, ast.If) and _is_type_checking_test(child.test):
|
|
106
|
+
for stmt in child.body:
|
|
107
|
+
walk(ast.Module(body=[stmt], type_ignores=[]), TYPE_CHECKING)
|
|
108
|
+
for stmt in child.orelse:
|
|
109
|
+
walk(ast.Module(body=[stmt], type_ignores=[]), kind)
|
|
110
|
+
else:
|
|
111
|
+
walk(child, kind)
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
walk(tree, MODULE_LEVEL)
|
|
115
|
+
except RecursionError:
|
|
116
|
+
return None
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# rel path -> (mtime, statements | None); the (path, mtime) scheme of the span cache.
|
|
121
|
+
_IMPORTS_CACHE: dict[str, tuple[float, Any]] = {}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _imports_for_file(rel: str) -> list[_Import] | None:
|
|
125
|
+
"""Import statements of a Python file under PROJECT_DIR; None when unreadable."""
|
|
126
|
+
if not rel.lower().endswith((".py", ".pyi")):
|
|
127
|
+
return None
|
|
128
|
+
return _cached_file_analysis(
|
|
129
|
+
_IMPORTS_CACHE, rel, lambda src, _rel_path: _python_imports(src), lambda: None
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# ---------------------------------------------------------------------------
|
|
134
|
+
# JS / TS (optional tree-sitter backend)
|
|
135
|
+
# ---------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class _JsImport(NamedTuple):
|
|
139
|
+
line: int
|
|
140
|
+
kind: str # MODULE_LEVEL / DEFERRED / TYPE_CHECKING
|
|
141
|
+
specifier: str # './lib/api.js', 'yaml', '@/store'
|
|
142
|
+
# `export … from './x'` / `module.exports = require('./x')`: the file passes
|
|
143
|
+
# on what `./x` defines, so an import of this file reaches `./x` too
|
|
144
|
+
reexport: bool = False
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class JsFile(NamedTuple):
|
|
148
|
+
"""What one JS/TS file imports, binds and calls through a binding."""
|
|
149
|
+
|
|
150
|
+
imports: list[_JsImport]
|
|
151
|
+
# local name -> specifier, for names that stand for a whole module:
|
|
152
|
+
# `import * as ns`, a default import, `const m = require(..)` / `await import(..)`
|
|
153
|
+
bindings: dict[str, str]
|
|
154
|
+
# (line, bound name, property) for every `name.prop(...)` call
|
|
155
|
+
calls: list[tuple[int, str, str]]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _js_function_like(node_type: str) -> bool:
|
|
159
|
+
t = node_type.lower()
|
|
160
|
+
return "function" in t or t == "method_definition"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _js_file(root: Any) -> JsFile:
|
|
164
|
+
imports: list[_JsImport] = []
|
|
165
|
+
bindings: dict[str, str] = {}
|
|
166
|
+
raw_calls: list[tuple[int, str, str]] = []
|
|
167
|
+
|
|
168
|
+
def text(node: Any) -> str:
|
|
169
|
+
return node.text.decode("utf-8", "replace")
|
|
170
|
+
|
|
171
|
+
def dynamic_source(call: Any) -> str | None:
|
|
172
|
+
"""Specifier of `require('x')` / `import('x')`, else None."""
|
|
173
|
+
fn = call.child_by_field_name("function")
|
|
174
|
+
args = call.child_by_field_name("arguments")
|
|
175
|
+
if fn is None or args is None or not (fn.type == "import" or fn.text == b"require"):
|
|
176
|
+
return None
|
|
177
|
+
for a in args.named_children:
|
|
178
|
+
if "string" in a.type:
|
|
179
|
+
return _strip_quotes(text(a)) or None
|
|
180
|
+
return None
|
|
181
|
+
|
|
182
|
+
def bind_clause(stmt: Any, source: str) -> None:
|
|
183
|
+
stack = [c for c in stmt.named_children if c.type == "import_clause"]
|
|
184
|
+
while stack:
|
|
185
|
+
n = stack.pop()
|
|
186
|
+
if n.type == "namespace_import": # import * as ns
|
|
187
|
+
for c in n.named_children:
|
|
188
|
+
if c.type == "identifier":
|
|
189
|
+
bindings[text(c)] = source
|
|
190
|
+
elif n.type == "identifier": # default import
|
|
191
|
+
bindings[text(n)] = source
|
|
192
|
+
elif n.type != "named_imports": # { a, b } bind symbols, not the module
|
|
193
|
+
stack.extend(n.named_children)
|
|
194
|
+
|
|
195
|
+
def walk(node: Any, in_function: bool) -> None:
|
|
196
|
+
for child in node.named_children:
|
|
197
|
+
t = child.type
|
|
198
|
+
line = child.start_point[0] + 1
|
|
199
|
+
if t in ("import_statement", "export_statement"):
|
|
200
|
+
src = child.child_by_field_name("source")
|
|
201
|
+
if src is not None:
|
|
202
|
+
source = _strip_quotes(text(src))
|
|
203
|
+
kind = TYPE_CHECKING if _TS_TYPE_IMPORT.match(text(child)) else MODULE_LEVEL
|
|
204
|
+
imports.append(_JsImport(line, kind, source, t == "export_statement"))
|
|
205
|
+
if t == "import_statement" and kind != TYPE_CHECKING:
|
|
206
|
+
bind_clause(child, source)
|
|
207
|
+
continue
|
|
208
|
+
if t == "call_expression":
|
|
209
|
+
dynamic = dynamic_source(child)
|
|
210
|
+
if dynamic is not None:
|
|
211
|
+
left = (node.child_by_field_name("left")
|
|
212
|
+
if node.type == "assignment_expression" else None)
|
|
213
|
+
imports.append(_JsImport(
|
|
214
|
+
line, DEFERRED if in_function else MODULE_LEVEL, dynamic,
|
|
215
|
+
left is not None
|
|
216
|
+
and text(left).startswith(("module.exports", "exports")),
|
|
217
|
+
))
|
|
218
|
+
continue
|
|
219
|
+
fn = child.child_by_field_name("function")
|
|
220
|
+
if fn is not None and fn.type == "member_expression":
|
|
221
|
+
obj = fn.child_by_field_name("object")
|
|
222
|
+
prop = fn.child_by_field_name("property")
|
|
223
|
+
if obj is not None and prop is not None and obj.type == "identifier":
|
|
224
|
+
raw_calls.append((line, text(obj), text(prop)))
|
|
225
|
+
if t == "variable_declarator": # const m = require('x') / await import('x')
|
|
226
|
+
name = child.child_by_field_name("name")
|
|
227
|
+
value = child.child_by_field_name("value")
|
|
228
|
+
if value is not None and value.type == "await_expression":
|
|
229
|
+
value = next(iter(value.named_children), None)
|
|
230
|
+
if (name is not None and name.type == "identifier" and value is not None
|
|
231
|
+
and value.type == "call_expression"
|
|
232
|
+
and (bound := dynamic_source(value)) is not None):
|
|
233
|
+
bindings[text(name)] = bound
|
|
234
|
+
walk(child, in_function or _js_function_like(t))
|
|
235
|
+
|
|
236
|
+
walk(root, False)
|
|
237
|
+
return JsFile(imports, bindings, [c for c in raw_calls if c[1] in bindings])
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# rel path -> (mtime, JsFile | None); the (path, mtime) scheme of the span cache.
|
|
241
|
+
_JS_CACHE: dict[str, tuple[float, Any]] = {}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _js_for_file(rel: str) -> JsFile | None:
|
|
245
|
+
"""Imports, module bindings and member calls of a JS/TS file; None when the
|
|
246
|
+
tree-sitter backend is absent or the file does not parse."""
|
|
247
|
+
if not rel.lower().endswith(_JS_EXTS):
|
|
248
|
+
return None
|
|
249
|
+
|
|
250
|
+
def compute(src: bytes, path: str) -> JsFile | None:
|
|
251
|
+
parser, _lang = _ts_parser_for(path)
|
|
252
|
+
if parser is None:
|
|
253
|
+
return None
|
|
254
|
+
try:
|
|
255
|
+
return _js_file(parser.parse(src).root_node)
|
|
256
|
+
except Exception: # noqa: BLE001 - grammar drift / recursion: no visibility
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
return _cached_file_analysis(_JS_CACHE, rel, compute, lambda: None)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _js_module_forms(path: str) -> set[str]:
|
|
263
|
+
"""The extension-less ways a specifier can name a file: ``lib/api`` for
|
|
264
|
+
``lib/api.ts``, and both ``lib/store/index`` and ``lib/store`` for an index file."""
|
|
265
|
+
low = path.lower()
|
|
266
|
+
base = next((path[: -len(ext)] for ext in _JS_EXTS if low.endswith(ext)), path)
|
|
267
|
+
forms = {base}
|
|
268
|
+
if base.endswith("/index"):
|
|
269
|
+
forms.add(base[: -len("/index")])
|
|
270
|
+
elif base == "index":
|
|
271
|
+
forms.add("") # the project root's own index: `require('../..')`
|
|
272
|
+
return forms
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _js_relative_base(specifier: str, importer: str) -> str:
|
|
276
|
+
"""The project-relative path a relative specifier points at ("" for the root)."""
|
|
277
|
+
base = posixpath.normpath(posixpath.join(posixpath.dirname(importer), specifier))
|
|
278
|
+
return "" if base == "." else base
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _js_can_mean(specifier: str, importer: str, target: str) -> bool:
|
|
282
|
+
"""Can ``specifier``, written in ``importer``, name the file ``target``?"""
|
|
283
|
+
forms = _js_module_forms(target)
|
|
284
|
+
if specifier.startswith("."):
|
|
285
|
+
base = _js_relative_base(specifier, importer)
|
|
286
|
+
# `./x.js` in TypeScript source names `x.ts`: compare without extensions
|
|
287
|
+
return base == target or bool(_js_module_forms(base) & forms)
|
|
288
|
+
if _js_internal_source(specifier): # '/abs', '@/alias', '~/alias', '#subpath'
|
|
289
|
+
path = specifier.lstrip("/#~@").lstrip("/")
|
|
290
|
+
wanted = _js_module_forms(path)
|
|
291
|
+
return any(f == w or f.endswith("/" + w) for f in forms for w in wanted)
|
|
292
|
+
segments = specifier.split("/")
|
|
293
|
+
if len(segments) == 1:
|
|
294
|
+
# One bare word is an npm package — unless the project root, or a source
|
|
295
|
+
# root directly under it (a tsconfig `baseUrl`), holds a module of that name.
|
|
296
|
+
return any(
|
|
297
|
+
f == specifier or (
|
|
298
|
+
f.endswith("/" + specifier)
|
|
299
|
+
and f[: -len(specifier) - 1].lower() in _ROOT_DIR_NAMES
|
|
300
|
+
)
|
|
301
|
+
for f in forms
|
|
302
|
+
)
|
|
303
|
+
# `@app/utils`, `components/Button`: a scoped package or a tsconfig path
|
|
304
|
+
# alias. Which one cannot be told without the config, so the edge is kept
|
|
305
|
+
# whenever the last segment names the target.
|
|
306
|
+
last = next(iter(_js_module_forms(segments[-1])))
|
|
307
|
+
return any(f.rsplit("/", 1)[-1] == last for f in forms)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _module_parts(path: str) -> tuple[str, ...] | None:
|
|
311
|
+
"""``a/b/c.py`` -> (a, b, c); ``a/b/__init__.py`` -> (a, b). None if not Python."""
|
|
312
|
+
if not path.lower().endswith((".py", ".pyi")):
|
|
313
|
+
return None
|
|
314
|
+
parts = path.rsplit(".", 1)[0].split("/")
|
|
315
|
+
if parts[-1] == "__init__":
|
|
316
|
+
parts = parts[:-1]
|
|
317
|
+
return tuple(parts)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class ImportChecker:
|
|
321
|
+
"""Classifies file-level import edges against the importing file's source.
|
|
322
|
+
|
|
323
|
+
One instance per tool call: it memoizes the directory lookups (is this a
|
|
324
|
+
package, is this a distribution root) that the edges of one graph repeat.
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
def __init__(self) -> None:
|
|
328
|
+
self._is_package: dict[str, bool] = {}
|
|
329
|
+
self._is_root: dict[str, bool] = {}
|
|
330
|
+
self._is_file: dict[str, bool] = {}
|
|
331
|
+
self._reexports: dict[tuple[str, str], bool] = {}
|
|
332
|
+
self._lines: dict[str, list[str]] = {}
|
|
333
|
+
self.rejected: list[dict[str, str]] = []
|
|
334
|
+
self.unclassified = 0
|
|
335
|
+
|
|
336
|
+
def _exists(self, rel: str) -> bool:
|
|
337
|
+
got = self._is_file.get(rel)
|
|
338
|
+
if got is None:
|
|
339
|
+
full = _resolve_in_project(rel)
|
|
340
|
+
got = self._is_file[rel] = full is not None and full.is_file()
|
|
341
|
+
return got
|
|
342
|
+
|
|
343
|
+
def _js_entries(self, specifier: str, importer: str, target: str) -> list[str]:
|
|
344
|
+
"""Files other than ``target`` that ``specifier`` names from ``importer``.
|
|
345
|
+
|
|
346
|
+
A relative specifier names one module or a directory's index. An alias or
|
|
347
|
+
a bare path (``@/client``, ``app/store``) cannot be resolved without the
|
|
348
|
+
build config, so the index files of the directories above ``target`` are
|
|
349
|
+
tried against it.
|
|
350
|
+
"""
|
|
351
|
+
found: list[str] = []
|
|
352
|
+
if specifier.startswith("."):
|
|
353
|
+
for stem in _js_module_forms(_js_relative_base(specifier, importer)):
|
|
354
|
+
for ext in _JS_EXTS:
|
|
355
|
+
found.append(stem + ext)
|
|
356
|
+
found.append(f"{stem}/index{ext}" if stem else f"index{ext}")
|
|
357
|
+
else:
|
|
358
|
+
d = posixpath.dirname(target)
|
|
359
|
+
while True:
|
|
360
|
+
found += [f"{d}/index{ext}" if d else f"index{ext}" for ext in _JS_EXTS]
|
|
361
|
+
if not d:
|
|
362
|
+
break
|
|
363
|
+
d = posixpath.dirname(d)
|
|
364
|
+
return [
|
|
365
|
+
f for f in dict.fromkeys(found)
|
|
366
|
+
if f != target and self._exists(f)
|
|
367
|
+
and (specifier.startswith(".") or _js_can_mean(specifier, importer, f))
|
|
368
|
+
]
|
|
369
|
+
|
|
370
|
+
def _js_means(self, specifier: str, importer: str, target: str) -> bool:
|
|
371
|
+
"""Can ``specifier`` reach ``target``: by naming it, or by naming a module
|
|
372
|
+
that re-exports from it.
|
|
373
|
+
|
|
374
|
+
graphify links ``import { CreateDto } from './dto'`` to the file that
|
|
375
|
+
defines ``CreateDto``, not to ``dto/index.ts`` which re-exports it. The
|
|
376
|
+
statement still loads that file, so the edge holds. Only re-exports are
|
|
377
|
+
followed (``export … from``, ``module.exports = require(…)``), through at
|
|
378
|
+
most ``_BARREL_DEPTH`` files: a file the entry merely imports is not what
|
|
379
|
+
the importer asked for.
|
|
380
|
+
"""
|
|
381
|
+
if _js_can_mean(specifier, importer, target):
|
|
382
|
+
return True
|
|
383
|
+
return any(self._js_reexports(entry, target, _BARREL_DEPTH)
|
|
384
|
+
for entry in self._js_entries(specifier, importer, target))
|
|
385
|
+
|
|
386
|
+
def _js_reexports(self, entry: str, target: str, depth: int) -> bool:
|
|
387
|
+
key = (entry, target)
|
|
388
|
+
got = self._reexports.get(key)
|
|
389
|
+
if got is None:
|
|
390
|
+
self._reexports[key] = False # a re-export cycle ends here
|
|
391
|
+
js = _js_for_file(entry)
|
|
392
|
+
got = js is not None and any(
|
|
393
|
+
i.reexport and (
|
|
394
|
+
_js_can_mean(i.specifier, entry, target)
|
|
395
|
+
or (depth > 1 and any(
|
|
396
|
+
self._js_reexports(nxt, target, depth - 1)
|
|
397
|
+
for nxt in self._js_entries(i.specifier, entry, target)))
|
|
398
|
+
)
|
|
399
|
+
for i in js.imports
|
|
400
|
+
)
|
|
401
|
+
self._reexports[key] = got
|
|
402
|
+
return got
|
|
403
|
+
|
|
404
|
+
def _package(self, d: str) -> bool:
|
|
405
|
+
got = self._is_package.get(d)
|
|
406
|
+
if got is None:
|
|
407
|
+
prefix = f"{d}/" if d else ""
|
|
408
|
+
got = self._is_package[d] = (
|
|
409
|
+
self._exists(prefix + "__init__.py") or self._exists(prefix + "__init__.pyi")
|
|
410
|
+
)
|
|
411
|
+
return got
|
|
412
|
+
|
|
413
|
+
def _root_like(self, d: str, importer: str) -> bool:
|
|
414
|
+
"""Could ``d`` be on ``sys.path`` when ``importer`` runs?
|
|
415
|
+
|
|
416
|
+
The project root, a conventional source directory, a distribution root, or
|
|
417
|
+
a directory the importing file lives under (a script's own directory and
|
|
418
|
+
the working directories above it).
|
|
419
|
+
"""
|
|
420
|
+
if not d:
|
|
421
|
+
return True
|
|
422
|
+
if importer.startswith(d + "/") or d.rsplit("/", 1)[-1].lower() in _ROOT_DIR_NAMES:
|
|
423
|
+
return True
|
|
424
|
+
got = self._is_root.get(d)
|
|
425
|
+
if got is None:
|
|
426
|
+
got = self._is_root[d] = any(self._exists(f"{d}/{m}") for m in _ROOT_MARKERS)
|
|
427
|
+
return got
|
|
428
|
+
|
|
429
|
+
def _can_mean(self, stmt: _Import, importer: str, target: tuple[str, ...]) -> bool:
|
|
430
|
+
"""Can this statement, written in ``importer``, import the module ``target``?"""
|
|
431
|
+
# Importing a.b.c imports a and a.b on the way; a from-import may name a
|
|
432
|
+
# submodule. So the statement reaches every prefix, and one level below.
|
|
433
|
+
reach = [stmt.module[:i] for i in range(1, len(stmt.module) + 1)]
|
|
434
|
+
reach += [(*stmt.module, n) for n in stmt.names]
|
|
435
|
+
if stmt.level:
|
|
436
|
+
base = importer.split("/")[:-1]
|
|
437
|
+
if stmt.level - 1 > len(base):
|
|
438
|
+
return False
|
|
439
|
+
base = base[: len(base) - (stmt.level - 1)]
|
|
440
|
+
reach.append(()) # `from . import x` also names the package itself
|
|
441
|
+
return any(tuple(base) + r == target for r in reach)
|
|
442
|
+
for dotted in reach:
|
|
443
|
+
n = len(dotted)
|
|
444
|
+
if not n or len(target) < n or target[-n:] != dotted:
|
|
445
|
+
continue
|
|
446
|
+
root = "/".join(target[:-n])
|
|
447
|
+
# The directory the dotted path starts in must be importable from: a
|
|
448
|
+
# package is not (its modules are reached as pkg.mod, never as mod),
|
|
449
|
+
# and a bare one-word import needs more than that — it is what an
|
|
450
|
+
# installed package looks like.
|
|
451
|
+
if self._package(root):
|
|
452
|
+
continue
|
|
453
|
+
if n > 1 or self._root_like(root, importer):
|
|
454
|
+
return True
|
|
455
|
+
return False
|
|
456
|
+
|
|
457
|
+
def resolve(
|
|
458
|
+
self, importer: str, level: int, dotted: tuple[str, ...],
|
|
459
|
+
by_parts: dict[tuple[str, ...], str], by_last: dict[str, list[tuple[str, ...]]],
|
|
460
|
+
) -> str | None:
|
|
461
|
+
"""The first-party file a dotted module path names from ``importer``.
|
|
462
|
+
|
|
463
|
+
``by_parts`` maps a file's module parts to the file and ``by_last`` indexes
|
|
464
|
+
those parts by their last segment. None when no file, or more than one,
|
|
465
|
+
can be meant — the same root rules as :meth:`kind`.
|
|
466
|
+
"""
|
|
467
|
+
if not dotted:
|
|
468
|
+
return None
|
|
469
|
+
if level:
|
|
470
|
+
base = importer.split("/")[:-1]
|
|
471
|
+
if level - 1 > len(base):
|
|
472
|
+
return None
|
|
473
|
+
return by_parts.get(tuple(base[: len(base) - (level - 1)]) + dotted)
|
|
474
|
+
n = len(dotted)
|
|
475
|
+
found: list[str] = []
|
|
476
|
+
for parts in by_last.get(dotted[-1], ()):
|
|
477
|
+
if len(parts) < n or parts[-n:] != dotted:
|
|
478
|
+
continue
|
|
479
|
+
root = "/".join(parts[:-n])
|
|
480
|
+
if not self._package(root) and (n > 1 or self._root_like(root, importer)):
|
|
481
|
+
found.append(by_parts[parts])
|
|
482
|
+
return found[0] if len(found) == 1 else None
|
|
483
|
+
|
|
484
|
+
def kind(self, importer: str, imported: str, edge: dict) -> str | None:
|
|
485
|
+
"""When the import behind a file-level edge runs, or None for a false edge.
|
|
486
|
+
|
|
487
|
+
None means the importing file's own statements cannot mean ``imported``:
|
|
488
|
+
the resolver matched a name. Edges this cannot judge (a language it does
|
|
489
|
+
not read, source missing or unparseable) are kept as ``UNCLASSIFIED``.
|
|
490
|
+
"""
|
|
491
|
+
importer, imported = _norm_relpath(importer), _norm_relpath(imported)
|
|
492
|
+
carried = edge.get("runs")
|
|
493
|
+
if carried in (MODULE_LEVEL, DEFERRED, TYPE_CHECKING):
|
|
494
|
+
# the native engine read this statement and resolved its module by
|
|
495
|
+
# path, not by name: nothing for the source check to correct
|
|
496
|
+
return str(carried)
|
|
497
|
+
if _rel(edge) == "dynamic_import":
|
|
498
|
+
return DEFERRED
|
|
499
|
+
low = importer.lower()
|
|
500
|
+
if low.endswith(_COMPILED_EXTS):
|
|
501
|
+
return MODULE_LEVEL # resolved at compile time: never deferred
|
|
502
|
+
kinds: list[str]
|
|
503
|
+
if low.endswith(_JS_EXTS):
|
|
504
|
+
js = _js_for_file(importer)
|
|
505
|
+
if js is None or not js.imports:
|
|
506
|
+
# no tree-sitter backend (or nothing parsed): the line still says
|
|
507
|
+
# whether a TypeScript import is type-only
|
|
508
|
+
if _TS_TYPE_IMPORT.match(self._line(importer, edge)):
|
|
509
|
+
return TYPE_CHECKING
|
|
510
|
+
self.unclassified += 1
|
|
511
|
+
return UNCLASSIFIED
|
|
512
|
+
kinds = [i.kind for i in js.imports
|
|
513
|
+
if self._js_means(i.specifier, importer, imported)]
|
|
514
|
+
else:
|
|
515
|
+
stmts = _imports_for_file(importer)
|
|
516
|
+
if stmts is None:
|
|
517
|
+
self.unclassified += 1
|
|
518
|
+
return UNCLASSIFIED
|
|
519
|
+
target = _module_parts(imported)
|
|
520
|
+
kinds = (
|
|
521
|
+
[s.kind for s in stmts if self._can_mean(s, importer, target)]
|
|
522
|
+
if target else []
|
|
523
|
+
)
|
|
524
|
+
if not kinds:
|
|
525
|
+
self.rejected.append({
|
|
526
|
+
"from_file": importer, "to_file": imported,
|
|
527
|
+
"site": f"{importer}:{edge.get('source_location')}"
|
|
528
|
+
if edge.get("source_location") else importer,
|
|
529
|
+
})
|
|
530
|
+
return None
|
|
531
|
+
# One edge may stand for several statements (the graph keeps one per pair
|
|
532
|
+
# of nodes): the one that runs earliest decides.
|
|
533
|
+
return min(kinds, key=lambda k: _RUNTIME_RANK[k])
|
|
534
|
+
|
|
535
|
+
def reaches(self, importer: str, imported: str) -> bool | None:
|
|
536
|
+
"""Can any import statement in ``importer``'s own source mean ``imported``?
|
|
537
|
+
|
|
538
|
+
For a file whose imports the graph did not record: False when the source
|
|
539
|
+
was read and none of its statements can import that file (a script that
|
|
540
|
+
imports only the standard library imports nothing of the project). None
|
|
541
|
+
when it cannot tell — a language it does not read, a compiled language
|
|
542
|
+
(imports resolved by the build), missing or unparseable source.
|
|
543
|
+
"""
|
|
544
|
+
importer, imported = _norm_relpath(importer), _norm_relpath(imported)
|
|
545
|
+
low = importer.lower()
|
|
546
|
+
if low.endswith(_COMPILED_EXTS):
|
|
547
|
+
return None
|
|
548
|
+
if low.endswith(_JS_EXTS):
|
|
549
|
+
js = _js_for_file(importer)
|
|
550
|
+
if js is None:
|
|
551
|
+
return None
|
|
552
|
+
return any(self._js_means(i.specifier, importer, imported) for i in js.imports)
|
|
553
|
+
stmts = _imports_for_file(importer)
|
|
554
|
+
target = _module_parts(imported)
|
|
555
|
+
if stmts is None or target is None:
|
|
556
|
+
return None
|
|
557
|
+
return any(self._can_mean(st, importer, target) for st in stmts)
|
|
558
|
+
|
|
559
|
+
def resolve_js(self, importer: str, specifier: str, files: set[str]) -> str | None:
|
|
560
|
+
"""The one file of ``files`` a JS/TS specifier names from ``importer``."""
|
|
561
|
+
found = [f for f in files if _js_can_mean(specifier, importer, f)]
|
|
562
|
+
return found[0] if len(found) == 1 else None
|
|
563
|
+
|
|
564
|
+
def _line(self, rel: str, edge: dict) -> str:
|
|
565
|
+
"""Source text of the line an edge was recorded at ("" when unavailable)."""
|
|
566
|
+
loc = str(edge.get("source_location") or "").lstrip("Ll")
|
|
567
|
+
digits = "".join(ch for ch in loc.split("-")[0] if ch.isdigit())
|
|
568
|
+
if not digits:
|
|
569
|
+
return ""
|
|
570
|
+
lines = self._lines.get(rel)
|
|
571
|
+
if lines is None:
|
|
572
|
+
lines = []
|
|
573
|
+
full = _resolve_in_project(rel)
|
|
574
|
+
if full is not None:
|
|
575
|
+
try:
|
|
576
|
+
lines = full.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
577
|
+
except OSError:
|
|
578
|
+
lines = []
|
|
579
|
+
self._lines[rel] = lines
|
|
580
|
+
n = int(digits)
|
|
581
|
+
return lines[n - 1] if 0 < n <= len(lines) else ""
|