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/embed.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""The optional dense tier of the built-in search: static embeddings.
|
|
2
|
+
|
|
3
|
+
A model2vec static model (``minishlab/potion-code-16M-v2`` by default, the one
|
|
4
|
+
semble 0.7 uses, so the Hugging Face cache is shared) turns each chunk into a
|
|
5
|
+
vector; similarity is a dot product of L2-normalised rows. Everything here is
|
|
6
|
+
optional: ``model2vec`` and ``numpy`` come from the ``[embed]`` extra and are
|
|
7
|
+
imported inside functions, and every failure — the extra missing, the model not
|
|
8
|
+
downloadable, ``GRAPHLORE_OFFLINE`` with no cached copy — is a ``(None, reason)``
|
|
9
|
+
the caller reports, never an exception.
|
|
10
|
+
|
|
11
|
+
Vectors are keyed by a hash of the model id and the embedded text, so editing a
|
|
12
|
+
file re-embeds only the definitions whose text changed. They can be kept on disk
|
|
13
|
+
under the user cache directory (``GRAPHLORE_CACHE_DIR``), never in the project.
|
|
14
|
+
|
|
15
|
+
Depends only on :mod:`graphlore.config`.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import os
|
|
21
|
+
import threading
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from . import config
|
|
26
|
+
|
|
27
|
+
DEFAULT_MODEL = "minishlab/potion-code-16M-v2"
|
|
28
|
+
# Characters of a chunk that are embedded. A static model averages token vectors,
|
|
29
|
+
# so the head of a long body carries its meaning; the rest only costs time.
|
|
30
|
+
_EMBED_MAX_CHARS = 4000
|
|
31
|
+
# Above this many chunks the dense tier is off for the project (about 100 MB of
|
|
32
|
+
# float32 vectors at 256 dimensions) and the reply says so.
|
|
33
|
+
EMBED_MAX_CHUNKS = 100_000
|
|
34
|
+
_OFF = frozenset({"off", "none", "0", "false", "no"})
|
|
35
|
+
|
|
36
|
+
# spec -> (model or None, reason it is None). Failures are cached too: a model that
|
|
37
|
+
# cannot be downloaded would otherwise cost a network timeout on every call.
|
|
38
|
+
_MODEL_CACHE: dict[tuple[str, bool], tuple[Any, str]] = {}
|
|
39
|
+
_MODEL_LOCK = threading.Lock()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def model_spec() -> str:
|
|
43
|
+
"""``GRAPHLORE_EMBED_MODEL``: a Hugging Face repo id, a local directory, or
|
|
44
|
+
``off``. Default: :data:`DEFAULT_MODEL`."""
|
|
45
|
+
return (config.env("EMBED_MODEL", "") or "").strip() or DEFAULT_MODEL
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def dense_wanted() -> bool:
|
|
49
|
+
return model_spec().lower() not in _OFF
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# How to get the model onto a machine before it is needed; quoted in replies that
|
|
53
|
+
# ran without the dense tier because the model could not be loaded.
|
|
54
|
+
MODEL_PREFETCH_NOTE = (
|
|
55
|
+
"To fetch it ahead of time: python -c \"from model2vec import StaticModel; "
|
|
56
|
+
f"StaticModel.from_pretrained('{DEFAULT_MODEL}')\" — then copy "
|
|
57
|
+
"~/.cache/huggingface to a machine without network access, or set "
|
|
58
|
+
"GRAPHLORE_EMBED_MODEL to a local copy of the model."
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _load_model(spec: str) -> tuple[Any, str]:
|
|
63
|
+
"""Load the static model, or ``(None, why not)``. Cached per (spec, offline)."""
|
|
64
|
+
key = (spec, config.offline())
|
|
65
|
+
with _MODEL_LOCK:
|
|
66
|
+
cached = _MODEL_CACHE.get(key)
|
|
67
|
+
if cached is not None:
|
|
68
|
+
return cached
|
|
69
|
+
result = _load_model_uncached(spec)
|
|
70
|
+
_MODEL_CACHE[key] = result
|
|
71
|
+
return result
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _load_model_uncached(spec: str) -> tuple[Any, str]:
|
|
75
|
+
config.export_offline_env() # before the import: huggingface_hub reads it then
|
|
76
|
+
try:
|
|
77
|
+
import numpy # noqa: F401
|
|
78
|
+
from model2vec import StaticModel
|
|
79
|
+
except ImportError:
|
|
80
|
+
return None, (
|
|
81
|
+
"the dense tier needs the optional [embed] extra (model2vec, numpy): "
|
|
82
|
+
"pip install 'graphlore[embed]'"
|
|
83
|
+
)
|
|
84
|
+
try:
|
|
85
|
+
try:
|
|
86
|
+
model = StaticModel.from_pretrained(spec, force_download=False)
|
|
87
|
+
except TypeError: # a model2vec without the keyword
|
|
88
|
+
model = StaticModel.from_pretrained(spec)
|
|
89
|
+
except Exception as exc: # noqa: BLE001 - any load failure degrades to BM25 only
|
|
90
|
+
why = f"{type(exc).__name__}: {str(exc).strip()[:200]}"
|
|
91
|
+
if config.offline():
|
|
92
|
+
return None, (
|
|
93
|
+
f"embedding model {spec} is not in the local Hugging Face cache and "
|
|
94
|
+
f"GRAPHLORE_OFFLINE is set ({why}). " + MODEL_PREFETCH_NOTE
|
|
95
|
+
)
|
|
96
|
+
return None, f"embedding model {spec} could not be loaded ({why}). " + MODEL_PREFETCH_NOTE
|
|
97
|
+
return model, ""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def text_key(spec: str, text: str) -> bytes:
|
|
101
|
+
"""The cache key of one embedded text under one model."""
|
|
102
|
+
h = hashlib.blake2b(digest_size=16)
|
|
103
|
+
h.update(spec.encode("utf-8", "replace"))
|
|
104
|
+
h.update(b"\0")
|
|
105
|
+
h.update(text[:_EMBED_MAX_CHARS].encode("utf-8", "replace"))
|
|
106
|
+
return h.digest()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _encode(model: Any, texts: list[str]) -> Any:
|
|
110
|
+
"""Rows of L2-normalised float32 vectors, one per text."""
|
|
111
|
+
import numpy as np
|
|
112
|
+
|
|
113
|
+
vecs = np.asarray(
|
|
114
|
+
model.encode([t[:_EMBED_MAX_CHARS] for t in texts]), dtype=np.float32
|
|
115
|
+
)
|
|
116
|
+
if vecs.ndim != 2:
|
|
117
|
+
vecs = vecs.reshape(len(texts), -1)
|
|
118
|
+
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
|
|
119
|
+
norms[norms == 0] = 1.0
|
|
120
|
+
return vecs / norms
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _cache_root() -> Path | None:
|
|
124
|
+
"""Where vectors are kept between runs, or None when disabled
|
|
125
|
+
(``GRAPHLORE_CACHE_DIR=off``)."""
|
|
126
|
+
raw = (config.env("CACHE_DIR", "") or "").strip()
|
|
127
|
+
if raw.lower() in _OFF:
|
|
128
|
+
return None
|
|
129
|
+
if raw:
|
|
130
|
+
return Path(raw).expanduser()
|
|
131
|
+
base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
|
|
132
|
+
return Path(base) / "graphlore"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class VectorStore:
|
|
136
|
+
"""Vectors of chunk texts for one project and one model, by text hash.
|
|
137
|
+
|
|
138
|
+
``vectors_for(keys, texts)`` embeds the texts it has not seen and returns a
|
|
139
|
+
matrix in key order. ``save(live)`` keeps the vectors of the live keys on disk
|
|
140
|
+
(atomic replace; any failure is ignored: the cache only saves time).
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
def __init__(self, model: Any, spec: str, project: str) -> None:
|
|
144
|
+
self.model = model
|
|
145
|
+
self.spec = spec
|
|
146
|
+
self.dim = 0
|
|
147
|
+
self._vecs: dict[bytes, Any] = {}
|
|
148
|
+
self._dirty = False
|
|
149
|
+
self._path: Path | None = None
|
|
150
|
+
root = _cache_root()
|
|
151
|
+
if root is not None:
|
|
152
|
+
pid = hashlib.blake2b(project.encode("utf-8", "replace"), digest_size=8).hexdigest()
|
|
153
|
+
mid = hashlib.blake2b(spec.encode("utf-8", "replace"), digest_size=6).hexdigest()
|
|
154
|
+
self._path = root / pid / f"vectors-{mid}.npz"
|
|
155
|
+
self._load()
|
|
156
|
+
|
|
157
|
+
def _load(self) -> None:
|
|
158
|
+
import numpy as np
|
|
159
|
+
|
|
160
|
+
if self._path is None or not self._path.is_file():
|
|
161
|
+
return
|
|
162
|
+
try:
|
|
163
|
+
with np.load(self._path, allow_pickle=False) as data:
|
|
164
|
+
keys = data["keys"]
|
|
165
|
+
mat = data["vectors"].astype(np.float32)
|
|
166
|
+
except Exception: # noqa: BLE001 - a corrupt cache is a cold cache
|
|
167
|
+
return
|
|
168
|
+
if keys.ndim != 1 or mat.ndim != 2 or len(keys) != len(mat):
|
|
169
|
+
return
|
|
170
|
+
self.dim = int(mat.shape[1])
|
|
171
|
+
for k, row in zip(keys.tolist(), mat, strict=False):
|
|
172
|
+
self._vecs[bytes(k)] = row
|
|
173
|
+
|
|
174
|
+
def __len__(self) -> int:
|
|
175
|
+
return len(self._vecs)
|
|
176
|
+
|
|
177
|
+
def vectors_for(self, keys: list[bytes], texts: list[str]) -> tuple[Any, int]:
|
|
178
|
+
"""(matrix in key order, how many texts were newly embedded)."""
|
|
179
|
+
import numpy as np
|
|
180
|
+
|
|
181
|
+
missing = [(k, t) for k, t in zip(keys, texts, strict=True) if k not in self._vecs]
|
|
182
|
+
if missing:
|
|
183
|
+
new = _encode(self.model, [t for _k, t in missing])
|
|
184
|
+
self.dim = int(new.shape[1])
|
|
185
|
+
for (k, _t), row in zip(missing, new, strict=True):
|
|
186
|
+
self._vecs[k] = row
|
|
187
|
+
self._dirty = True
|
|
188
|
+
if not keys:
|
|
189
|
+
return np.zeros((0, self.dim or 1), dtype=np.float32), 0
|
|
190
|
+
return np.stack([self._vecs[k] for k in keys]), len(missing)
|
|
191
|
+
|
|
192
|
+
def query(self, text: str) -> Any:
|
|
193
|
+
return _encode(self.model, [text])[0]
|
|
194
|
+
|
|
195
|
+
def save(self, live: set[bytes]) -> None:
|
|
196
|
+
"""Write the live vectors to disk and forget the dead ones."""
|
|
197
|
+
import numpy as np
|
|
198
|
+
|
|
199
|
+
dead = [k for k in self._vecs if k not in live]
|
|
200
|
+
for k in dead:
|
|
201
|
+
del self._vecs[k]
|
|
202
|
+
if not (self._dirty or dead) or self._path is None or not self._vecs:
|
|
203
|
+
self._dirty = False
|
|
204
|
+
return
|
|
205
|
+
self._dirty = False
|
|
206
|
+
keys = list(self._vecs)
|
|
207
|
+
try:
|
|
208
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
209
|
+
tmp = self._path.with_suffix(f".tmp{os.getpid()}.npz")
|
|
210
|
+
np.savez(
|
|
211
|
+
tmp,
|
|
212
|
+
keys=np.array(keys, dtype="S16"),
|
|
213
|
+
vectors=np.stack([self._vecs[k] for k in keys]).astype(np.float16),
|
|
214
|
+
)
|
|
215
|
+
os.replace(tmp, self._path)
|
|
216
|
+
except Exception: # noqa: BLE001 - the cache only saves time
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def top_k(matrix: Any, q: Any, k: int, alive: Any = None) -> list[tuple[int, float]]:
|
|
221
|
+
"""(row, cosine) of the k rows of ``matrix`` closest to ``q``, best first,
|
|
222
|
+
ties by row. ``alive`` masks rows out (False = skip)."""
|
|
223
|
+
import numpy as np
|
|
224
|
+
|
|
225
|
+
if matrix is None or len(matrix) == 0 or k <= 0:
|
|
226
|
+
return []
|
|
227
|
+
sims = matrix @ q
|
|
228
|
+
if alive is not None:
|
|
229
|
+
sims = np.where(alive, sims, -np.inf)
|
|
230
|
+
k = min(k, len(sims))
|
|
231
|
+
idx = np.argpartition(-sims, k - 1)[:k]
|
|
232
|
+
rows = sorted(((int(i), float(sims[i])) for i in idx), key=lambda r: (-r[1], r[0]))
|
|
233
|
+
return [r for r in rows if r[1] != float("-inf")]
|
graphlore/engine.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""Which extractor builds the graph: the graphify CLI or graphlore's native engine.
|
|
2
|
+
|
|
3
|
+
The native engine is the ``graphlore-engine`` distribution (import name
|
|
4
|
+
``graphlore_engine``), written in Rust with its tree-sitter grammars compiled in.
|
|
5
|
+
It is installed with the ``engine`` extra (prebuilt wheels): it extracts
|
|
6
|
+
definitions with their real spans, containment, document headings, the imports,
|
|
7
|
+
calls, bases and type references it resolves from the source, and communities by
|
|
8
|
+
its own weighting; ``update=True`` parses only the files that changed.
|
|
9
|
+
``GRAPHLORE_ENGINE`` picks the engine at call time:
|
|
10
|
+
|
|
11
|
+
auto (default) native when installed, graphify for what native cannot do
|
|
12
|
+
native the native engine; an error when it is not installed
|
|
13
|
+
graphify the graphify CLI, as before (going in the next release)
|
|
14
|
+
|
|
15
|
+
Nothing here imports ``graphlore_engine`` at module import: ``available`` asks
|
|
16
|
+
``importlib`` whether it exists, builds run it in a child process, and
|
|
17
|
+
``file_spans`` imports it on first use.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import importlib.util
|
|
23
|
+
import json
|
|
24
|
+
import subprocess
|
|
25
|
+
import sys
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from . import config
|
|
30
|
+
|
|
31
|
+
ENGINES = ("graphify", "native", "auto")
|
|
32
|
+
DEFAULT_ENGINE = "auto"
|
|
33
|
+
# graph.json schema versions of the native engine this graphlore reads.
|
|
34
|
+
SUPPORTED_SCHEMAS = frozenset({1, 2, 3, 4, 5, 6, 7})
|
|
35
|
+
INSTALL_HINT = (
|
|
36
|
+
'Install it with: pip install "graphlore[engine]" (or pip install graphlore-engine; '
|
|
37
|
+
"from a checkout of graphlore: pip install maturin && maturin develop -m "
|
|
38
|
+
"engine/Cargo.toml --release)."
|
|
39
|
+
)
|
|
40
|
+
# Said when graphify answers a build: it is going, and what replaces it.
|
|
41
|
+
GRAPHIFY_DEPRECATED = (
|
|
42
|
+
"graphify is deprecated as graphlore's extractor and goes in the next release; "
|
|
43
|
+
"the native engine replaces it. " + INSTALL_HINT
|
|
44
|
+
)
|
|
45
|
+
# What a native graph does not have yet; said after every native build so an
|
|
46
|
+
# empty answer is not mistaken for a codebase without structure.
|
|
47
|
+
NATIVE_GAPS = (
|
|
48
|
+
"Built by graphlore's native engine: this graph has files, definitions with "
|
|
49
|
+
"their spans, containment, document headings and the code they name, the "
|
|
50
|
+
"imports, calls, bases and type references it could resolve from the source, "
|
|
51
|
+
"and communities by its own "
|
|
52
|
+
"weighting (edge kind, confidence and directory), not graphify's. "
|
|
53
|
+
"update=True parses only the files that changed."
|
|
54
|
+
)
|
|
55
|
+
# The same for a graph written before the engine detected communities.
|
|
56
|
+
NATIVE_GAPS_NO_COMMUNITIES = (
|
|
57
|
+
"Built by graphlore's native engine: this graph has files, definitions with "
|
|
58
|
+
"their spans, containment, document headings and the imports, calls, bases and "
|
|
59
|
+
"type references it could resolve from the source, but no communities, and "
|
|
60
|
+
"update=True rebuilds the whole graph. A current graphlore-engine detects them."
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def requested() -> str:
|
|
65
|
+
"""``GRAPHLORE_ENGINE``, lower-cased; the default when unset. Read per call."""
|
|
66
|
+
return (config.env("ENGINE", "") or "").strip().lower() or DEFAULT_ENGINE
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def available() -> bool:
|
|
70
|
+
"""Whether ``graphlore_engine`` is importable, without importing it."""
|
|
71
|
+
try:
|
|
72
|
+
return importlib.util.find_spec("graphlore_engine") is not None
|
|
73
|
+
except (ImportError, ValueError):
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def graph_engine(graph: object) -> str:
|
|
78
|
+
"""``"native"`` for a graph the native engine wrote, else ``"graphify"``."""
|
|
79
|
+
if isinstance(graph, dict):
|
|
80
|
+
meta = graph.get("graph")
|
|
81
|
+
if isinstance(meta, dict) and meta.get("engine") == "graphlore":
|
|
82
|
+
return "native"
|
|
83
|
+
return "graphify"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def choose(
|
|
87
|
+
*,
|
|
88
|
+
requested: str,
|
|
89
|
+
native_found: bool,
|
|
90
|
+
graphify_found: bool,
|
|
91
|
+
mode: str = "",
|
|
92
|
+
update: bool = False,
|
|
93
|
+
cluster_only: bool = False,
|
|
94
|
+
existing: str | None = None,
|
|
95
|
+
) -> tuple[str, str]:
|
|
96
|
+
"""The engine a build runs with, and a note saying why when it is not plain.
|
|
97
|
+
|
|
98
|
+
Returns ``("graphify" | "native", note)``, or ``("error", message)`` with an
|
|
99
|
+
``ERROR`` message when the request cannot be met. ``existing`` is the engine
|
|
100
|
+
of the graph already on disk, if any.
|
|
101
|
+
"""
|
|
102
|
+
if requested not in ENGINES:
|
|
103
|
+
return "error", (
|
|
104
|
+
f"ERROR: GRAPHLORE_ENGINE={requested!r} is not an engine "
|
|
105
|
+
f"({', '.join(ENGINES)}). Unset it for the default (auto)."
|
|
106
|
+
)
|
|
107
|
+
if requested == "graphify":
|
|
108
|
+
return "graphify", f"GRAPHLORE_ENGINE=graphify: {GRAPHIFY_DEPRECATED}"
|
|
109
|
+
unsupported = f"mode={mode!r} (graphify's LLM extraction)" if mode else ""
|
|
110
|
+
if requested == "native":
|
|
111
|
+
if not native_found:
|
|
112
|
+
return "error", (
|
|
113
|
+
"ERROR: GRAPHLORE_ENGINE=native, but the native engine (graphlore_engine) "
|
|
114
|
+
f"is not installed. {INSTALL_HINT}"
|
|
115
|
+
)
|
|
116
|
+
if unsupported:
|
|
117
|
+
return "error", (
|
|
118
|
+
f"ERROR: the native engine has no {unsupported} yet. "
|
|
119
|
+
"GRAPHLORE_ENGINE=graphify (or auto) runs it with graphify."
|
|
120
|
+
)
|
|
121
|
+
return "native", _update_note(update)
|
|
122
|
+
# auto
|
|
123
|
+
if not native_found:
|
|
124
|
+
if not graphify_found:
|
|
125
|
+
return "error", (
|
|
126
|
+
"ERROR: no extractor is installed: neither graphlore's native engine "
|
|
127
|
+
f"(graphlore_engine) nor the graphify CLI. {INSTALL_HINT}"
|
|
128
|
+
)
|
|
129
|
+
return "graphify", (
|
|
130
|
+
"The native engine is not installed, so graphify built the graph. "
|
|
131
|
+
+ GRAPHIFY_DEPRECATED
|
|
132
|
+
)
|
|
133
|
+
if unsupported:
|
|
134
|
+
if graphify_found:
|
|
135
|
+
return "graphify", (
|
|
136
|
+
f"The native engine has no {unsupported}, so graphify ran it. mode= "
|
|
137
|
+
"goes with graphify in the next release."
|
|
138
|
+
)
|
|
139
|
+
return "error", (
|
|
140
|
+
f"ERROR: the native engine has no {unsupported}, and the graphify CLI "
|
|
141
|
+
"is not installed either. mode= goes with graphify in the next release; "
|
|
142
|
+
"build without it."
|
|
143
|
+
)
|
|
144
|
+
if (update or cluster_only) and existing == "graphify" and graphify_found:
|
|
145
|
+
what = "update=True" if update else "cluster_only=True"
|
|
146
|
+
return "graphify", (
|
|
147
|
+
f"The graph on disk is graphify's, so {what} went to graphify to keep "
|
|
148
|
+
"its edges and communities. graphlore_build(update=False) rebuilds it "
|
|
149
|
+
"with the native engine, which replaces graphify in the next release."
|
|
150
|
+
)
|
|
151
|
+
return "native", _update_note(update)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _update_note(update: bool) -> str:
|
|
155
|
+
del update # the build reply says what an update reused
|
|
156
|
+
return ""
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def build(
|
|
160
|
+
target: Path,
|
|
161
|
+
*,
|
|
162
|
+
documents: bool = True,
|
|
163
|
+
commit: str | None = None,
|
|
164
|
+
timeout: int = 600,
|
|
165
|
+
incremental: bool = False,
|
|
166
|
+
) -> dict[str, Any] | str:
|
|
167
|
+
"""Build ``target``'s graph with the native engine, in a child process.
|
|
168
|
+
|
|
169
|
+
Writes ``target/<out dir>/graph.json`` and returns the engine's report, or an
|
|
170
|
+
``ERROR`` string. A child process, so that a crash in a grammar cannot take
|
|
171
|
+
the server down and the timeout is a real one.
|
|
172
|
+
"""
|
|
173
|
+
out = target / config.OUT_DIR_NAME / "graph.json"
|
|
174
|
+
argv = [
|
|
175
|
+
sys.executable, "-m", "graphlore_engine", "build", str(target),
|
|
176
|
+
"--out", str(out), "--out-dir-name", config.OUT_DIR_NAME,
|
|
177
|
+
]
|
|
178
|
+
if commit:
|
|
179
|
+
argv += ["--commit", commit]
|
|
180
|
+
if not documents:
|
|
181
|
+
argv.append("--no-docs")
|
|
182
|
+
if incremental:
|
|
183
|
+
argv.append("--incremental")
|
|
184
|
+
try:
|
|
185
|
+
proc = subprocess.run(
|
|
186
|
+
argv, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
187
|
+
timeout=timeout,
|
|
188
|
+
)
|
|
189
|
+
except subprocess.TimeoutExpired:
|
|
190
|
+
return f"ERROR: the native engine did not finish within {timeout}s (GRAPHLORE_TIMEOUT)."
|
|
191
|
+
except OSError as e:
|
|
192
|
+
return f"ERROR: failed to run the native engine: {e}"
|
|
193
|
+
if proc.returncode != 0:
|
|
194
|
+
detail = (proc.stderr or proc.stdout or "").strip()
|
|
195
|
+
if detail.startswith("ERROR"):
|
|
196
|
+
return detail
|
|
197
|
+
return f"ERROR (native engine, exit {proc.returncode}):\n{detail}"
|
|
198
|
+
try:
|
|
199
|
+
report = json.loads(proc.stdout)
|
|
200
|
+
except ValueError:
|
|
201
|
+
return f"ERROR: the native engine's report is not JSON:\n{proc.stdout[:500]}"
|
|
202
|
+
if not isinstance(report, dict):
|
|
203
|
+
return "ERROR: the native engine's report is not a JSON object."
|
|
204
|
+
if report.get("schema_version") not in SUPPORTED_SCHEMAS:
|
|
205
|
+
return (
|
|
206
|
+
f"ERROR: the native engine writes graph schema {report.get('schema_version')}, "
|
|
207
|
+
f"which this graphlore does not read (it reads {sorted(SUPPORTED_SCHEMAS)}). "
|
|
208
|
+
"Install a matching graphlore-engine."
|
|
209
|
+
)
|
|
210
|
+
return report
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def cluster(graph: Path, *, timeout: int = 600) -> dict[str, Any] | str:
|
|
214
|
+
"""Detect the communities of the native graph at ``graph`` again, in a child
|
|
215
|
+
process; returns the engine's community report or an ``ERROR`` string."""
|
|
216
|
+
argv = [sys.executable, "-m", "graphlore_engine", "cluster", str(graph)]
|
|
217
|
+
try:
|
|
218
|
+
proc = subprocess.run(
|
|
219
|
+
argv, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
220
|
+
timeout=timeout,
|
|
221
|
+
)
|
|
222
|
+
except subprocess.TimeoutExpired:
|
|
223
|
+
return f"ERROR: the native engine did not finish within {timeout}s (GRAPHLORE_TIMEOUT)."
|
|
224
|
+
except OSError as e:
|
|
225
|
+
return f"ERROR: failed to run the native engine: {e}"
|
|
226
|
+
if proc.returncode != 0:
|
|
227
|
+
detail = (proc.stderr or proc.stdout or "").strip()
|
|
228
|
+
if detail.startswith("ERROR"):
|
|
229
|
+
return detail
|
|
230
|
+
return f"ERROR (native engine, exit {proc.returncode}):\n{detail}"
|
|
231
|
+
try:
|
|
232
|
+
report = json.loads(proc.stdout)
|
|
233
|
+
except ValueError:
|
|
234
|
+
return f"ERROR: the native engine's report is not JSON:\n{proc.stdout[:500]}"
|
|
235
|
+
if not isinstance(report, dict):
|
|
236
|
+
return "ERROR: the native engine's report is not a JSON object."
|
|
237
|
+
return report
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def render_communities(c: dict[str, Any]) -> str:
|
|
241
|
+
"""One line on the communities a native build or re-cluster found."""
|
|
242
|
+
line = (
|
|
243
|
+
f"communities: {c.get('count', 0)} (largest {c.get('largest', 0)} nodes, "
|
|
244
|
+
f"modularity {c.get('modularity', 0)})"
|
|
245
|
+
)
|
|
246
|
+
if c.get("kept_ids"):
|
|
247
|
+
line += f", {c['kept_ids']} kept their id from the previous graph"
|
|
248
|
+
if c.get("renamed_labels"):
|
|
249
|
+
line += (
|
|
250
|
+
f"; {_plural(c['renamed_labels'], 'saved name')} dropped from "
|
|
251
|
+
".graphify_labels.json because its community changed beyond recognition"
|
|
252
|
+
)
|
|
253
|
+
return line
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _plural(n: int, word: str) -> str:
|
|
257
|
+
return f"{n} {word}" + ("" if n == 1 else "s")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def render_report(report: dict[str, Any], verbose: bool = False, update: bool = False) -> str:
|
|
261
|
+
"""The build reply: counts first, then everything that was left out."""
|
|
262
|
+
langs: dict[str, dict[str, int]] = report.get("languages") or {}
|
|
263
|
+
secs = (report.get("elapsed_ms") or 0) / 1000
|
|
264
|
+
head = (
|
|
265
|
+
f"native engine {report.get('engine_version', '?')}: "
|
|
266
|
+
f"{report.get('nodes', 0)} nodes, {report.get('edges', 0)} edges from "
|
|
267
|
+
f"{_plural(report.get('files', 0), 'source file')} "
|
|
268
|
+
f"({_plural(len(langs), 'language')}) and "
|
|
269
|
+
f"{_plural(report.get('documents', 0), 'document')} in {secs:.1f}s"
|
|
270
|
+
)
|
|
271
|
+
lines = [head]
|
|
272
|
+
if langs:
|
|
273
|
+
rows = [
|
|
274
|
+
f"{name} {_plural(s.get('files', 0), 'file')}, "
|
|
275
|
+
f"{_plural(s.get('definitions', 0), 'definition')}"
|
|
276
|
+
for name, s in sorted(langs.items(), key=lambda kv: -kv[1].get("files", 0))
|
|
277
|
+
]
|
|
278
|
+
lines.append(" " + " · ".join(rows if verbose else rows[:8])
|
|
279
|
+
+ ("" if verbose or len(rows) <= 8 else f" · +{len(rows) - 8} more"))
|
|
280
|
+
resolution: dict[str, dict[str, Any]] = report.get("resolution") or {}
|
|
281
|
+
if resolution:
|
|
282
|
+
rows = []
|
|
283
|
+
for fam, r in sorted(resolution.items()):
|
|
284
|
+
edges = sum((r.get("edges") or {}).values())
|
|
285
|
+
if not edges and not r.get("unresolved"):
|
|
286
|
+
continue
|
|
287
|
+
bit = f"{fam} {_plural(edges, 'edge')}"
|
|
288
|
+
if r.get("inferred"):
|
|
289
|
+
bit += f" ({r['inferred']} inferred)"
|
|
290
|
+
if r.get("unresolved"):
|
|
291
|
+
bit += f", {r['unresolved']} unresolved"
|
|
292
|
+
rows.append(bit)
|
|
293
|
+
if rows:
|
|
294
|
+
lines.append(" resolved: " + " · ".join(rows if verbose else rows[:8])
|
|
295
|
+
+ ("" if verbose or len(rows) <= 8 else f" · +{len(rows) - 8} more"))
|
|
296
|
+
if report.get("documents"):
|
|
297
|
+
line = f" documents: {_plural(report.get('headings', 0), 'heading')}"
|
|
298
|
+
if "doc_links" in report:
|
|
299
|
+
line += (f", {_plural(report['doc_links'], 'link')} to the definition a name "
|
|
300
|
+
"of code in them means")
|
|
301
|
+
lines.append(line)
|
|
302
|
+
inc = report.get("incremental")
|
|
303
|
+
if isinstance(inc, dict) and inc.get("cache"):
|
|
304
|
+
line = (f" update: {_plural(inc.get('parsed', 0), 'file')} parsed, "
|
|
305
|
+
f"{inc.get('reused', 0)} unchanged reused from the cache")
|
|
306
|
+
if inc.get("removed"):
|
|
307
|
+
line += f", {inc['removed']} gone since the last build"
|
|
308
|
+
lines.append(line)
|
|
309
|
+
elif isinstance(inc, dict) and update:
|
|
310
|
+
lines.append(" update: no cache from this engine version and options, "
|
|
311
|
+
"so every file was parsed")
|
|
312
|
+
state = report.get("state")
|
|
313
|
+
if isinstance(state, dict) and (state.get("reads") or state.get("writes")):
|
|
314
|
+
line = (f" shared state: {_plural(state.get('state_nodes', 0), 'variable/field')}, "
|
|
315
|
+
f"{state.get('reads', 0)} reads, {state.get('writes', 0)} writes")
|
|
316
|
+
res = state.get("resources") or {}
|
|
317
|
+
if res:
|
|
318
|
+
line += "; resources: " + ", ".join(f"{k} {v}" for k, v in sorted(res.items()))
|
|
319
|
+
if state.get("single_touch"):
|
|
320
|
+
line += f" ({state['single_touch']} more touched in one place only, not shown)"
|
|
321
|
+
lines.append(line)
|
|
322
|
+
coupling = report.get("coupling")
|
|
323
|
+
if isinstance(coupling, dict) and coupling.get("pairs"):
|
|
324
|
+
line = (f" implicit coupling: {_plural(coupling['pairs'], 'pair')} of definitions "
|
|
325
|
+
f"share state, {coupling.get('hidden', 0)} with no call path between them")
|
|
326
|
+
if coupling.get("hidden_without_edge"):
|
|
327
|
+
line += (f" ({coupling['hidden_without_edge']} of them past the limit of "
|
|
328
|
+
"couples_with edges per state node: listed on the node only)")
|
|
329
|
+
lines.append(line)
|
|
330
|
+
communities = report.get("communities")
|
|
331
|
+
if isinstance(communities, dict) and communities.get("count"):
|
|
332
|
+
lines.append(" " + render_communities(communities))
|
|
333
|
+
errors = {k: v["parse_errors"] for k, v in langs.items() if v.get("parse_errors")}
|
|
334
|
+
if errors:
|
|
335
|
+
lines.append(
|
|
336
|
+
" parse errors (definitions found are partial): "
|
|
337
|
+
+ ", ".join(f"{k} {_plural(v, 'file')}" for k, v in sorted(errors.items()))
|
|
338
|
+
)
|
|
339
|
+
not_read = report.get("not_read") or {}
|
|
340
|
+
if not_read:
|
|
341
|
+
lines.append(
|
|
342
|
+
" not read (no module for these source files): "
|
|
343
|
+
+ ", ".join(f"{ext} {n}" for ext, n in sorted(not_read.items()))
|
|
344
|
+
)
|
|
345
|
+
for key, what in (
|
|
346
|
+
("too_large", f"skipped as larger than {(report.get('max_file_bytes') or 0) // 1024} KB"),
|
|
347
|
+
("timed_out", "parse timed out"),
|
|
348
|
+
("unreadable", "could not be read"),
|
|
349
|
+
):
|
|
350
|
+
count = report.get(f"{key}_count") or 0
|
|
351
|
+
if count:
|
|
352
|
+
sample = report.get(key) or []
|
|
353
|
+
shown = sample if verbose else sample[:3]
|
|
354
|
+
more = f", +{count - len(shown)} more" if count > len(shown) else ""
|
|
355
|
+
lines.append(f" {what}: {_plural(count, 'file')} ({', '.join(shown)}{more})")
|
|
356
|
+
if report.get("non_utf8_paths"):
|
|
357
|
+
skipped = _plural(report["non_utf8_paths"], "file")
|
|
358
|
+
lines.append(f" skipped {skipped} whose name is not UTF-8")
|
|
359
|
+
phases = report.get("phases_ms")
|
|
360
|
+
if verbose and isinstance(phases, dict) and phases:
|
|
361
|
+
lines.append(" time per phase: " + ", ".join(f"{k} {v} ms" for k, v in phases.items()))
|
|
362
|
+
if verbose and report.get("id_collisions"):
|
|
363
|
+
lines.append(f" {report['id_collisions']} node id(s) suffixed _2, _3… to stay unique")
|
|
364
|
+
has = isinstance(communities, dict) and bool(communities.get("count"))
|
|
365
|
+
lines.append(NATIVE_GAPS if has or not report.get("nodes") else NATIVE_GAPS_NO_COMMUNITIES)
|
|
366
|
+
return "\n".join(lines)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def file_spans(src: bytes, rel: str) -> list[tuple[int, int, int, str]] | None:
|
|
370
|
+
"""The native engine's ``(region_start, end_line, def_line, qualname)`` spans
|
|
371
|
+
of one file, or None when the engine is not installed or cannot read it."""
|
|
372
|
+
try:
|
|
373
|
+
import graphlore_engine
|
|
374
|
+
except ImportError:
|
|
375
|
+
return None
|
|
376
|
+
try:
|
|
377
|
+
return [tuple(s) for s in graphlore_engine.file_spans(src, rel)] # type: ignore[misc]
|
|
378
|
+
except Exception: # noqa: BLE001 - a span backend that fails reads as "no spans"
|
|
379
|
+
return None
|