graphe-code 0.1.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.
- graphe/__init__.py +0 -0
- graphe/cli.py +991 -0
- graphe/core.py +461 -0
- graphe/generic.py +662 -0
- graphe/godot.py +386 -0
- graphe/js.py +564 -0
- graphe/python.py +917 -0
- graphe/root.py +82 -0
- graphe_code-0.1.0.dist-info/METADATA +24 -0
- graphe_code-0.1.0.dist-info/RECORD +14 -0
- graphe_code-0.1.0.dist-info/WHEEL +5 -0
- graphe_code-0.1.0.dist-info/entry_points.txt +2 -0
- graphe_code-0.1.0.dist-info/licenses/LICENSE +21 -0
- graphe_code-0.1.0.dist-info/top_level.txt +1 -0
graphe/cli.py
ADDED
|
@@ -0,0 +1,991 @@
|
|
|
1
|
+
"""graphe: the code graph of a host project - what calls what, what cites what.
|
|
2
|
+
|
|
3
|
+
graphe build [--quiet] graphe/: graphe.json, REPORT.md
|
|
4
|
+
graphe view [X] graphe/graphe.html, opened (on X): the
|
|
5
|
+
nodes laid out by community, on demand
|
|
6
|
+
graphe check the coverage of each contribution
|
|
7
|
+
graphe path A B [--undirected] the shortest path from A to B
|
|
8
|
+
graphe explain X [--all] [--source] what X calls, what calls X (and its code)
|
|
9
|
+
graphe callers X [--depth N]
|
|
10
|
+
both say how many calls of X's name no
|
|
11
|
+
reader could attribute: grep those
|
|
12
|
+
graphe search PATTERN by name, then by displayed texts and comments
|
|
13
|
+
graphe install [--remove] the git hooks that rebuild it
|
|
14
|
+
|
|
15
|
+
A node is designated by its id, its name (`help`, `Class.method`),
|
|
16
|
+
`file::name` (`tools.py::help`), a file by its path, or, in GDScript, by the
|
|
17
|
+
constant that preloads its script (`Script.function`).
|
|
18
|
+
|
|
19
|
+
The readers: graphe/python.py (the ast, calls resolved by types),
|
|
20
|
+
graphe/godot.py (GDScript, by patterns) and graphe/js.py
|
|
21
|
+
(`.js`, `.mjs`, `.ts`, the script and markup of `.svelte`, by tree-sitter: calls
|
|
22
|
+
resolved by the imports, by `new C()` or `f()` assigned, else by the name); generic.py reads
|
|
23
|
+
Go, Rust, Java/Kotlin, C/C++, C#, Ruby, Swift and PHP (with the actions of a
|
|
24
|
+
`switch ($action)`) by tree-sitter, a call linked by its name only when the
|
|
25
|
+
language (or family) defines it once (docs/readers.md lists every reader). The core, core.py, then
|
|
26
|
+
reads the text: the end of each function and class, the texts it displays
|
|
27
|
+
(the `displayed_text` pattern of graphe.toml), its comment, module variables
|
|
28
|
+
and who reads them, and the documents (the host's Markdown, `[documents]` of
|
|
29
|
+
graphe.toml) - who cites them, what they name. The fields of a class are
|
|
30
|
+
nodes (the Python reader). A keyed link (`[keys]` of graphe.toml: `names`,
|
|
31
|
+
`answers`, `parameters`) is a `sends` from the code that names a key (a
|
|
32
|
+
front's `api("zones")`) to the code that answers it (`'/api/zones'`).
|
|
33
|
+
|
|
34
|
+
Communities (`[communities]` of graphe.toml): `separate` gives kinds outside
|
|
35
|
+
the code their own community (kind -> name), after tickets, values and
|
|
36
|
+
documents; `strip_prefixes` removes prefixes from community names.
|
|
37
|
+
|
|
38
|
+
The contract (docs/contribution.md): readers and local extensions return a
|
|
39
|
+
contribution through `contribute(project)`. Assembly runs the readers, then
|
|
40
|
+
the core (core.py), then the extensions declared by `[[extensions]]`
|
|
41
|
+
in graphe.toml, in their order. A `with_readers` extension comes in with the
|
|
42
|
+
readers, before the core, and may take over their links.
|
|
43
|
+
|
|
44
|
+
Files read (root.py): those git tracks, plus untracked files that
|
|
45
|
+
are not ignored, each to the reader of its extension; `exclude`, in an
|
|
46
|
+
optional graphe.toml at the host root, removes folders.
|
|
47
|
+
|
|
48
|
+
Updates: `install` sets git hooks (post-commit, post-merge, post-checkout,
|
|
49
|
+
post-rewrite) that rebuild the graph in the background with the global
|
|
50
|
+
`graphe` command, and adds the output to the host's .gitignore; a query on a
|
|
51
|
+
graph older than the host's code or than the tool rebuilds it first.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
from __future__ import annotations
|
|
55
|
+
|
|
56
|
+
import copy
|
|
57
|
+
import functools
|
|
58
|
+
import importlib.util
|
|
59
|
+
import itertools
|
|
60
|
+
import json
|
|
61
|
+
import math
|
|
62
|
+
import os
|
|
63
|
+
import re
|
|
64
|
+
import subprocess
|
|
65
|
+
import sys
|
|
66
|
+
import tempfile
|
|
67
|
+
import time
|
|
68
|
+
import webbrowser
|
|
69
|
+
from collections import Counter, defaultdict
|
|
70
|
+
from functools import cached_property
|
|
71
|
+
from pathlib import Path
|
|
72
|
+
|
|
73
|
+
import networkx as nx
|
|
74
|
+
|
|
75
|
+
from graphe import core, generic, godot, js, python
|
|
76
|
+
from graphe import root as graphe_root # `root` is the host's path in this module's signatures
|
|
77
|
+
from graphe.root import CONFIGURATION, OUTPUT, ROOT
|
|
78
|
+
|
|
79
|
+
JSON = OUTPUT / "graphe.json"
|
|
80
|
+
HOOKS = ("post-commit", "post-merge", "post-checkout", "post-rewrite")
|
|
81
|
+
# (start, end) of the block set in a hook; the second, the one from before T-0011 (the host's relay, then the tool in
|
|
82
|
+
# French), is removed too.
|
|
83
|
+
BLOCKS = (("# >>> graphe code graph", "# <<< graphe code graph"), ("# >>> graphe du code", "# <<< graphe du code"))
|
|
84
|
+
# What leads from the caller to the callee.
|
|
85
|
+
CALLS = {"calls", "uses", "references", "indirect_call", "sends", "dispatches", "reads", "writes", "value"}
|
|
86
|
+
# T-0354: nodes that are not code, each their own community - a ticket, a value or a document links files that
|
|
87
|
+
# nothing else links, and would merge unrelated communities. The host adds some (`[communities] separate`).
|
|
88
|
+
SEPARATE = {"ticket": "tickets", "value": "values", "document": "documents"}
|
|
89
|
+
OFF_CODE_WEIGHT = 4
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _communities_config() -> tuple[dict[str, str], list[str]]:
|
|
93
|
+
"""`[communities]` of graphe.toml: the separate kinds (kind -> name), and the prefixes removed from names."""
|
|
94
|
+
table = graphe_root.configuration().get("communities", {})
|
|
95
|
+
return {**SEPARATE, **table.get("separate", {})}, table.get("strip_prefixes", [])
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---------- build
|
|
99
|
+
|
|
100
|
+
def _sources() -> list[Path]:
|
|
101
|
+
"""T-0009: all the host's files, not only the readers' (an extension reads what it wants)."""
|
|
102
|
+
return graphe_root.files("") + [p for p in [ROOT / CONFIGURATION] # files() tests is_file already
|
|
103
|
+
+ [ROOT / e.get("path", "") for e in _declared_extensions()] if p.is_file()]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _tool() -> list[Path]:
|
|
107
|
+
"""The tool's files (T-0006): a fixed reader makes every host's graph stale."""
|
|
108
|
+
return sorted(Path(__file__).parent.glob("*.py"))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _commit() -> str | None:
|
|
112
|
+
try:
|
|
113
|
+
r = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, text=True,
|
|
114
|
+
timeout=10)
|
|
115
|
+
return r.stdout.strip() or None
|
|
116
|
+
except (OSError, subprocess.SubprocessError):
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Each reader under the name of its graphe.toml section: the key of its configuration and of its coverage.
|
|
121
|
+
READERS = {"python": python.contribute, "godot": godot.contribute, "js": js.contribute,
|
|
122
|
+
"go": functools.partial(generic.contribute, generic.GO),
|
|
123
|
+
"rust": functools.partial(generic.contribute, generic.RUST),
|
|
124
|
+
"java": functools.partial(generic.contribute, generic.JVM),
|
|
125
|
+
"c": functools.partial(generic.contribute, generic.C),
|
|
126
|
+
"csharp": functools.partial(generic.contribute, generic.CSHARP),
|
|
127
|
+
"ruby": functools.partial(generic.contribute, generic.RUBY),
|
|
128
|
+
"swift": functools.partial(generic.contribute, generic.SWIFT),
|
|
129
|
+
"php": functools.partial(generic.contribute, generic.PHP)}
|
|
130
|
+
NODE_FIELDS = ("id", "label", "kind", "source_file", "source_location", "name")
|
|
131
|
+
LINK_FIELDS = ("source", "target", "relation", "confidence", "source_file", "source_location", "context")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class Project:
|
|
135
|
+
"""What `contribute(project)` receives: the root, the host's files, the configuration section of the one who
|
|
136
|
+
contributes and the graph already assembled, copied on reading (docs/contribution.md)."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, configuration: dict, graph: nx.DiGraph, checking: bool) -> None:
|
|
139
|
+
self.root = ROOT
|
|
140
|
+
self.configuration = configuration
|
|
141
|
+
self.checking = checking
|
|
142
|
+
self._graph = graph
|
|
143
|
+
|
|
144
|
+
def files(self, suffix: str) -> list[Path]:
|
|
145
|
+
return graphe_root.files(suffix, self.root)
|
|
146
|
+
|
|
147
|
+
@cached_property
|
|
148
|
+
def graph(self) -> dict:
|
|
149
|
+
return {"nodes": {n: copy.deepcopy(d) for n, d in self._graph.nodes(data=True)},
|
|
150
|
+
"links": [{"source": s, "target": t, **copy.deepcopy({**d, "relations": sorted(d["relations"])})}
|
|
151
|
+
for s, t, d in self._graph.edges(data=True)]}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _declared_extensions() -> list[dict]:
|
|
155
|
+
return graphe_root.configuration().get("extensions", [])
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _extension(declaration: dict):
|
|
159
|
+
"""The `contribute` function of a local extension; an extension not found stops the build."""
|
|
160
|
+
rel = declaration.get("path", "")
|
|
161
|
+
file = ROOT / rel
|
|
162
|
+
if not rel or not file.is_file():
|
|
163
|
+
raise RuntimeError(f"local extension {rel!r} not found ([[extensions]] path, {CONFIGURATION})")
|
|
164
|
+
spec = importlib.util.spec_from_file_location(f"graphe_extension_{file.stem}", file)
|
|
165
|
+
if spec is None:
|
|
166
|
+
raise RuntimeError(f"local extension {rel}: not a Python module")
|
|
167
|
+
module = importlib.util.module_from_spec(spec)
|
|
168
|
+
sys.modules[spec.name] = module # a dataclass of the extension looks for its module here
|
|
169
|
+
spec.loader.exec_module(module)
|
|
170
|
+
if not callable(getattr(module, "contribute", None)):
|
|
171
|
+
raise RuntimeError(f"local extension {rel}: no function contribute(project)")
|
|
172
|
+
return module.contribute
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _insert(graph: nx.DiGraph, contributions: list[tuple[str, dict]], dangling: list[dict]) -> None:
|
|
176
|
+
"""The contributions into the graph: the nodes sorted by id (an id already there merges its attributes), then
|
|
177
|
+
the links; one link per pair of nodes, which keeps its relations and its locations."""
|
|
178
|
+
nodes = sorted(((who, n) for who, c in contributions for n in c.get("nodes", [])), key=lambda p: str(p[1].get("id")))
|
|
179
|
+
for who, n in nodes:
|
|
180
|
+
required = ("id",) if n.get("id") in graph else NODE_FIELDS
|
|
181
|
+
if missing := [k for k in required if k not in n]:
|
|
182
|
+
raise RuntimeError(f"{who}: node {n.get('id')!r} lacks {', '.join(missing)}")
|
|
183
|
+
graph.add_node(n["id"], **n)
|
|
184
|
+
for who, c in contributions:
|
|
185
|
+
for e in c.get("links", []):
|
|
186
|
+
if missing := [k for k in LINK_FIELDS if k not in e]:
|
|
187
|
+
raise RuntimeError(f"{who}: link {e.get('source')!r} -> {e.get('target')!r} lacks "
|
|
188
|
+
f"{', '.join(missing)}")
|
|
189
|
+
s, target = e["source"], e["target"]
|
|
190
|
+
if s not in graph or target not in graph:
|
|
191
|
+
dangling.append(e)
|
|
192
|
+
continue
|
|
193
|
+
location = f"{e['source_file']}:{e['source_location'].lstrip('L')}"
|
|
194
|
+
if graph.has_edge(s, target):
|
|
195
|
+
d = graph[s][target]
|
|
196
|
+
d["relations"].add(e["relation"])
|
|
197
|
+
if location not in d["locations"]:
|
|
198
|
+
d["locations"].append(location)
|
|
199
|
+
if e["confidence"] == "EXTRACTED":
|
|
200
|
+
d["confidence"] = "EXTRACTED"
|
|
201
|
+
if e["context"] and e["context"] not in d["contexts"]:
|
|
202
|
+
d["contexts"].append(e["context"])
|
|
203
|
+
else:
|
|
204
|
+
graph.add_edge(s, target, relations={e["relation"]}, confidence=e["confidence"], locations=[location],
|
|
205
|
+
contexts=[e["context"]] if e["context"] else [])
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _take_over(contributions: list[tuple[str, dict]]) -> None:
|
|
209
|
+
"""The takeovers (`takeovers`), in their order: the links that leave `from` from the lines `lines`
|
|
210
|
+
(bounds included) of `source_file` leave from `to`. A later takeover sees the earlier ones (a branch in a branch).
|
|
211
|
+
Only the readers' links are taken over: an extension returns its own already in their place."""
|
|
212
|
+
links = [e for who, c in contributions if who in READERS for e in c.get("links", [])]
|
|
213
|
+
for who, c in contributions:
|
|
214
|
+
for r in c.get("takeovers", []):
|
|
215
|
+
if missing := [k for k in ("from", "to", "source_file", "lines") if k not in r]:
|
|
216
|
+
raise RuntimeError(f"{who}: a takeover lacks {', '.join(missing)}")
|
|
217
|
+
start, end = r["lines"]
|
|
218
|
+
for e in links:
|
|
219
|
+
line = int(str(e.get("source_location", "")).lstrip("L") or 0)
|
|
220
|
+
if e.get("source") == r["from"] and e.get("source_file") == r["source_file"] and start <= line <= end:
|
|
221
|
+
e["source"] = r["to"]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def assemble(checking: bool = False) -> tuple[nx.DiGraph, dict, list[dict], dict[str, list[dict]]]:
|
|
225
|
+
"""The readers (and the `with_readers` extensions), then the core, then the other local extensions
|
|
226
|
+
in the order of graphe.toml: the directed graph,
|
|
227
|
+
the coverage, the dangling links and the sites of each contribution."""
|
|
228
|
+
configuration = graphe_root.configuration()
|
|
229
|
+
graph = nx.DiGraph()
|
|
230
|
+
dangling: list[dict] = []
|
|
231
|
+
# The readers together: their nodes come in sorted all at once, as before the contract (T-0007).
|
|
232
|
+
readers = [(name, contribute(Project(configuration.get(name, {}), graph, checking)))
|
|
233
|
+
for name, contribute in READERS.items()]
|
|
234
|
+
# T-0008: a `with_readers` extension comes in with them, before the core, and may take over their links.
|
|
235
|
+
with_, after = [], []
|
|
236
|
+
for declaration in _declared_extensions():
|
|
237
|
+
(with_ if declaration.get("with_readers") else after).append(declaration)
|
|
238
|
+
readers += [(d.get("path", ""), _extension(d)(Project(d, graph, checking))) for d in with_]
|
|
239
|
+
_take_over(readers)
|
|
240
|
+
_insert(graph, readers, dangling)
|
|
241
|
+
core.enrich(graph, ROOT)
|
|
242
|
+
contributions = list(readers)
|
|
243
|
+
for declaration in after:
|
|
244
|
+
contribution = (declaration.get("path", ""), _extension(declaration)(Project(declaration, graph, checking)))
|
|
245
|
+
if "takeovers" in contribution[1]:
|
|
246
|
+
raise RuntimeError(f"{contribution[0]}: takeovers without with_readers = true ({CONFIGURATION})")
|
|
247
|
+
_insert(graph, [contribution], dangling)
|
|
248
|
+
contributions.append(contribution)
|
|
249
|
+
# shortcut: a file declared twice that returns sites twice keeps only the last ones; to merge if an extension
|
|
250
|
+
# needs both sides.
|
|
251
|
+
sites = {who: c["sites"] for who, c in contributions if "sites" in c}
|
|
252
|
+
coverage = {who: dict(Counter(s["verdict"] for s in site_list if "verdict" in s).most_common())
|
|
253
|
+
for who, site_list in sites.items()}
|
|
254
|
+
coverage["dangling"] = len(dangling)
|
|
255
|
+
return _sorted(graph), coverage, dangling, sites
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _location_key(location: str) -> tuple[str, int]:
|
|
259
|
+
file, _, line = location.rpartition(":")
|
|
260
|
+
digits = re.match(r"\d*", line).group()
|
|
261
|
+
return file, int(digits or 0)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _sorted(graph: nx.DiGraph) -> nx.DiGraph:
|
|
265
|
+
"""T-0381: nodes, links and locations in the order of their content - that of the readers (and of hashing) moved graphe.html."""
|
|
266
|
+
sorted_ = nx.DiGraph()
|
|
267
|
+
sorted_.add_nodes_from(sorted(graph.nodes(data=True), key=lambda n: n[0]))
|
|
268
|
+
for s, t, d in sorted(graph.edges(data=True), key=lambda e: (e[0], e[1])):
|
|
269
|
+
sorted_.add_edge(s, t, **{**d, "locations": sorted(d["locations"], key=_location_key), "contexts": sorted(d["contexts"])})
|
|
270
|
+
return sorted_
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def communities(graph: nx.DiGraph) -> tuple[dict[str, int], dict[int, str]]:
|
|
274
|
+
separate, prefixes = _communities_config()
|
|
275
|
+
undirected = nx.Graph()
|
|
276
|
+
undirected.add_nodes_from(n for n in graph.nodes if graph.nodes[n]["kind"] not in separate)
|
|
277
|
+
for s, t, d in graph.edges(data=True):
|
|
278
|
+
if s != t and s in undirected and t in undirected:
|
|
279
|
+
weight = undirected[s][t]["weight"] if undirected.has_edge(s, t) else 0
|
|
280
|
+
undirected.add_edge(s, t, weight=weight + len(d["locations"]))
|
|
281
|
+
groups = nx.community.louvain_communities(undirected, weight="weight", seed=0)
|
|
282
|
+
groups = sorted(groups, key=lambda g: (-len(g), min(g)))
|
|
283
|
+
community_of, names, seen = {}, {}, Counter()
|
|
284
|
+
for i, group in enumerate(groups):
|
|
285
|
+
for n in group:
|
|
286
|
+
community_of[n] = i
|
|
287
|
+
files = Counter(graph.nodes[n]["source_file"] for n in sorted(group)) # ties: by the id
|
|
288
|
+
(first, count), *rest = files.most_common(2)
|
|
289
|
+
name = _short(first, prefixes)
|
|
290
|
+
if rest and rest[0][1] * 3 >= count:
|
|
291
|
+
name += " + " + _short(rest[0][0], prefixes)
|
|
292
|
+
seen[name] += 1
|
|
293
|
+
names[i] = name if seen[name] == 1 else f"{name} ({seen[name]})"
|
|
294
|
+
for kind, name in separate.items():
|
|
295
|
+
members = [n for n, d in graph.nodes(data=True) if d["kind"] == kind]
|
|
296
|
+
if members:
|
|
297
|
+
i = len(names)
|
|
298
|
+
names[i] = name
|
|
299
|
+
community_of.update(dict.fromkeys(members, i))
|
|
300
|
+
return community_of, names
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _short(file: str, prefixes: list[str]) -> str:
|
|
304
|
+
for prefix in prefixes:
|
|
305
|
+
file = file.removeprefix(prefix)
|
|
306
|
+
return file.rsplit(".", 1)[0]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# T-0016: above it, spring_layout costs minutes (Django: 270 s for 19 communities of 1000 to 4800 nodes). The
|
|
310
|
+
# hosts' communities stay below (Grid Zero: 539 at most): their layout does not move.
|
|
311
|
+
LARGE_COMMUNITY = 1000
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _sunflower(graph: nx.DiGraph, group: list[str]) -> dict[str, tuple[float, float]]:
|
|
315
|
+
"""The nodes on a sunflower spiral in the unit disc, in the order of their files: a file's nodes side by side."""
|
|
316
|
+
ordered = sorted(group, key=lambda n: (graph.nodes[n]["source_file"], n))
|
|
317
|
+
golden = math.pi * (3 - math.sqrt(5))
|
|
318
|
+
return {n: (math.sqrt((k + 0.5) / len(ordered)) * math.cos(k * golden),
|
|
319
|
+
math.sqrt((k + 0.5) / len(ordered)) * math.sin(k * golden)) for k, n in enumerate(ordered)}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _first_free(placed: list[tuple[float, float, float]], radius: float, smallest: float,
|
|
323
|
+
open_from: int) -> tuple[tuple[float, float], int]:
|
|
324
|
+
"""The first step of the spiral, from `open_from`, where a disc of `radius` overlaps none of those placed; and
|
|
325
|
+
the new `open_from`. T-0016: numpy discards by batches the steps surely blocked (with a margin over its
|
|
326
|
+
rounding), the others are decided by the exact test, in order: the place is the same. The steps blocked even
|
|
327
|
+
for the `smallest` disc stay blocked for every disc to come (the radii only decrease): they are not walked
|
|
328
|
+
again (Django's 919 communities: from 65 s to a few)."""
|
|
329
|
+
import numpy as np # here: the queries do not pay for it
|
|
330
|
+
|
|
331
|
+
discs = np.array(placed)
|
|
332
|
+
for start in itertools.count(open_from, 1024):
|
|
333
|
+
steps = np.arange(start, start + 1024)
|
|
334
|
+
distance = 2.0 * np.sqrt(steps + 1) * 3.0
|
|
335
|
+
gap = np.hypot(distance * np.cos(steps * 0.5) - discs[:, 0, None],
|
|
336
|
+
distance * np.sin(steps * 0.5) - discs[:, 1, None]) - discs[:, 2, None]
|
|
337
|
+
if start == open_from:
|
|
338
|
+
forever = (gap < smallest + 1.0 - 1e-6).any(axis=0)
|
|
339
|
+
open_from += 1024 if forever.all() else int(np.argmin(forever))
|
|
340
|
+
for step in np.flatnonzero(~(gap < radius + 1.0 - 1e-6).any(axis=0)) + start:
|
|
341
|
+
angle, distance = int(step) * 0.5, 2.0 * math.sqrt(int(step) + 1) * 3.0
|
|
342
|
+
center = (distance * math.cos(angle), distance * math.sin(angle))
|
|
343
|
+
if all(math.dist(center, (x, y)) >= r + radius + 1.0 for x, y, r in placed):
|
|
344
|
+
return center, open_from
|
|
345
|
+
raise AssertionError("unreachable: the spiral leaves every disc behind")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def layout(graph: nx.DiGraph, community_of: dict[str, int]) -> dict[str, tuple[float, float]]:
|
|
349
|
+
"""Each community laid out alone in a disc, the discs set in a spiral
|
|
350
|
+
from the largest to the smallest: much faster than a whole layout
|
|
351
|
+
(15 s for 2400 nodes), and without overlap."""
|
|
352
|
+
members = defaultdict(list)
|
|
353
|
+
for n, i in community_of.items():
|
|
354
|
+
members[i].append(n)
|
|
355
|
+
placed: list[tuple[float, float, float]] = []
|
|
356
|
+
positions = {}
|
|
357
|
+
smallest, open_from = math.sqrt(min(map(len, members.values()), default=1)) * 1.6 + 1.0, 0
|
|
358
|
+
for i in sorted(members, key=lambda i: (-len(members[i]), i)):
|
|
359
|
+
radius = math.sqrt(len(members[i])) * 1.6 + 1.0
|
|
360
|
+
center = (0.0, 0.0)
|
|
361
|
+
if placed:
|
|
362
|
+
center, open_from = _first_free(placed, radius, smallest, open_from)
|
|
363
|
+
placed.append((*center, radius))
|
|
364
|
+
# T-0381: not graph.subgraph(), which walks its nodes in the order of a set (the luck of hashing)
|
|
365
|
+
group = sorted(members[i])
|
|
366
|
+
if len(group) > LARGE_COMMUNITY:
|
|
367
|
+
local = _sunflower(graph, group)
|
|
368
|
+
else:
|
|
369
|
+
inside = set(group)
|
|
370
|
+
sub = nx.Graph()
|
|
371
|
+
sub.add_nodes_from(group)
|
|
372
|
+
sub.add_edges_from((s, t) for s, t in graph.edges(group) if t in inside)
|
|
373
|
+
local = nx.spring_layout(sub, seed=0, iterations=60) if len(members[i]) > 1 else {members[i][0]: (0, 0)}
|
|
374
|
+
for n, (x, y) in local.items():
|
|
375
|
+
positions[n] = (round(center[0] + x * radius * 0.92, 2), round(center[1] + y * radius * 0.92, 2))
|
|
376
|
+
return positions
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _write(path: Path, text: str) -> None:
|
|
380
|
+
"""Writes alongside then replaces: two builds in a row never leave a
|
|
381
|
+
half-written file."""
|
|
382
|
+
with tempfile.NamedTemporaryFile("wb", dir=path.parent, delete=False, suffix=".tmp") as f:
|
|
383
|
+
f.write(text.encode("utf-8"))
|
|
384
|
+
os.replace(f.name, path)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
# T-0025: the verdicts of a call no link leads from: a name of ours, perhaps, but the reader could not tell which.
|
|
388
|
+
UNATTRIBUTED = {"ambiguous", "unknown", "absent", "attribute", "member", "external?", "common"} # `dynamic` has no name
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _unattributed(graph: nx.DiGraph, sites: dict[str, list[dict]]) -> dict[str, int]:
|
|
392
|
+
"""The calls not attributed, by the name of a function or a method of ours (`filter`): what grep would find and
|
|
393
|
+
the graph does not."""
|
|
394
|
+
ours = {graph.nodes[n]["name"].rsplit(".", 1)[-1] for n in graph if graph.nodes[n]["kind"] in ("function", "method")}
|
|
395
|
+
counted = Counter(s["name"] for site_list in sites.values() for s in site_list
|
|
396
|
+
if s.get("verdict") in UNATTRIBUTED and s.get("name") in ours)
|
|
397
|
+
return dict(sorted(counted.items()))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _missed(graph: nx.DiGraph, n: str) -> None:
|
|
401
|
+
"""T-0025: the line that tells the agent when to grep."""
|
|
402
|
+
d = graph.nodes[n]
|
|
403
|
+
name = d["name"].rsplit(".", 1)[-1]
|
|
404
|
+
count = graph.graph["unattributed"].get(name, 0) if d["kind"] in ("function", "method") else 0
|
|
405
|
+
if count:
|
|
406
|
+
print(f" + {count} calls named `{name}` the graph could not attribute: grep them")
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def build(quiet: bool = False) -> int:
|
|
410
|
+
start = time.monotonic()
|
|
411
|
+
OUTPUT.mkdir(exist_ok=True)
|
|
412
|
+
graph, coverage, dangling, sites = assemble()
|
|
413
|
+
community_of, names = communities(graph)
|
|
414
|
+
data = {
|
|
415
|
+
"built": time.strftime("%Y-%m-%d %H:%M:%S"), "built_s": time.time(), "commit": _commit(),
|
|
416
|
+
"coverage": coverage, "communities": {str(i): name for i, name in names.items()},
|
|
417
|
+
"unattributed": _unattributed(graph, sites),
|
|
418
|
+
"nodes": [{**graph.nodes[n], "community": community_of[n]} for n in graph.nodes],
|
|
419
|
+
"links": [{"source": s, "target": t, "relations": sorted(d["relations"]), "confidence": d["confidence"],
|
|
420
|
+
"locations": d["locations"], "contexts": d["contexts"]} for s, t, d in graph.edges(data=True)],
|
|
421
|
+
}
|
|
422
|
+
_write(JSON, json.dumps(data, ensure_ascii=False))
|
|
423
|
+
_write(OUTPUT / "REPORT.md", report(graph, data, community_of, names))
|
|
424
|
+
if not quiet:
|
|
425
|
+
print(f"{graph.number_of_nodes()} nodes, {graph.number_of_edges()} links, {len(names)} communities, "
|
|
426
|
+
f"{len(dangling)} dangling link(s) - {time.monotonic() - start:.1f} s -> {OUTPUT.relative_to(ROOT)}/")
|
|
427
|
+
for e in dangling[:10]:
|
|
428
|
+
print(" dangling", e["source"], "->", e["target"], e["relation"], e["source_file"], e["source_location"])
|
|
429
|
+
return 0
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
# ---------- the report
|
|
433
|
+
|
|
434
|
+
def _location(graph: nx.DiGraph, n: str) -> str:
|
|
435
|
+
d = graph.nodes[n]
|
|
436
|
+
return f"{d['source_file']}:{d['source_location'].lstrip('L')}"
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def report(graph: nx.DiGraph, data: dict, community_of: dict, names: dict) -> str:
|
|
440
|
+
c = data["coverage"]
|
|
441
|
+
kinds = Counter(d["kind"] for _, d in graph.nodes(data=True))
|
|
442
|
+
lines = [
|
|
443
|
+
"# The code graph", "",
|
|
444
|
+
f"Built on {data['built']} (commit {data['commit']}, working tree included) "
|
|
445
|
+
"by `graphe build`.", "",
|
|
446
|
+
f"- {graph.number_of_nodes()} nodes: " + ", ".join(f"{n} {k}" for k, n in kinds.most_common()),
|
|
447
|
+
f"- {graph.number_of_edges()} links, {len(names)} communities, {c['dangling']} dangling link(s)",
|
|
448
|
+
f"- Python calls classified: {c['python']}",
|
|
449
|
+
f"- GDScript calls classified: {c['godot']}",
|
|
450
|
+
"", "`ours`: linked for sure; `ours?`: linked by name alone (INFERRED); `ambiguous`: a name that "
|
|
451
|
+
"several of our functions bear, on an untyped receiver - not linked; `external`, `engine`: "
|
|
452
|
+
"outside the repository. Details: `graphe check`.", "",
|
|
453
|
+
"## Most connected", "",
|
|
454
|
+
]
|
|
455
|
+
def real(links) -> int: # without containment (file, class -> function)
|
|
456
|
+
return sum(1 for *_, d in links if d["relations"] - {"contains", "method"})
|
|
457
|
+
incoming = {n: real(graph.in_edges(n, data=True)) for n in graph.nodes}
|
|
458
|
+
outgoing = {n: real(graph.out_edges(n, data=True)) for n in graph.nodes}
|
|
459
|
+
central = sorted((n for n in graph.nodes if graph.nodes[n]["kind"] != "file"),
|
|
460
|
+
key=lambda n: (-incoming[n] - outgoing[n], n))[:20]
|
|
461
|
+
for n in central:
|
|
462
|
+
lines.append(f"- `{graph.nodes[n]['label']}` - {incoming[n]} incoming, "
|
|
463
|
+
f"{outgoing[n]} outgoing ({_location(graph, n)})")
|
|
464
|
+
commands = sorted(n for n in graph.nodes if graph.nodes[n]["kind"] == "command")
|
|
465
|
+
if commands:
|
|
466
|
+
lines += ["", "## Commands", "", "Each command: who sends it, what it calls.", ""]
|
|
467
|
+
for n in commands:
|
|
468
|
+
senders = sorted({graph.nodes[s]["label"] for s in graph.predecessors(n)
|
|
469
|
+
if "sends" in graph[s][n]["relations"]})
|
|
470
|
+
callees = sorted({graph.nodes[x]["label"] for x in graph.successors(n)})
|
|
471
|
+
lines.append(f"- `{graph.nodes[n]['label']}`: sent by "
|
|
472
|
+
f"{', '.join(senders) or 'nobody'}; calls "
|
|
473
|
+
f"{', '.join(callees[:8]) or '-'}{' …' if len(callees) > 8 else ''}")
|
|
474
|
+
imports = nx.DiGraph()
|
|
475
|
+
for s, target, d in graph.edges(data=True):
|
|
476
|
+
ss, tt = graph.nodes[s]["source_file"], graph.nodes[target]["source_file"]
|
|
477
|
+
if "imports" in d["relations"] and graph.nodes[s]["kind"] == "file" and ss != tt:
|
|
478
|
+
imports.add_edge(ss, tt)
|
|
479
|
+
cycles = sorted((cy for cy in nx.simple_cycles(imports, length_bound=4)), key=lambda cy: (len(cy), cy))[:20]
|
|
480
|
+
lines += ["", "## Import cycles (module level)", ""]
|
|
481
|
+
lines += [f"- {' → '.join(cy + cy[:1])}" for cy in cycles] or ["None."]
|
|
482
|
+
lines += ["", "## Communities", ""]
|
|
483
|
+
members = defaultdict(list)
|
|
484
|
+
for n, i in community_of.items():
|
|
485
|
+
members[i].append(n)
|
|
486
|
+
small = 0
|
|
487
|
+
for i in sorted(members):
|
|
488
|
+
if len(members[i]) < 4:
|
|
489
|
+
small += 1
|
|
490
|
+
continue
|
|
491
|
+
top = sorted(members[i], key=lambda n: (-graph.degree(n), n))[:8]
|
|
492
|
+
lines += [f"### {i} - {names[i]} ({len(members[i])} nodes)", "",
|
|
493
|
+
", ".join(f"`{graph.nodes[n]['label']}`" for n in top), ""]
|
|
494
|
+
lines += [f"{small} small communities (fewer than 4 nodes) not detailed.", "",
|
|
495
|
+
"## What the graph does not see", "",
|
|
496
|
+
"- dynamic calls: `getattr`, a callback stored in a variable, a receiver that nothing "
|
|
497
|
+
"types (the `ambiguous` ones);",
|
|
498
|
+
"- files that no reader takes, and those that `exclude` removes (graphe.toml).", ""]
|
|
499
|
+
return "\n".join(lines)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
# ---------- the page
|
|
503
|
+
|
|
504
|
+
def page(data: dict) -> str:
|
|
505
|
+
nodes = data["nodes"]
|
|
506
|
+
index = {n["id"]: i for i, n in enumerate(nodes)}
|
|
507
|
+
compact = {
|
|
508
|
+
"n": [[n["label"], n["source_file"], n["source_location"].lstrip("L"), n["community"], n["x"], n["y"],
|
|
509
|
+
n["kind"], n["id"]] for n in nodes],
|
|
510
|
+
"l": [[index[e["source"]], index[e["target"]], ",".join(e["relations"]), e["confidence"] == "EXTRACTED"]
|
|
511
|
+
for e in data["links"]],
|
|
512
|
+
"c": data["communities"], "t": data["built"], "k": data["commit"],
|
|
513
|
+
}
|
|
514
|
+
text = json.dumps(compact, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
|
|
515
|
+
return PAGE.replace("__DATA__", text)
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
PAGE = r"""<!doctype html>
|
|
519
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
520
|
+
<title>Code graph</title>
|
|
521
|
+
<style>
|
|
522
|
+
:root{--bg:#f7f7f5;--text:#1d1d1b;--muted:#6b6b66;--panel:#ffffff;--border:#deded8;--link:rgba(60,60,60,.10);--pick:#d4572a}
|
|
523
|
+
@media (prefers-color-scheme:dark){:root{--bg:#161615;--text:#e8e8e3;--muted:#9a9a93;--panel:#1f1f1d;--border:#34342f;--link:rgba(220,220,210,.09);--pick:#f08a5d}}
|
|
524
|
+
*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--text);font:14px/1.4 system-ui,sans-serif}
|
|
525
|
+
#map{position:fixed;top:0;left:0;width:calc(100% - 340px);height:100%;cursor:grab;touch-action:none}#map.dragging{cursor:grabbing}
|
|
526
|
+
#side{position:fixed;top:0;right:0;bottom:0;width:340px;background:var(--panel);border-left:1px solid var(--border);display:flex;flex-direction:column;overflow-x:hidden}
|
|
527
|
+
#side header{padding:12px 14px;border-bottom:1px solid var(--border)}#side h1{font-size:15px;margin:0 0 6px}
|
|
528
|
+
#side input[type=search]{width:100%;padding:7px 9px;border:1px solid var(--border);border-radius:6px;background:var(--bg);color:var(--text);font:inherit}
|
|
529
|
+
#side label{display:block;margin-top:8px;color:var(--muted);font-size:12px}
|
|
530
|
+
#card{padding:12px 14px;overflow:auto;flex:1}#card h2{font-size:15px;margin:0 0 2px;word-break:break-all}
|
|
531
|
+
#card .where{color:var(--muted);font-size:12px;margin-bottom:10px;word-break:break-all}#card h3{font-size:12px;text-transform:uppercase;letter-spacing:.04em;color:var(--muted);margin:14px 0 4px}
|
|
532
|
+
#card a{color:var(--text);text-decoration:none;display:block;padding:2px 0;border-bottom:1px dotted transparent;cursor:pointer;word-break:break-all}
|
|
533
|
+
#card a:hover{color:var(--pick)}#card .rel{color:var(--muted);font-size:11px}
|
|
534
|
+
@media (max-width:760px){#map{width:100%;height:55vh}#side{top:auto;height:45vh;width:100%;border-left:0;border-top:1px solid var(--border)}}
|
|
535
|
+
</style></head><body>
|
|
536
|
+
<canvas id="map"></canvas>
|
|
537
|
+
<aside id="side"><header><h1>Code graph</h1><input id="search" type="search" list="names" placeholder="Search a function, a file…" autocomplete="off"><datalist id="names"></datalist>
|
|
538
|
+
<label><input id="contains" type="checkbox"> containment links (file → function)</label></header>
|
|
539
|
+
<div id="card"></div></aside>
|
|
540
|
+
<script id="data" type="application/json">__DATA__</script>
|
|
541
|
+
<script>
|
|
542
|
+
const D=JSON.parse(document.getElementById('data').textContent);
|
|
543
|
+
const N=D.n.map((n,i)=>({i,label:n[0],file:n[1],line:n[2],c:n[3],x:n[4],y:n[5],kind:n[6],id:n[7],outs:[],ins:[]}));
|
|
544
|
+
const L=D.l.map(l=>({s:l[0],t:l[1],rel:l[2],sure:l[3]}));
|
|
545
|
+
for(const l of L){N[l.s].outs.push(l);N[l.t].ins.push(l)}
|
|
546
|
+
for(const n of N){n.deg=n.outs.length+n.ins.length;n.r=1.2+Math.sqrt(n.deg)*0.45}
|
|
547
|
+
const hue=c=>`hsl(${(c*137.508)%360},55%,52%)`;
|
|
548
|
+
const cv=document.getElementById('map'),cx=cv.getContext('2d');
|
|
549
|
+
let fit=1,view={x:0,y:0,z:1},picked=null,neighbours=new Set(),showContains=false;
|
|
550
|
+
function resize(){const r=cv.getBoundingClientRect(),d=devicePixelRatio||1;cv.width=r.width*d;cv.height=r.height*d;cx.setTransform(d,0,0,d,0,0);draw()}
|
|
551
|
+
function frame(){let a=1e9,b=1e9,c=-1e9,e=-1e9;for(const n of N){a=Math.min(a,n.x);b=Math.min(b,n.y);c=Math.max(c,n.x);e=Math.max(e,n.y)}
|
|
552
|
+
const r=cv.getBoundingClientRect();view.z=fit=Math.min(r.width/(c-a+10),r.height/(e-b+10));view.x=r.width/2-(a+c)/2*view.z;view.y=r.height/2-(b+e)/2*view.z}
|
|
553
|
+
const screen=n=>[n.x*view.z+view.x,n.y*view.z+view.y];
|
|
554
|
+
function color(v){return getComputedStyle(document.documentElement).getPropertyValue(v)}
|
|
555
|
+
function draw(){const r=cv.getBoundingClientRect();cx.clearRect(0,0,r.width,r.height);
|
|
556
|
+
cx.lineWidth=1;cx.strokeStyle=color('--link');cx.beginPath();
|
|
557
|
+
for(const l of L){if(!showContains&&(l.rel==='contains'||l.rel==='method'))continue;const[a,b]=screen(N[l.s]),[c,d]=screen(N[l.t]);cx.moveTo(a,b);cx.lineTo(c,d)}cx.stroke();
|
|
558
|
+
if(picked){cx.strokeStyle=color('--pick');cx.lineWidth=1.5;cx.beginPath();for(const l of picked.outs.concat(picked.ins)){const[a,b]=screen(N[l.s]),[c,d]=screen(N[l.t]);cx.moveTo(a,b);cx.lineTo(c,d)}cx.stroke()}
|
|
559
|
+
for(const n of N){const[x,y]=screen(n);if(x<-20||y<-20||x>r.width+20||y>r.height+20)continue;const rr=Math.max(1.5,n.r*Math.sqrt(view.z));
|
|
560
|
+
cx.globalAlpha=picked&&!neighbours.has(n.i)&&n!==picked?0.25:1;cx.fillStyle=n===picked?color('--pick'):hue(n.c);cx.beginPath();cx.arc(x,y,rr,0,7);cx.fill()}
|
|
561
|
+
cx.globalAlpha=1;cx.fillStyle=color('--text');
|
|
562
|
+
// Labels that do not overlap: the most linked first.
|
|
563
|
+
const placed=[],free=(x,y,w)=>{for(const p of placed)if(x<p[2]&&x+w>p[0]&&y-11<p[3]&&y+3>p[1])return false;placed.push([x,y-11,x+w,y+3]);return true};
|
|
564
|
+
if(view.z>fit*2.5){cx.font='12px system-ui';const shown=N.filter(n=>{const[x,y]=screen(n);return x>0&&y>0&&x<r.width&&y<r.height&&(!picked||neighbours.has(n.i)||n===picked)});
|
|
565
|
+
shown.sort((a,b)=>(b===picked)-(a===picked)||b.deg-a.deg);for(const n of shown.slice(0,600)){const[x,y]=screen(n),w=cx.measureText(n.label).width;if(free(x+4,y-3,w))cx.fillText(n.label,x+4,y-3)}}
|
|
566
|
+
else{const centers={};for(const n of N){const c=centers[n.c]||(centers[n.c]={x:0,y:0,k:0});c.x+=n.x;c.y+=n.y;c.k++}
|
|
567
|
+
cx.font='600 12px system-ui';for(const c of Object.keys(centers).sort((a,b)=>centers[b].k-centers[a].k)){const v=centers[c];const w=cx.measureText(D.c[c]).width,x=(v.x/v.k)*view.z+view.x-w/2,y=(v.y/v.k)*view.z+view.y;if(free(x,y,w))cx.fillText(D.c[c],x,y)}}}
|
|
568
|
+
function link(n){return `<a data-i="${n.i}">${esc(n.label)} <span class="rel">${esc(n.file)}:${n.line}</span></a>`}
|
|
569
|
+
function esc(s){return String(s).replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]))}
|
|
570
|
+
function group(list,end){const g={};for(const l of list){for(const r of l.rel.split(','))(g[r]=g[r]||[]).push(N[l[end]])}
|
|
571
|
+
return Object.keys(g).sort().map(r=>`<h3>${esc(r)} (${g[r].length})</h3>`+g[r].sort((a,b)=>a.label.localeCompare(b.label)).map(link).join('')).join('')}
|
|
572
|
+
function pick(n,center){picked=n;neighbours=new Set();if(n){for(const l of n.outs)neighbours.add(l.t);for(const l of n.ins)neighbours.add(l.s)}
|
|
573
|
+
const f=document.getElementById('card');
|
|
574
|
+
if(!n){f.innerHTML=`<p class="where">${N.length} nodes, ${L.length} links. Built on ${esc(D.t)} (commit ${esc(D.k)}).</p><p class="where">Wheel: zoom. Drag: move. Click: a node and its links.</p>`}
|
|
575
|
+
else{f.innerHTML=`<h2>${esc(n.label)}</h2><div class="where">${esc(n.kind)} · ${esc(n.file)}:${n.line} · ${esc(D.c[n.c])}<br>${esc(n.id)}</div><h3 style="color:var(--text)">What it calls</h3>${group(n.outs.filter(l=>l.rel!=='contains'&&l.rel!=='method'),'t')||'<p class=where>nothing</p>'}<h3 style="color:var(--text)">What calls it</h3>${group(n.ins.filter(l=>l.rel!=='contains'&&l.rel!=='method'),'s')||'<p class=where>nothing</p>'}`}
|
|
576
|
+
if(n&¢er){const r=cv.getBoundingClientRect();view.z=Math.max(view.z,fit*6);view.x=r.width/2-n.x*view.z;view.y=r.height/2-n.y*view.z}draw()}
|
|
577
|
+
document.getElementById('card').addEventListener('click',e=>{const a=e.target.closest('a[data-i]');if(a)pick(N[+a.dataset.i],true)});
|
|
578
|
+
const dl=document.getElementById('names');dl.innerHTML=N.map(n=>`<option value="${esc(n.label)} — ${esc(n.file)}">`).join('');
|
|
579
|
+
document.getElementById('search').addEventListener('change',e=>{const v=e.target.value.split(' — ');const n=N.find(n=>n.label===v[0]&&(!v[1]||n.file===v[1]))||N.find(n=>n.label.toLowerCase().includes(v[0].toLowerCase()));if(n)pick(n,true)});
|
|
580
|
+
document.getElementById('contains').addEventListener('change',e=>{showContains=e.target.checked;draw()});
|
|
581
|
+
let drag=null,moved=false;
|
|
582
|
+
cv.addEventListener('pointerdown',e=>{drag={x:e.clientX,y:e.clientY,vx:view.x,vy:view.y};moved=false;cv.classList.add('dragging');cv.setPointerCapture(e.pointerId)});
|
|
583
|
+
cv.addEventListener('pointermove',e=>{if(!drag)return;const dx=e.clientX-drag.x,dy=e.clientY-drag.y;if(Math.abs(dx)+Math.abs(dy)>3)moved=true;view.x=drag.vx+dx;view.y=drag.vy+dy;draw()});
|
|
584
|
+
cv.addEventListener('pointerup',e=>{cv.classList.remove('dragging');if(!moved){const r=cv.getBoundingClientRect(),px=e.clientX-r.left,py=e.clientY-r.top;let m=null,dm=144;
|
|
585
|
+
for(const n of N){const[x,y]=screen(n),d=(x-px)**2+(y-py)**2;if(d<dm){dm=d;m=n}}pick(m,false)}drag=null});
|
|
586
|
+
cv.addEventListener('wheel',e=>{e.preventDefault();const r=cv.getBoundingClientRect(),px=e.clientX-r.left,py=e.clientY-r.top,f=Math.exp(-e.deltaY*0.0015);
|
|
587
|
+
view.x=px-(px-view.x)*f;view.y=py-(py-view.y)*f;view.z*=f;draw()},{passive:false});
|
|
588
|
+
addEventListener('resize',resize);resize();frame();pick(null);
|
|
589
|
+
// graphe.html#<id> opens that node.
|
|
590
|
+
const anchor=()=>{const n=N.find(n=>n.id===decodeURIComponent(location.hash.slice(1)));if(n)pick(n,true)};addEventListener('hashchange',anchor);anchor();
|
|
591
|
+
</script></body></html>
|
|
592
|
+
"""
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
# ---------- the queries
|
|
596
|
+
|
|
597
|
+
def load(as_is: bool = False) -> nx.DiGraph:
|
|
598
|
+
"""The graph; rebuilt first if it is older than the host's code or than the tool."""
|
|
599
|
+
if not JSON.exists() or (not as_is and max((p.stat().st_mtime for p in _sources() + _tool()), default=0)
|
|
600
|
+
> JSON.stat().st_mtime):
|
|
601
|
+
print("(the graph is older than the code or the tool: rebuilding)", file=sys.stderr)
|
|
602
|
+
build(quiet=True)
|
|
603
|
+
data = json.loads(JSON.read_bytes())
|
|
604
|
+
graph = nx.DiGraph(communities=data["communities"], unattributed=data.get("unattributed", {}))
|
|
605
|
+
for n in data["nodes"]:
|
|
606
|
+
graph.add_node(n["id"], **n)
|
|
607
|
+
for e in data["links"]:
|
|
608
|
+
graph.add_edge(e["source"], e["target"], **{k: v for k, v in e.items() if k not in ("source", "target")})
|
|
609
|
+
return graph
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _bare(label: str) -> str:
|
|
613
|
+
return label.removesuffix("()").lstrip(".")
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _preloads(root: Path = ROOT) -> dict[str, set[str]]:
|
|
617
|
+
"""The constants that preload a GDScript script, and that script:
|
|
618
|
+
`const Outils = preload("res://menu/outils.gd")` -> godot/menu/outils.gd (godot.GODOT)."""
|
|
619
|
+
pattern = re.compile(r'^const\s+(\w+)\s*=\s*preload\("res://([^"]+\.gd)"\)', re.M)
|
|
620
|
+
alias: dict[str, set[str]] = defaultdict(set)
|
|
621
|
+
for script in godot.scripts():
|
|
622
|
+
for name, target in pattern.findall(script.read_bytes().decode("utf-8", "replace")):
|
|
623
|
+
alias[name].add(godot.res(target))
|
|
624
|
+
return alias
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def find(graph: nx.DiGraph, text: str) -> list[str]:
|
|
628
|
+
if text in graph:
|
|
629
|
+
return [text]
|
|
630
|
+
file, _, name = text.rpartition("::")
|
|
631
|
+
found = []
|
|
632
|
+
for n, d in graph.nodes(data=True):
|
|
633
|
+
if file and not (d["source_file"].endswith(file) or file in d["source_file"]):
|
|
634
|
+
continue
|
|
635
|
+
if name in (d["name"], _bare(d["label"]), d["label"]) or d["name"].endswith("." + name) \
|
|
636
|
+
or (d["kind"] == "file" and name == d["source_file"]): # T-0016: a file as the answers print it
|
|
637
|
+
found.append(n)
|
|
638
|
+
exact = [n for n in found if graph.nodes[n]["name"] == name] # a method's label is `.cle()`: not exact
|
|
639
|
+
if file and len(exact) == 1: # T-0016: in a file, `cle` is the variable, not `Gabarit.cle` too
|
|
640
|
+
return exact
|
|
641
|
+
if not found and not file and "." in name:
|
|
642
|
+
# `Outils.aider`: Outils preloads godot/menu/outils.gd.
|
|
643
|
+
head, _, member = name.partition(".")
|
|
644
|
+
scripts = _preloads().get(head, set())
|
|
645
|
+
found = [n for n, d in graph.nodes(data=True)
|
|
646
|
+
if d["source_file"] in scripts and member in (d["name"], _bare(d["label"]))]
|
|
647
|
+
return sorted(found)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _one(graph: nx.DiGraph, text: str) -> str | None:
|
|
651
|
+
found = find(graph, text)
|
|
652
|
+
if len(found) == 1:
|
|
653
|
+
return found[0]
|
|
654
|
+
if not found:
|
|
655
|
+
print(f"no node for {text!r} - try: graphe search {text}")
|
|
656
|
+
else:
|
|
657
|
+
print(f"{text!r} designates {len(found)} nodes; pick one:")
|
|
658
|
+
for n in found[:20]: # each designation scans the graph: Django has 972 `__init__`
|
|
659
|
+
print(f" {_designation(graph, n)} {_location(graph, n)}")
|
|
660
|
+
if len(found) > 20:
|
|
661
|
+
print(f" ... and {len(found) - 20} more: narrow it by file::name")
|
|
662
|
+
return None
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def _designation(graph: nx.DiGraph, n: str) -> str:
|
|
666
|
+
"""T-0016: the shortest text that designates n alone, `Class.method` or `file::name`; else its id."""
|
|
667
|
+
d = graph.nodes[n]
|
|
668
|
+
for text in (d["name"], f"{d['source_file']}::{d['name']}", f"{d['source_file']}::{_bare(d['label'])}"):
|
|
669
|
+
if find(graph, text) == [n]:
|
|
670
|
+
return text
|
|
671
|
+
return n
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def _line(graph: nx.DiGraph, n: str) -> int:
|
|
675
|
+
return int(graph.nodes[n]["source_location"].lstrip("L") or 0)
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _by_file(graph: nx.DiGraph, nodes, suffix: dict[str, str] | None = None) -> list[str]:
|
|
679
|
+
"""T-0016: nodes as the agent designates them next, one line per file (`file: Class.method:line, ...`); the
|
|
680
|
+
kinds outside the code (tickets, values) by their name alone, on one line."""
|
|
681
|
+
separate, _ = _communities_config()
|
|
682
|
+
suffix = suffix or {}
|
|
683
|
+
off, files = [], defaultdict(list)
|
|
684
|
+
for n in sorted(nodes, key=lambda n: (graph.nodes[n]["source_file"], _line(graph, n), n)):
|
|
685
|
+
d = graph.nodes[n]
|
|
686
|
+
if d["kind"] in separate:
|
|
687
|
+
off.append(d["name"] + suffix.get(n, ""))
|
|
688
|
+
else:
|
|
689
|
+
files[d["source_file"]].append(("(file)" if d["kind"] == "file" else f"{d['name']}:{_line(graph, n)}")
|
|
690
|
+
+ suffix.get(n, ""))
|
|
691
|
+
return ([", ".join(off)] if off else []) + [file if entries == ["(file)"] else f"{file}: {', '.join(entries)}"
|
|
692
|
+
for file, entries in files.items()]
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _label(graph: nx.DiGraph, n: str) -> str:
|
|
696
|
+
d = graph.nodes[n]
|
|
697
|
+
return d["source_file"] if d["kind"] == "file" else f"{d['name']} ({_location(graph, n)})"
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def path(graph: nx.DiGraph, a: str, b: str, undirected: bool) -> int:
|
|
701
|
+
source, target = _one(graph, a), _one(graph, b)
|
|
702
|
+
if source is None or target is None:
|
|
703
|
+
return 2
|
|
704
|
+
view = graph.to_undirected(as_view=True) if undirected else graph
|
|
705
|
+
separate, _ = _communities_config()
|
|
706
|
+
|
|
707
|
+
def weight(x: str, y: str, _d: dict) -> int:
|
|
708
|
+
# T-0354: without the direction, a value or a ticket links everything
|
|
709
|
+
# that writes it; it serves only for want of a path through the code.
|
|
710
|
+
off_code = graph.nodes[x]["kind"] in separate or graph.nodes[y]["kind"] in separate
|
|
711
|
+
return OFF_CODE_WEIGHT if undirected and off_code else 1
|
|
712
|
+
|
|
713
|
+
try:
|
|
714
|
+
steps = nx.shortest_path(view, source, target, weight=weight)
|
|
715
|
+
except nx.NetworkXNoPath:
|
|
716
|
+
print("no path" + ("" if undirected else " in the direction of the links (try --undirected)"))
|
|
717
|
+
return 1
|
|
718
|
+
print(f"{len(steps) - 1} step(s):")
|
|
719
|
+
print(f" {_label(graph, steps[0])}")
|
|
720
|
+
for x, y in zip(steps, steps[1:], strict=False):
|
|
721
|
+
direction, d = ("-->", graph[x][y]) if graph.has_edge(x, y) else ("<--", graph[y][x])
|
|
722
|
+
sure = "" if d["confidence"] == "EXTRACTED" else " [by name]"
|
|
723
|
+
print(f" {direction} {','.join(d['relations'])}{sure} {d['locations'][0]}")
|
|
724
|
+
print(f" {_label(graph, y)}")
|
|
725
|
+
return 0
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def source_text(graph: nx.DiGraph, n: str) -> str:
|
|
729
|
+
"""The node's lines, numbered; "" without a known extent."""
|
|
730
|
+
d = graph.nodes[n]
|
|
731
|
+
start, end = int(d["source_location"].lstrip("L") or 0), int(d.get("end", 0))
|
|
732
|
+
if not end or not (ROOT / d["source_file"]).is_file():
|
|
733
|
+
return ""
|
|
734
|
+
lines = (ROOT / d["source_file"]).read_bytes().decode("utf-8", "replace").splitlines()
|
|
735
|
+
return "\n".join(f"{i:5d} {lines[i - 1]}" for i in range(start, min(end, len(lines)) + 1))
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def view(graph: nx.DiGraph, x: str | None) -> int:
|
|
739
|
+
"""T-0046: the page, on demand only: the build no longer pays for the layout. Its positions are those the build
|
|
740
|
+
gave: the graph read back from graphe.json keeps the order of its nodes and links (T-0381)."""
|
|
741
|
+
n = _one(graph, x) if x else ""
|
|
742
|
+
if n is None:
|
|
743
|
+
return 2
|
|
744
|
+
data = json.loads(JSON.read_bytes())
|
|
745
|
+
positions = layout(graph, {m: d["community"] for m, d in graph.nodes(data=True)})
|
|
746
|
+
for node in data["nodes"]:
|
|
747
|
+
node["x"], node["y"] = positions[node["id"]]
|
|
748
|
+
_write(OUTPUT / "graphe.html", page(data))
|
|
749
|
+
webbrowser.open((OUTPUT / "graphe.html").resolve().as_uri() + (f"#{n}" if n else ""))
|
|
750
|
+
return 0
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def explain(graph: nx.DiGraph, x: str, all_: bool, code: bool = False) -> int:
|
|
754
|
+
n = _one(graph, x)
|
|
755
|
+
if n is None:
|
|
756
|
+
return 2
|
|
757
|
+
d = graph.nodes[n]
|
|
758
|
+
end = f"-{d['end']}" if d.get("end") and d["end"] != int(d["source_location"].lstrip("L") or 0) else ""
|
|
759
|
+
print(f"{d['label']} [{d['kind']}] {_location(graph, n)}{end}")
|
|
760
|
+
print(f" id: {n}")
|
|
761
|
+
print(f" community: {graph.graph['communities'][str(d['community'])]}")
|
|
762
|
+
if d.get("notes"):
|
|
763
|
+
print(f" note: {d['notes'][:300]}")
|
|
764
|
+
for text in d.get("texts", [])[:10]:
|
|
765
|
+
print(f" displays: {text}")
|
|
766
|
+
if code:
|
|
767
|
+
print("\n" + (source_text(graph, n) or " (no known extent)"))
|
|
768
|
+
limit = None if all_ else 25
|
|
769
|
+
for title, pairs in (("what it calls", [(t, graph[n][t]) for t in graph.successors(n)]),
|
|
770
|
+
("what calls it", [(s, graph[s][n]) for s in graph.predecessors(n)])):
|
|
771
|
+
by_relation = defaultdict(list)
|
|
772
|
+
for other, link in pairs:
|
|
773
|
+
for r in link["relations"]:
|
|
774
|
+
by_relation[r].append((other, link))
|
|
775
|
+
print(f"\n{title}:" + ("" if by_relation else " nothing"))
|
|
776
|
+
for r in sorted(by_relation):
|
|
777
|
+
inferred = {other for other, link in by_relation[r] if link["confidence"] != "EXTRACTED"}
|
|
778
|
+
every = len(inferred) == len(by_relation[r]) # the mark once, on the relation
|
|
779
|
+
print(f" {r} ({len(by_relation[r])})" + (" [by name]" if every else
|
|
780
|
+
f" [{len(inferred)} by name: ?]" if inferred else ""))
|
|
781
|
+
shown = sorted(by_relation[r], key=lambda p: (graph.nodes[p[0]]["source_file"], _line(graph, p[0])))
|
|
782
|
+
for line in _by_file(graph, [other for other, _ in shown[:limit]],
|
|
783
|
+
{} if every else dict.fromkeys(inferred, "?")):
|
|
784
|
+
print(f" {line}")
|
|
785
|
+
if limit and len(by_relation[r]) > limit:
|
|
786
|
+
print(f" ... and {len(by_relation[r]) - limit} more (--all)")
|
|
787
|
+
_missed(graph, n) # under "what calls it", the last
|
|
788
|
+
return 0
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def callers(graph: nx.DiGraph, x: str, depth: int) -> int:
|
|
792
|
+
n = _one(graph, x)
|
|
793
|
+
if n is None:
|
|
794
|
+
return 2
|
|
795
|
+
seen, front = {n}, [n]
|
|
796
|
+
for level in range(1, depth + 1):
|
|
797
|
+
following = []
|
|
798
|
+
for y in front:
|
|
799
|
+
for s in graph.predecessors(y):
|
|
800
|
+
if s not in seen and CALLS & set(graph[s][y]["relations"]):
|
|
801
|
+
seen.add(s)
|
|
802
|
+
following.append(s)
|
|
803
|
+
if not following:
|
|
804
|
+
break
|
|
805
|
+
print(f"level {level} ({len(following)}):")
|
|
806
|
+
for line in _by_file(graph, following):
|
|
807
|
+
print(f" {line}")
|
|
808
|
+
front = following
|
|
809
|
+
if len(seen) == 1:
|
|
810
|
+
print("nothing calls it (in what the graph sees)")
|
|
811
|
+
_missed(graph, n)
|
|
812
|
+
return 0
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
# `def reset`, `func _ready`, `class Gabarit`: the name, without the language's keyword.
|
|
816
|
+
HEAD_WORDS = re.compile(r"^(?:async\s+def|def|static\s+func|func|class|function|const|var)\s+")
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def search_nodes(graph: nx.DiGraph, pattern: str) -> list[tuple[str, str]]:
|
|
820
|
+
"""(node, where): by the name first; then, if a displayed text or a
|
|
821
|
+
comment contains it, with what found it."""
|
|
822
|
+
pattern = HEAD_WORDS.sub("", pattern.strip()).lower()
|
|
823
|
+
by_name = sorted(n for n, d in graph.nodes(data=True)
|
|
824
|
+
if pattern in n.lower() or pattern in d["label"].lower() or pattern in d["name"].lower())
|
|
825
|
+
seen = set(by_name)
|
|
826
|
+
others = []
|
|
827
|
+
for n, d in sorted(graph.nodes(data=True)):
|
|
828
|
+
if n in seen:
|
|
829
|
+
continue
|
|
830
|
+
text = next((t for t in d.get("texts", []) if pattern in t.lower()), None)
|
|
831
|
+
if text is not None:
|
|
832
|
+
others.append((n, f"displays \"{text[:60]}\""))
|
|
833
|
+
elif pattern in d.get("notes", "").lower():
|
|
834
|
+
others.append((n, "comment"))
|
|
835
|
+
return [(n, "") for n in by_name] + others
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def search(graph: nx.DiGraph, pattern: str) -> int:
|
|
839
|
+
found = search_nodes(graph, pattern)
|
|
840
|
+
shown = dict(found[:60])
|
|
841
|
+
by_name = [n for n, where in shown.items() if not where] # first, as search_nodes ranks them
|
|
842
|
+
for line in _by_file(graph, by_name) + _by_file(graph, shown.keys() - set(by_name),
|
|
843
|
+
{n: f" ({where})" for n, where in shown.items()}):
|
|
844
|
+
print(f" {line}")
|
|
845
|
+
print(f"{len(found)} node(s)" + (" (60 shown)" if len(found) > 60 else ""))
|
|
846
|
+
return 0 if found else 1
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def check() -> int:
|
|
850
|
+
"""The coverage of each contribution, read in its sites: the classification of the calls, the most frequent
|
|
851
|
+
names of each verdict, then the alerts; a failure if there is an alert or a dangling link."""
|
|
852
|
+
_, _, dangling, sites = assemble(checking=True)
|
|
853
|
+
alerts = 0
|
|
854
|
+
for who, site_list in sites.items():
|
|
855
|
+
verdicts = Counter(s["verdict"] for s in site_list if "verdict" in s)
|
|
856
|
+
print(f"== {who}: {sum(verdicts.values())} sites classified {dict(verdicts.most_common())}")
|
|
857
|
+
for verdict, n in verdicts.most_common():
|
|
858
|
+
names = Counter(s["text"] for s in site_list if s.get("verdict") == verdict)
|
|
859
|
+
print(f" {verdict} ({n}): {dict(names.most_common(12))}")
|
|
860
|
+
to_report = [s for s in site_list if "alert" in s]
|
|
861
|
+
alerts += len(to_report)
|
|
862
|
+
print(f" alerts: {len(to_report)}")
|
|
863
|
+
for s in to_report[:60]:
|
|
864
|
+
print(f" {s['file']}:{s['line']} {s['text']} ({s['alert']})")
|
|
865
|
+
print()
|
|
866
|
+
print(f"== Graph: {len(dangling)} dangling link(s)")
|
|
867
|
+
for e in dangling[:20]:
|
|
868
|
+
print(" ", e["source"], "->", e["target"], e["relation"], e["source_file"], e["source_location"])
|
|
869
|
+
return 1 if alerts or dangling else 0
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
# ---------- the git hooks
|
|
873
|
+
|
|
874
|
+
def _hooks_folder() -> Path:
|
|
875
|
+
r = subprocess.run(["git", "rev-parse", "--git-path", "hooks"], cwd=ROOT, capture_output=True, text=True,
|
|
876
|
+
check=True)
|
|
877
|
+
folder = Path(r.stdout.strip())
|
|
878
|
+
return folder if folder.is_absolute() else ROOT / folder
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
def _without_block(text: str) -> str:
|
|
882
|
+
"""The hook as it was before `install`, to the byte: the block is an exact addition."""
|
|
883
|
+
for opening, closing in BLOCKS:
|
|
884
|
+
start = text.find("\n" + opening)
|
|
885
|
+
end = text.find(closing, start)
|
|
886
|
+
if start >= 0 and end >= 0:
|
|
887
|
+
# Up to the end of the line that closes the block, LF or CRLF (an editor may have converted the hook): a
|
|
888
|
+
# recognised block is never doubled.
|
|
889
|
+
text = text[:start] + text[end:].partition("\n")[2]
|
|
890
|
+
return text
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def _ignore_output() -> None:
|
|
894
|
+
"""Adds the output to the host's .gitignore, unless git already ignores it (in whatever form)."""
|
|
895
|
+
if subprocess.run(["git", "check-ignore", "-q", f"{OUTPUT.name}/"], cwd=ROOT).returncode == 0:
|
|
896
|
+
return
|
|
897
|
+
file = ROOT / ".gitignore"
|
|
898
|
+
text = file.read_bytes() if file.exists() else b"" # in bytes: a .gitignore outside UTF-8 stays intact
|
|
899
|
+
file.write_bytes(text + (b"\n" if text and not text.endswith(b"\n") else b"") + f"/{OUTPUT.name}/\n".encode())
|
|
900
|
+
print(f" .gitignore: /{OUTPUT.name}/ added")
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
def install(remove: bool = False) -> int:
|
|
904
|
+
"""Sets (or removes) the block that rebuilds the graph in each hook; a
|
|
905
|
+
hook already there keeps what it did."""
|
|
906
|
+
folder = _hooks_folder()
|
|
907
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
908
|
+
# shortcut: `graphe` must be in the PATH of git's shell, else the hook fails silently (the next query rebuilds
|
|
909
|
+
# anyway); an absolute path if a git client does not inherit the PATH.
|
|
910
|
+
block = f"\n{BLOCKS[0][0]} (graphe install)\ngraphe build --quiet >/dev/null 2>&1 &\n{BLOCKS[0][1]}\n"
|
|
911
|
+
for name in HOOKS:
|
|
912
|
+
hook = folder / name
|
|
913
|
+
text = _without_block(hook.read_bytes().decode("utf-8") if hook.exists() else "#!/bin/sh\n")
|
|
914
|
+
if not remove:
|
|
915
|
+
text += block
|
|
916
|
+
# shortcut: a host hook reduced to `#!/bin/sh` is deleted like those install created; to tell apart if a
|
|
917
|
+
# host keeps one.
|
|
918
|
+
if remove and text.strip() in ("", "#!/bin/sh"):
|
|
919
|
+
hook.unlink(missing_ok=True)
|
|
920
|
+
print(f" {name}: removed")
|
|
921
|
+
continue
|
|
922
|
+
hook.write_bytes(text.encode("utf-8"))
|
|
923
|
+
hook.chmod(0o755)
|
|
924
|
+
print(f" {name}: {'block removed' if remove else 'set'} ({hook})")
|
|
925
|
+
if not remove:
|
|
926
|
+
_ignore_output()
|
|
927
|
+
return 0
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def _option(arguments: list[str], name: str, default: int) -> int:
|
|
931
|
+
return int(arguments[arguments.index(name) + 1]) if name in arguments else default
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
FLAGS = {"--quiet", "--undirected", "--all", "--source", "--depth", "--remove"}
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def main(arguments: list[str] | None = None) -> int:
|
|
938
|
+
"""The `graphe` command. An expected error (a RuntimeError: not a git repository, an extension not found, an
|
|
939
|
+
incomplete node) prints one line, `graphe: <message>`; a real bug keeps its traceback (T-0065)."""
|
|
940
|
+
try:
|
|
941
|
+
return _command(sys.argv[1:] if arguments is None else arguments)
|
|
942
|
+
except RuntimeError as e:
|
|
943
|
+
print(f"graphe: {e}", file=sys.stderr)
|
|
944
|
+
return 1
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _command(arguments: list[str]) -> int:
|
|
948
|
+
# Read by another program (an agent, a pipe), cp1252 printed « D?fi ».
|
|
949
|
+
if not sys.stdout.isatty():
|
|
950
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
951
|
+
command, rest = (arguments[0], arguments[1:]) if arguments else ("", [])
|
|
952
|
+
if command in ("-h", "--help"):
|
|
953
|
+
print(__doc__)
|
|
954
|
+
return 0
|
|
955
|
+
# An unknown flag ran the command: `install --help` installed the hooks.
|
|
956
|
+
unknown = [a for a in rest if a == "-h" or (a.startswith("--") and a not in FLAGS)]
|
|
957
|
+
if unknown:
|
|
958
|
+
print(__doc__)
|
|
959
|
+
return 0 if set(unknown) <= {"-h", "--help"} else 2
|
|
960
|
+
positionals = [a for i, a in enumerate(rest) if not a.startswith("--")
|
|
961
|
+
and not (i and rest[i - 1] == "--depth")]
|
|
962
|
+
if command == "build":
|
|
963
|
+
try:
|
|
964
|
+
return build(quiet="--quiet" in rest)
|
|
965
|
+
except Exception:
|
|
966
|
+
if "--quiet" not in rest:
|
|
967
|
+
raise
|
|
968
|
+
import traceback # noqa: PLC0415 - the error path only
|
|
969
|
+
OUTPUT.mkdir(exist_ok=True)
|
|
970
|
+
(OUTPUT / "error.txt").write_bytes(traceback.format_exc().encode("utf-8"))
|
|
971
|
+
return 1
|
|
972
|
+
if command == "check":
|
|
973
|
+
return check()
|
|
974
|
+
if command == "install":
|
|
975
|
+
return install(remove="--remove" in rest)
|
|
976
|
+
if command == "path" and len(positionals) == 2:
|
|
977
|
+
return path(load(), *positionals, undirected="--undirected" in rest)
|
|
978
|
+
if command == "explain" and len(positionals) == 1:
|
|
979
|
+
return explain(load(), positionals[0], all_="--all" in rest, code="--source" in rest)
|
|
980
|
+
if command == "callers" and len(positionals) == 1:
|
|
981
|
+
return callers(load(), positionals[0], _option(rest, "--depth", 2))
|
|
982
|
+
if command == "search" and len(positionals) == 1:
|
|
983
|
+
return search(load(), positionals[0])
|
|
984
|
+
if command == "view" and len(positionals) <= 1:
|
|
985
|
+
return view(load(), positionals[0] if positionals else None)
|
|
986
|
+
print(__doc__)
|
|
987
|
+
return 2
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
if __name__ == "__main__":
|
|
991
|
+
sys.exit(main(sys.argv[1:]))
|