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/viz.py ADDED
@@ -0,0 +1,381 @@
1
+ """graph.html: an offline, self-contained view of graph.json.
2
+
3
+ graphlore writes it next to graph.json after every build (``no_viz=True`` skips
4
+ it), whichever engine built the graph, and again when community names change.
5
+ The page is one file: the drawing code is graphlore's own (``viewer.html``,
6
+ canvas and plain JavaScript), the graph is embedded as JSON, and a Content
7
+ Security Policy forbids every request, so opening it reaches no network.
8
+ ``viewer.html`` with no graph in it is a viewer of its own: it opens any
9
+ graph.json the reader picks or drops (read in the browser), through its
10
+ ``compact()``, the JavaScript twin of :func:`page_data` — the two give the
11
+ same answer (``test_the_viewer_reads_a_raw_graph_as_python_does``).
12
+
13
+ A large codebase does not fit on one screen, so the page starts from the
14
+ communities (one bubble each, the edges between them counted) and opens one
15
+ community, or one node's neighbourhood, at a time. Labels, paths and names come
16
+ from the repository: the page puts them on the canvas and in the DOM as text
17
+ only (``textContent``, ``fillText``), never as markup, and the JSON is embedded
18
+ with ``<``, ``>`` and ``&`` escaped so it cannot close its ``<script>``.
19
+
20
+ What graphlore's tools found (cycles, surprises, shared state, unreferenced
21
+ code, vendored files, the edges graphlore resolves for a graphify graph) is
22
+ not in graph.json: server.py works it out for the active project and hands it
23
+ in as ``analysis``, which the page shows as its findings. A graph.json opened
24
+ in the browser has none, and the page says so. The impact view walks the
25
+ edges as ``graphlore_impact`` does (``impact_walk``), in the page's
26
+ ``impact:begin`` / ``impact:end`` block.
27
+
28
+ Imports only ``graph``.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import html
34
+ import json
35
+ import re
36
+ from collections import Counter
37
+ from pathlib import Path
38
+ from typing import Any
39
+
40
+ from .graph import (
41
+ _CALL_RELATIONS,
42
+ _CONTAINMENT_RELATIONS,
43
+ _COUPLING_RELATIONS,
44
+ _DOCUMENT_RELATIONS,
45
+ _HTTP_RELATIONS,
46
+ _IMPORT_RELATIONS,
47
+ _STATE_RELATIONS,
48
+ _edge_ends,
49
+ _edge_rel,
50
+ _is_external_node,
51
+ _is_file_hub_node,
52
+ _is_resource_node,
53
+ _is_route_node,
54
+ _is_state_node,
55
+ _is_test_path,
56
+ _node_file,
57
+ _node_id,
58
+ _node_label,
59
+ _node_line,
60
+ _node_type,
61
+ _nodes_edges,
62
+ )
63
+
64
+ TEMPLATE = Path(__file__).with_name("viewer.html")
65
+ # How a graph.html says graphlore wrote it (graphify's is patched, not rewritten).
66
+ GENERATOR = '<meta name="generator" content="graphlore">'
67
+ # Past this many nodes the page would be tens of megabytes and slow to open:
68
+ # graph.html is not written, and the build says so.
69
+ MAX_NODES = 150_000
70
+ # The communities the overview draws (largest first); the rest are counted.
71
+ MAX_COMMUNITIES = 300
72
+
73
+ _INHERITANCE = frozenset({"inherits", "implements", "mixes_in", "embeds", "extends"})
74
+ # Edge groups: the page colours and filters edges by these, in this order.
75
+ GROUPS = ("structure", "imports", "calls", "inheritance", "references", "state",
76
+ "http", "documents", "other")
77
+
78
+
79
+ def relation_group(rel: str) -> str:
80
+ """The group a relation is drawn and filtered with."""
81
+ if rel in _CONTAINMENT_RELATIONS:
82
+ return "structure"
83
+ if rel in _IMPORT_RELATIONS:
84
+ return "imports"
85
+ if rel in _CALL_RELATIONS or rel == "dispatches_to":
86
+ return "calls"
87
+ if rel in _INHERITANCE:
88
+ return "inheritance"
89
+ if rel == "references":
90
+ return "references"
91
+ if rel in _STATE_RELATIONS or rel in _COUPLING_RELATIONS:
92
+ return "state"
93
+ if rel in _HTTP_RELATIONS:
94
+ return "http"
95
+ if rel in _DOCUMENT_RELATIONS:
96
+ return "documents"
97
+ return "other"
98
+
99
+
100
+ # How graphlore_impact walks a relation by default (server.py's skip sets):
101
+ # 1 always, 0 never (a docstring describes code, it does not depend on it),
102
+ # 2 only from a state node (its readers and writers are its dependents).
103
+ _IMPACT_NEVER = frozenset({"rationale_for"})
104
+ _IMPACT_FROM_STATE = _STATE_RELATIONS | _COUPLING_RELATIONS
105
+
106
+
107
+ def impact_walk(rel: str) -> int:
108
+ """Whether the page's impact view walks ``rel``: 1, 0 or 2 (see above)."""
109
+ r = rel.strip().lower()
110
+ if r in _IMPACT_NEVER:
111
+ return 0
112
+ return 2 if r in _IMPACT_FROM_STATE else 1
113
+
114
+
115
+ # Where a node's source can be opened on the web: the hosts whose file pages
116
+ # take a commit and a line range in the URL (the page builds it, `sourceUrl`).
117
+ _SOURCE_HOSTS = {"github.com": "github", "gitlab.com": "gitlab", "bitbucket.org": "bitbucket"}
118
+ _REPO_PART = re.compile(r"[A-Za-z0-9_.-]+")
119
+ _SCP_REMOTE = re.compile(r"^[A-Za-z0-9_.-]+@([A-Za-z0-9.-]+):(.+)$")
120
+
121
+
122
+ def source_of_remote(url: str, commit: str, prefix: str = "") -> dict[str, str] | None:
123
+ """What graph.html needs to open a node's lines on its host, from a git
124
+ remote's URL: ``{"host", "web", "commit", "prefix"}``, or None for a host it
125
+ has no link form for, a malformed URL or commit. Only the host and the
126
+ repository's path are kept: a user name, a token or a port in the remote
127
+ never reaches the page."""
128
+ from urllib.parse import urlsplit
129
+
130
+ url, commit = url.strip(), commit.strip()
131
+ if not re.fullmatch(r"[0-9a-f]{7,40}", commit):
132
+ return None
133
+ scp = _SCP_REMOTE.match(url)
134
+ if scp:
135
+ host, path = scp.group(1), scp.group(2)
136
+ else:
137
+ try:
138
+ parts = urlsplit(url)
139
+ host = parts.hostname or ""
140
+ except ValueError:
141
+ return None
142
+ if parts.scheme not in ("https", "http", "ssh", "git"):
143
+ return None
144
+ path = parts.path
145
+ kind = _SOURCE_HOSTS.get(host.lower())
146
+ path = path.strip("/").removesuffix(".git")
147
+ segments = path.split("/")
148
+ if kind is None or len(segments) < 2 or not all(_REPO_PART.fullmatch(s) for s in segments):
149
+ return None
150
+ prefix = prefix.strip("/")
151
+ if prefix and not all(p and p not in (".", "..") for p in prefix.split("/")):
152
+ return None
153
+ return {"host": kind, "web": f"https://{host.lower()}/{path}", "commit": commit,
154
+ "prefix": prefix + "/" if prefix else ""}
155
+
156
+
157
+ def _int(v: Any) -> int:
158
+ """An integer the graph wrote, as JSON gives it; 0 when it is none."""
159
+ if isinstance(v, bool):
160
+ return 0
161
+ if isinstance(v, int):
162
+ return v
163
+ if isinstance(v, float) and v.is_integer():
164
+ return int(v)
165
+ if isinstance(v, str) and v.isdigit():
166
+ return int(v)
167
+ return 0
168
+
169
+
170
+ def _loc_line(e: dict) -> int:
171
+ """The leading line of an edge's ``source_location`` (``L13``, ``L13-L15``)."""
172
+ loc = e.get("source_location")
173
+ m = re.match(r"\d+", str(loc if loc not in (None, "") else "").lstrip("Ll"))
174
+ return int(m.group(0)) if m else 0
175
+
176
+
177
+ def _text(v: Any) -> str:
178
+ """A string field, or "" when it is absent or not a string."""
179
+ return v if isinstance(v, str) else ""
180
+
181
+
182
+ def _external(n: dict) -> bool:
183
+ """Code outside the repository. A resource (an environment variable, a
184
+ table) has an empty file too, and is the project's own."""
185
+ return _is_external_node(n) and not _is_resource_node(n)
186
+
187
+
188
+ def _qualname(n: dict) -> str:
189
+ """The node's qualified name when it says more than its label: "" for a
190
+ top-level ``run()`` whose qualname is ``run``."""
191
+ qual = _text(n.get("qualname"))
192
+ label = _node_label(n)
193
+ bare = (label[:-2] if label.endswith("()") else label).lstrip(".")
194
+ return "" if qual == bare else qual
195
+
196
+
197
+ def _kind(n: dict) -> str:
198
+ if _external(n):
199
+ return "external"
200
+ if _is_file_hub_node(n):
201
+ return "file"
202
+ kind = n.get("kind")
203
+ if isinstance(kind, str) and kind:
204
+ return kind
205
+ return _node_type(n) or "node"
206
+
207
+
208
+ def _is_document(n: dict) -> bool:
209
+ """A document's file or heading node: what graph.json calls a document."""
210
+ return str(n.get("file_type") or "").lower() == "document"
211
+
212
+
213
+ def _is_test(n: dict) -> bool:
214
+ """Test code as the graph says it, without reading any file: the native
215
+ engine's ``test`` mark, or a test path."""
216
+ return n.get("test") is True or _is_test_path(_node_file(n))
217
+
218
+
219
+ def page_data(
220
+ graph: dict, names: dict[str, str] | None = None,
221
+ analysis: dict[str, Any] | None = None,
222
+ source: dict[str, str] | None = None,
223
+ ) -> dict[str, Any]:
224
+ """The compact form of ``graph`` the page reads: nodes and edges as arrays of
225
+ indices into the relation, kind and community tables.
226
+
227
+ Everything but ``analysis`` comes from graph.json alone, so the page's own
228
+ ``compact()`` makes the same from a raw graph. ``analysis`` is what
229
+ graphlore's tools found (server.py's ``_viz_analysis``), put in unchanged, and
230
+ so is ``source`` (``source_of_remote``: where a node's lines open on the web)."""
231
+ nodes, edges = _nodes_edges(graph)
232
+ names = names or {}
233
+ index: dict[str, int] = {}
234
+ for i, n in enumerate(nodes):
235
+ index.setdefault(_node_id(n), i)
236
+
237
+ degree: Counter[int] = Counter()
238
+ flat_edges: list[int] = []
239
+ eattrs: list[int] = []
240
+ rels: dict[str, int] = {}
241
+ ctxs: dict[str, int] = {}
242
+ runs: dict[str, int] = {}
243
+ for e in edges:
244
+ s, t = _edge_ends(e)
245
+ si, ti = index.get(s), index.get(t)
246
+ if si is None or ti is None:
247
+ continue # a dangling edge: graphlore_validate reports it
248
+ rel = _edge_rel(e) or "related"
249
+ r = rels.setdefault(rel, len(rels))
250
+ inferred = str(e.get("confidence", "")).upper() == "INFERRED"
251
+ flat_edges += [si, ti, r, 1 if inferred else 0]
252
+ context, run = _text(e.get("context")), _text(e.get("runs"))
253
+ eattrs += [_loc_line(e), ctxs.setdefault(context, len(ctxs)) if context else -1,
254
+ runs.setdefault(run, len(runs)) if run else -1]
255
+ degree[si] += 1
256
+ degree[ti] += 1
257
+
258
+ comm_ids: dict[str, int] = {}
259
+ comm_size: Counter[int] = Counter()
260
+ comm_name: dict[int, str] = {}
261
+ kinds: dict[str, int] = {}
262
+ langs: dict[str, int] = {}
263
+ rows: list[list[Any]] = []
264
+ routes: list[list[Any]] = []
265
+ coupling: list[list[Any]] = []
266
+ for i, n in enumerate(nodes):
267
+ raw = n.get("community", n.get("cluster"))
268
+ c = -1
269
+ if raw is not None and raw != "":
270
+ key = str(raw)
271
+ c = comm_ids.setdefault(key, len(comm_ids))
272
+ comm_size[c] += 1
273
+ if c not in comm_name:
274
+ given = names.get(key) or n.get("community_name")
275
+ comm_name[c] = str(given) if given else f"Community {key}"
276
+ k = kinds.setdefault(_kind(n), len(kinds))
277
+ flags = ((1 if _is_test(n) else 0) | (2 if _external(n) else 0)
278
+ | (4 if _is_state_node(n) else 0) | (8 if _is_document(n) else 0))
279
+ line = str(_node_line(n))
280
+ lang = _text(n.get("language"))
281
+ rows.append([_node_id(n), _node_label(n), _node_file(n),
282
+ int(line) if line.isdigit() else 0, c, k, flags, degree[i],
283
+ _int(n.get("end_line")), _qualname(n),
284
+ langs.setdefault(lang, len(langs)) if lang else -1])
285
+ if _is_route_node(n):
286
+ routes.append([i, str(n.get("method") or ""), str(n.get("pattern") or ""),
287
+ str(n.get("framework") or "")])
288
+ cp = n.get("coupling")
289
+ if isinstance(cp, dict):
290
+ listed = []
291
+ for pair in cp.get("listed") or []:
292
+ if not isinstance(pair, list) or len(pair) < 2:
293
+ continue
294
+ hops = pair[2] if len(pair) > 2 else None
295
+ cc = pair[3] if len(pair) > 3 else None
296
+ listed.append([index.get(str(pair[0]), -1), index.get(str(pair[1]), -1),
297
+ hops if isinstance(hops, int) and not isinstance(hops, bool)
298
+ else None,
299
+ cc if isinstance(cc, bool) else None])
300
+ coupling.append([i, _int(cp.get("pairs")), _int(cp.get("hidden")), listed])
301
+
302
+ # edges between communities, counted: the overview's links
303
+ between: Counter[tuple[int, int]] = Counter()
304
+ for j in range(0, len(flat_edges), 4):
305
+ a, b = rows[flat_edges[j]][4], rows[flat_edges[j + 1]][4]
306
+ if a >= 0 and b >= 0 and a != b:
307
+ between[(a, b) if a < b else (b, a)] += 1
308
+ comms = [[cid, comm_name.get(c, f"Community {cid}"), comm_size[c]]
309
+ for cid, c in comm_ids.items()]
310
+ header = graph.get("graph")
311
+ meta: dict[str, Any] = header if isinstance(header, dict) else {}
312
+ data: dict[str, Any] = {
313
+ "meta": {
314
+ "engine": "graphlore" if meta.get("engine") == "graphlore" else "graphify",
315
+ "commit": str(graph.get("built_at_commit") or meta.get("built_at_commit") or "")[:12],
316
+ "nodes": len(nodes), "edges": len(flat_edges) // 4,
317
+ },
318
+ "groups": list(GROUPS),
319
+ "rels": [[rel, GROUPS.index(relation_group(rel)), impact_walk(rel)] for rel in rels],
320
+ "kinds": list(kinds),
321
+ "langs": list(langs),
322
+ "ctxs": list(ctxs),
323
+ "runs": list(runs),
324
+ "comms": comms,
325
+ "maxComms": MAX_COMMUNITIES,
326
+ "nodes": rows,
327
+ "edges": flat_edges,
328
+ "cedges": [x for (a, b), w in sorted(between.items()) for x in (a, b, w)],
329
+ "eattrs": eattrs,
330
+ "routes": routes,
331
+ "coupling": coupling,
332
+ }
333
+ if analysis is not None:
334
+ data["analysis"] = analysis
335
+ if source is not None:
336
+ data["source"] = source
337
+ return data
338
+
339
+
340
+ def _embed(data: dict[str, Any]) -> str:
341
+ """JSON that can sit inside a ``<script>``: no ``<``, ``>`` or ``&`` left raw."""
342
+ text = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
343
+ return text.replace("&", "\\u0026").replace("<", "\\u003c").replace(">", "\\u003e")
344
+
345
+
346
+ def render(
347
+ graph: dict, title: str, names: dict[str, str] | None = None,
348
+ analysis: dict[str, Any] | None = None, source: dict[str, str] | None = None,
349
+ ) -> str:
350
+ """graph.html for ``graph``, with what graphlore's tools found in ``analysis``
351
+ and where its nodes' lines open on the web in ``source``."""
352
+ page = TEMPLATE.read_text(encoding="utf-8")
353
+ return (page.replace("__GRAPHLORE_TITLE__", html.escape(title))
354
+ .replace("/*__GRAPHLORE_DATA__*/",
355
+ _embed(page_data(graph, names, analysis, source))))
356
+
357
+
358
+ def is_ours(path: Path) -> bool:
359
+ """Whether the graph.html at ``path`` is one graphlore wrote."""
360
+ try:
361
+ with path.open(encoding="utf-8", errors="replace") as fh:
362
+ return GENERATOR in fh.read(2048)
363
+ except OSError:
364
+ return False
365
+
366
+
367
+ def write(
368
+ graph: dict, out: Path, title: str, names: dict[str, str] | None = None,
369
+ analysis: dict[str, Any] | None = None, source: dict[str, str] | None = None,
370
+ ) -> str:
371
+ """Write graph.html for ``graph`` to ``out``; a one-line note saying what was
372
+ done, for the build's reply."""
373
+ nodes, _ = _nodes_edges(graph)
374
+ if len(nodes) > MAX_NODES:
375
+ return (f"graph.html not written: {len(nodes):,} nodes is more than the page "
376
+ f"draws ({MAX_NODES:,}).")
377
+ try:
378
+ out.write_text(render(graph, title, names, analysis, source), encoding="utf-8")
379
+ except OSError as e:
380
+ return f"graph.html not written: {e}"
381
+ return f"graph.html written: {out} (open it in a browser; it reaches no network)"