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/core.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
"""The core: what the graph draws from the text of the sources, once the
|
|
2
|
+
readers have run (BACKLOG.md).
|
|
3
|
+
|
|
4
|
+
For each function, method, command or action:
|
|
5
|
+
- `end`: its last line - the first non-blank line that comes back to its
|
|
6
|
+
indentation closes its body (Python, GDScript and PHP are read alike);
|
|
7
|
+
`explain X --source` prints its lines;
|
|
8
|
+
- `texts`: the texts it displays, by the `displayed_text` pattern of
|
|
9
|
+
graphe.toml (T-0009) - a text seen on screen leads to its code; without a
|
|
10
|
+
pattern, none;
|
|
11
|
+
- `notes`: the comment just above it - a concept said in a comment
|
|
12
|
+
(« clarte ») leads to the function that has it.
|
|
13
|
+
|
|
14
|
+
And:
|
|
15
|
+
- a node per module variable or constant (Python: an assignment in column
|
|
16
|
+
0; GDScript: `const`/`var` in column 0, except `preload`), linked to the
|
|
17
|
+
functions that read it (`reads`) or write it (`writes`) - in its file by
|
|
18
|
+
the name, elsewhere by `X.NAME` when that name exists only once;
|
|
19
|
+
- a class and its fields have their end and their comment;
|
|
20
|
+
- Python: `alias.CONSTANT`, where `alias` is a module imported under that
|
|
21
|
+
name, reads that module's constant (EXTRACTED);
|
|
22
|
+
- a node per document (T-0010): each Markdown file of the host, restricted
|
|
23
|
+
by `[documents] patterns` (graphe.toml). A document whose name starts with
|
|
24
|
+
an identifier (`[documents] identifier`, `T-` and four digits by default)
|
|
25
|
+
is a ticket: the code that contains its identifier (in its body or its
|
|
26
|
+
comment) and the other documents lead to it by `cites`. A document leads
|
|
27
|
+
to the functions it names between backticks (`names`, by the name);
|
|
28
|
+
- a `value` node per string (an identifier, `"coupee"`) written both in
|
|
29
|
+
Python and in GDScript, linked to each body that writes it (`value`): what
|
|
30
|
+
one side emits and what the other compares;
|
|
31
|
+
- a keyed link (T-0047, `[keys]` of graphe.toml): `sends` from the body
|
|
32
|
+
that names a key (`api("zones")`) to the code that answers it
|
|
33
|
+
(`$chemin === '/api/zones'`), where no name joins them.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import re
|
|
39
|
+
from collections import defaultdict
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
|
|
42
|
+
import networkx as nx
|
|
43
|
+
|
|
44
|
+
from graphe import godot
|
|
45
|
+
from graphe import root as graphe_root # `root` is the host's path in this module's signatures
|
|
46
|
+
|
|
47
|
+
BODIES = {"function", "method", "command", "action", "class"}
|
|
48
|
+
# An extent and a comment, without being a body that owns its lines.
|
|
49
|
+
EXTENDED = BODIES | {"field"}
|
|
50
|
+
PY_ALIAS = re.compile(r"^\s*(?:from\s+([\w.]+)\s+import\s+(\w+)(?:\s+as\s+(\w+))?|import\s+([\w.]+)\s+as\s+(\w+))\s*$")
|
|
51
|
+
PY_QUALIFIED = re.compile(r"\b([a-z_]\w*)\.(\w+)\b")
|
|
52
|
+
# T-0010: a document's default identifier (`[documents] identifier`), that of tickets.
|
|
53
|
+
IDENTIFIER = r"\bT-\d{4}\b"
|
|
54
|
+
NAMED = re.compile(r"`([A-Za-z_][\w.]*?)(?:\([^`]*\))?`") # `f`, `f()`, and `f(a, b)` (T-0024)
|
|
55
|
+
PY_VARIABLE = re.compile(r"^([A-Za-z_]\w*)\s*(?::[^=]+)?=(?!=)")
|
|
56
|
+
GD_VARIABLE = re.compile(r"^(?:static\s+)?(const|var)\s+(\w+)\b(.*)$")
|
|
57
|
+
PRELOAD = re.compile(r'^const\s+(\w+)\s*=\s*preload\("res://([^"]+\.gd)"\)', re.M)
|
|
58
|
+
QUALIFIED = re.compile(r"\b([A-Z]\w*)\.(\w+)\b")
|
|
59
|
+
# Names too common to be followed from one file to another by the name.
|
|
60
|
+
NAME_MIN = 4
|
|
61
|
+
VALUE = re.compile(r'"([a-z][a-z0-9_]{3,})"')
|
|
62
|
+
VALUE_FILES_MAX = 8
|
|
63
|
+
VALUE_BODIES_MAX = 10
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _indent(line: str) -> int:
|
|
67
|
+
return len(line.expandtabs(4)) - len(line.expandtabs(4).lstrip())
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _comment(line: str) -> str | None:
|
|
71
|
+
s = line.strip()
|
|
72
|
+
for start in ("#", "//", "/**", "/*", "*"):
|
|
73
|
+
if s.startswith(start):
|
|
74
|
+
return s[len(start):].strip().removesuffix("*/").strip()
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def extent(lines: list[str], start: int) -> int:
|
|
79
|
+
"""The last line (1 = the first of the file) of the block that starts at
|
|
80
|
+
`start`: before the first non-blank line, outside a comment, that comes
|
|
81
|
+
back to the indentation of `start` or less. A closing `}` or `)` at that
|
|
82
|
+
indentation belongs to the block, and a `{` alone on its line right after
|
|
83
|
+
the signature."""
|
|
84
|
+
if start < 1 or start > len(lines):
|
|
85
|
+
return start
|
|
86
|
+
base = _indent(lines[start - 1])
|
|
87
|
+
end = start
|
|
88
|
+
open_ = lines[start - 1].count("(") - lines[start - 1].count(")")
|
|
89
|
+
body = False # a line of the body seen
|
|
90
|
+
for i in range(start, len(lines)):
|
|
91
|
+
line = lines[i]
|
|
92
|
+
if open_ > 0: # a signature over several lines
|
|
93
|
+
open_ += line.count("(") - line.count(")")
|
|
94
|
+
end = i + 1
|
|
95
|
+
continue
|
|
96
|
+
s = line.strip()
|
|
97
|
+
if not s or _comment(line) is not None and _indent(line) > base:
|
|
98
|
+
continue
|
|
99
|
+
if _indent(line) <= base:
|
|
100
|
+
if s == "{" and _indent(line) == base and not body: # the brace on its own line (PHP's PSR-12)
|
|
101
|
+
end = i + 1
|
|
102
|
+
continue
|
|
103
|
+
if s[0] in "})]" and _indent(line) == base:
|
|
104
|
+
end = i + 1
|
|
105
|
+
break
|
|
106
|
+
end, body = i + 1, True
|
|
107
|
+
return end
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def notes(lines: list[str], start: int) -> str:
|
|
111
|
+
"""The comment just above line `start` (decorators skipped), on one
|
|
112
|
+
line."""
|
|
113
|
+
i = start - 2
|
|
114
|
+
while i >= 0 and lines[i].strip().startswith("@"):
|
|
115
|
+
i -= 1
|
|
116
|
+
pieces = []
|
|
117
|
+
while i >= 0:
|
|
118
|
+
text = _comment(lines[i])
|
|
119
|
+
if text is None:
|
|
120
|
+
break
|
|
121
|
+
pieces.append(text)
|
|
122
|
+
i -= 1
|
|
123
|
+
return " ".join(reversed([p for p in pieces if p]))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _variables(rel: str, lines: list[str]) -> list[tuple[str, int, str]]:
|
|
127
|
+
"""(name, line, kind) of the module variables and constants."""
|
|
128
|
+
found = []
|
|
129
|
+
if rel.endswith(".py"):
|
|
130
|
+
for i, line in enumerate(lines, start=1):
|
|
131
|
+
m = PY_VARIABLE.match(line)
|
|
132
|
+
if m and m.group(1) not in ("__all__",):
|
|
133
|
+
name = m.group(1)
|
|
134
|
+
found.append((name, i, "constant" if name.lstrip("_").isupper() else "variable"))
|
|
135
|
+
elif rel.endswith(".gd"):
|
|
136
|
+
for i, line in enumerate(lines, start=1):
|
|
137
|
+
m = GD_VARIABLE.match(line)
|
|
138
|
+
if m and "preload(" not in m.group(3) and "load(" not in m.group(3):
|
|
139
|
+
found.append((m.group(2), i, "constant" if m.group(1) == "const" else "variable"))
|
|
140
|
+
seen = set()
|
|
141
|
+
return [t for t in found if not (t[0] in seen or seen.add(t[0]))]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _add_link(graph: nx.DiGraph, s: str, t: str, relation: str, location: str, confidence: str) -> None:
|
|
145
|
+
if graph.has_edge(s, t):
|
|
146
|
+
d = graph[s][t]
|
|
147
|
+
d["relations"].add(relation)
|
|
148
|
+
if location not in d["locations"]:
|
|
149
|
+
d["locations"].append(location)
|
|
150
|
+
else:
|
|
151
|
+
graph.add_edge(s, t, relations={relation}, confidence=confidence, locations=[location], contexts=[])
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _pattern(raw, where: str, group: str | None) -> re.Pattern | None:
|
|
155
|
+
"""A pattern of graphe.toml; `group` names what its only group holds (None: no group required)."""
|
|
156
|
+
if raw is None:
|
|
157
|
+
return None
|
|
158
|
+
try:
|
|
159
|
+
pattern = re.compile(raw)
|
|
160
|
+
except (re.error, TypeError) as e:
|
|
161
|
+
raise RuntimeError(f"{where} ({graphe_root.CONFIGURATION}): {e}") from None
|
|
162
|
+
if group and pattern.groups != 1:
|
|
163
|
+
raise RuntimeError(f"{where} ({graphe_root.CONFIGURATION}): it needs exactly one group, the "
|
|
164
|
+
f"{group}; it has {pattern.groups}")
|
|
165
|
+
return pattern
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def displayed_text_pattern(root: Path) -> re.Pattern | None:
|
|
169
|
+
"""`displayed_text` (graphe.toml): the pattern of a call that displays a text, the text in its only group."""
|
|
170
|
+
return _pattern(graphe_root.configuration(root).get("displayed_text"), "displayed_text", "displayed text")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _key_patterns(root: Path) -> tuple[re.Pattern, re.Pattern, re.Pattern | None] | None:
|
|
174
|
+
"""`[keys]` (graphe.toml, T-0047): where the code names a key, where it answers it, what is a parameter."""
|
|
175
|
+
keys = graphe_root.configuration(root).get("keys")
|
|
176
|
+
if keys is None:
|
|
177
|
+
return None
|
|
178
|
+
for required in ("names", "answers"):
|
|
179
|
+
if required not in keys:
|
|
180
|
+
raise RuntimeError(f"keys ({graphe_root.CONFIGURATION}): it needs `{required}`")
|
|
181
|
+
return (_pattern(keys["names"], "keys.names", "key"), _pattern(keys["answers"], "keys.answers", "key"),
|
|
182
|
+
_pattern(keys.get("parameters"), "keys.parameters", None))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def enrich(graph: nx.DiGraph, root: Path) -> None:
|
|
186
|
+
"""`root` is a git repository: the documents are its Markdown files that git tracks (graphe_root.files)."""
|
|
187
|
+
displays = displayed_text_pattern(root)
|
|
188
|
+
by_file: dict[str, list[str]] = defaultdict(list)
|
|
189
|
+
for n, d in graph.nodes(data=True):
|
|
190
|
+
by_file[d["source_file"]].append(n)
|
|
191
|
+
file_lines: dict[str, list[str]] = {}
|
|
192
|
+
for rel in by_file:
|
|
193
|
+
path = root / rel
|
|
194
|
+
if path.is_file():
|
|
195
|
+
file_lines[rel] = path.read_bytes().decode("utf-8", "replace").splitlines()
|
|
196
|
+
|
|
197
|
+
# The bodies: end, texts, notes.
|
|
198
|
+
bodies: dict[str, tuple[str, int, int]] = {}
|
|
199
|
+
for rel, ids in by_file.items():
|
|
200
|
+
lines = file_lines.get(rel)
|
|
201
|
+
if lines is None:
|
|
202
|
+
continue
|
|
203
|
+
for n in ids:
|
|
204
|
+
d = graph.nodes[n]
|
|
205
|
+
if d["kind"] not in EXTENDED:
|
|
206
|
+
continue
|
|
207
|
+
start = int(d["source_location"].lstrip("L") or 0)
|
|
208
|
+
end = extent(lines, start)
|
|
209
|
+
d["end"] = end
|
|
210
|
+
text = "\n".join(lines[start - 1:end])
|
|
211
|
+
found = [t.replace('\\"', '"') for t in displays.findall(text)] if displays else []
|
|
212
|
+
if found:
|
|
213
|
+
d["texts"] = found
|
|
214
|
+
note = notes(lines, start)
|
|
215
|
+
if note:
|
|
216
|
+
d["notes"] = note
|
|
217
|
+
if d["kind"] in BODIES:
|
|
218
|
+
bodies[n] = (rel, start, end)
|
|
219
|
+
|
|
220
|
+
# Each line has its owner: the smallest body that contains it - the
|
|
221
|
+
# branch of a command rather than the function that dispatches (its
|
|
222
|
+
# calls too: an extension's takeovers, T-0008). The head line is not a
|
|
223
|
+
# use.
|
|
224
|
+
owners: dict[str, dict[int, str]] = defaultdict(dict)
|
|
225
|
+
for n, (rel, start, end) in sorted(bodies.items(), key=lambda b: b[1][2] - b[1][1], reverse=True):
|
|
226
|
+
for i in range(start + 1, end + 1):
|
|
227
|
+
owners[rel][i] = n
|
|
228
|
+
|
|
229
|
+
# Module variables and constants.
|
|
230
|
+
file_id = {graph.nodes[n]["source_file"]: n for n in graph.nodes if graph.nodes[n]["kind"] == "file"}
|
|
231
|
+
variables: dict[str, dict[str, str]] = defaultdict(dict) # file -> name -> id
|
|
232
|
+
module_names: dict[str, list[str]] = defaultdict(list)
|
|
233
|
+
for rel, lines in file_lines.items():
|
|
234
|
+
fid = file_id.get(rel)
|
|
235
|
+
if fid is None:
|
|
236
|
+
continue
|
|
237
|
+
for name, line, kind in _variables(rel, lines):
|
|
238
|
+
vid = f"{fid}_{name.lower()}"
|
|
239
|
+
if vid in graph:
|
|
240
|
+
vid += "_" + kind
|
|
241
|
+
graph.add_node(vid, id=vid, label=name, kind=kind, source_file=rel, source_location=f"L{line}",
|
|
242
|
+
name=name, end=extent(lines, line))
|
|
243
|
+
note = notes(lines, line)
|
|
244
|
+
if note:
|
|
245
|
+
graph.nodes[vid]["notes"] = note
|
|
246
|
+
_add_link(graph, fid, vid, "contains", f"{rel}:{line}", "EXTRACTED")
|
|
247
|
+
variables[rel][name] = vid
|
|
248
|
+
module_names[name].append(vid)
|
|
249
|
+
unique = {name: ids[0] for name, ids in module_names.items() if len(ids) == 1 and len(name) >= NAME_MIN}
|
|
250
|
+
elsewhere = re.compile(r"\b\w+\.(" + "|".join(sorted(map(re.escape, unique), key=len, reverse=True)) + r")\b") \
|
|
251
|
+
if unique else None
|
|
252
|
+
write = r"\s*(?:[-+*/]?=(?!=)|\.(?:append|extend|clear|pop|update|insert|remove|add|discard|erase)\()"
|
|
253
|
+
uses: dict[str, list[tuple[str, str, str]]] = defaultdict(list)
|
|
254
|
+
py_files = {rel for rel in file_lines if rel.endswith(".py")}
|
|
255
|
+
for rel, lines in file_lines.items():
|
|
256
|
+
local = variables.get(rel, {})
|
|
257
|
+
# GDScript: `Script.CONSTANT`, where Script preloads a script (res://: godot/, godot.GODOT).
|
|
258
|
+
alias = {name: godot.res(target) for name, target in PRELOAD.findall("\n".join(lines))} \
|
|
259
|
+
if rel.endswith(".gd") else {}
|
|
260
|
+
# Python: `alias.CONSTANT`, alias a module imported under that name.
|
|
261
|
+
py_alias = _python_aliases(lines, py_files) if rel.endswith(".py") else {}
|
|
262
|
+
here = re.compile(r"(?<![\w.])(" + "|".join(sorted(map(re.escape, local), key=len, reverse=True)) + r")\b") \
|
|
263
|
+
if local else None
|
|
264
|
+
for i, n in owners.get(rel, {}).items():
|
|
265
|
+
line = lines[i - 1]
|
|
266
|
+
if _comment(line) is not None:
|
|
267
|
+
continue
|
|
268
|
+
location = f"{rel}:{i}"
|
|
269
|
+
if here is not None:
|
|
270
|
+
for m in here.finditer(line):
|
|
271
|
+
writes = re.match(write, line[m.end():])
|
|
272
|
+
_add_link(graph, n, local[m.group(1)], "writes" if writes else "reads", location, "EXTRACTED")
|
|
273
|
+
if alias and "." in line:
|
|
274
|
+
for head, name in set(QUALIFIED.findall(line)):
|
|
275
|
+
vid = variables.get(alias.get(head, ""), {}).get(name)
|
|
276
|
+
if vid:
|
|
277
|
+
_add_link(graph, n, vid, "reads", location, "EXTRACTED")
|
|
278
|
+
elif elsewhere is not None and "." in line:
|
|
279
|
+
sure = set()
|
|
280
|
+
for head, name in set(PY_QUALIFIED.findall(line)) if py_alias else ():
|
|
281
|
+
vid = variables.get(py_alias.get(head, ""), {}).get(name)
|
|
282
|
+
if vid:
|
|
283
|
+
_add_link(graph, n, vid, "reads", location, "EXTRACTED")
|
|
284
|
+
sure.add(name)
|
|
285
|
+
for name in set(elsewhere.findall(line)) - sure:
|
|
286
|
+
vid = unique[name]
|
|
287
|
+
# `examen.graine` in Python does not read a GDScript variable.
|
|
288
|
+
other = graph.nodes[vid]["source_file"]
|
|
289
|
+
if other != rel and Path(other).suffix == Path(rel).suffix:
|
|
290
|
+
_add_link(graph, n, vid, "reads", location, "INFERRED")
|
|
291
|
+
# T-0354: values written in one language and read in the other.
|
|
292
|
+
if '"' in line and rel.endswith((".py", ".gd")):
|
|
293
|
+
for v in set(VALUE.findall(line)):
|
|
294
|
+
uses[v].append((n, location, Path(rel).suffix))
|
|
295
|
+
|
|
296
|
+
_link_values(graph, uses)
|
|
297
|
+
keys = _key_patterns(root)
|
|
298
|
+
if keys:
|
|
299
|
+
_link_keys(graph, keys, file_lines, bodies, file_id)
|
|
300
|
+
_link_documents(graph, root, bodies, file_lines)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _link_keys(graph: nx.DiGraph, keys: tuple[re.Pattern, re.Pattern, re.Pattern | None],
|
|
304
|
+
file_lines: dict[str, list[str]], bodies: dict[str, tuple[str, int, int]],
|
|
305
|
+
file_id: dict[str, str]) -> None:
|
|
306
|
+
"""T-0047: a keyed link (`sends`), from the body that names a key to the code that answers it: what the
|
|
307
|
+
answering line calls, else its body (not its file). Two keys match when equal, `*` for each parameter."""
|
|
308
|
+
names, answers, parameters = keys
|
|
309
|
+
# The head line too: a one-line arrow (`f = () => api("zones")`) names on it.
|
|
310
|
+
holders: dict[str, dict[int, str]] = defaultdict(dict)
|
|
311
|
+
for n, (rel, start, end) in sorted(bodies.items(), key=lambda b: b[1][2] - b[1][1], reverse=True):
|
|
312
|
+
for i in range(start, end + 1):
|
|
313
|
+
holders[rel][i] = n
|
|
314
|
+
called: dict[str, list[str]] = defaultdict(list)
|
|
315
|
+
for _, t, d in graph.edges(data=True):
|
|
316
|
+
if "calls" in d["relations"]:
|
|
317
|
+
for location in d["locations"]:
|
|
318
|
+
called[location].append(t)
|
|
319
|
+
|
|
320
|
+
def key(raw: str) -> str:
|
|
321
|
+
return parameters.sub("*", raw) if parameters else raw
|
|
322
|
+
|
|
323
|
+
# shortcut: a route's HTTP method is no part of its key (4cast checks it on another line than the path), so
|
|
324
|
+
# GET and POST of a path lead to the same code; to take it in when a host answers them apart.
|
|
325
|
+
# shortcut: a call in the answering condition (`$chemin === '/api/x' && autorise()`) answers in place of the
|
|
326
|
+
# body; to take only the calls after the key when a host's router does that.
|
|
327
|
+
named: list[tuple[str, str, str]] = []
|
|
328
|
+
answerers: dict[str, set[str]] = defaultdict(set)
|
|
329
|
+
for rel, lines in file_lines.items():
|
|
330
|
+
for i, line in enumerate(lines, 1):
|
|
331
|
+
if _comment(line) is not None:
|
|
332
|
+
continue
|
|
333
|
+
body = holders[rel].get(i)
|
|
334
|
+
location = f"{rel}:{i}"
|
|
335
|
+
if namer := body or file_id.get(rel):
|
|
336
|
+
named += [(namer, key(m.group(1)), location) for m in names.finditer(line)]
|
|
337
|
+
# Not a file: its top-level router calls every route, `callers` would go from one route to all.
|
|
338
|
+
if answerer := called.get(location) or ([body] if body else []):
|
|
339
|
+
for m in answers.finditer(line):
|
|
340
|
+
answerers[key(m.group(1))].update(answerer)
|
|
341
|
+
for n, k, location in named:
|
|
342
|
+
for t in sorted(answerers.get(k, ())):
|
|
343
|
+
if t != n:
|
|
344
|
+
_add_link(graph, n, t, "sends", location, "INFERRED")
|
|
345
|
+
if k not in graph[n][t]["contexts"]:
|
|
346
|
+
graph[n][t]["contexts"].append(k)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _link_values(graph: nx.DiGraph, uses: dict[str, list[tuple[str, str, str]]]) -> None:
|
|
350
|
+
"""T-0354: a value written in Python and in GDScript becomes a node; its
|
|
351
|
+
name keeps its quotes, so as not to make ambiguous the name of a
|
|
352
|
+
function spelled the same. A value written in more than
|
|
353
|
+
VALUE_FILES_MAX files (`"name"`, `"tick"`) says nothing and shortened
|
|
354
|
+
one undirected path in three: no node."""
|
|
355
|
+
for v, us in sorted(uses.items()):
|
|
356
|
+
if {s for _, _, s in us} != {".py", ".gd"}:
|
|
357
|
+
continue
|
|
358
|
+
if (len({location.rsplit(":", 1)[0] for _, location, _ in us}) > VALUE_FILES_MAX
|
|
359
|
+
or len({n for n, _, _ in us}) > VALUE_BODIES_MAX):
|
|
360
|
+
continue
|
|
361
|
+
vid = f"value_{v}"
|
|
362
|
+
rel, line = min(location for _, location, s in us if s == ".py").rsplit(":", 1)
|
|
363
|
+
graph.add_node(vid, id=vid, label=f'"{v}"', kind="value", source_file=rel, source_location=f"L{line}",
|
|
364
|
+
name=f'"{v}"', end=int(line))
|
|
365
|
+
for n, location, _ in us:
|
|
366
|
+
_add_link(graph, n, vid, "value", location, "EXTRACTED")
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _python_aliases(lines: list[str], files: set[str]) -> dict[str, str]:
|
|
370
|
+
"""The modules imported under a name: name -> file."""
|
|
371
|
+
alias = {}
|
|
372
|
+
for line in lines:
|
|
373
|
+
m = PY_ALIAS.match(line)
|
|
374
|
+
if not m:
|
|
375
|
+
continue
|
|
376
|
+
if m.group(1):
|
|
377
|
+
module, name = f"{m.group(1)}.{m.group(2)}", m.group(3) or m.group(2)
|
|
378
|
+
else:
|
|
379
|
+
module, name = m.group(4), m.group(5)
|
|
380
|
+
path = module.replace(".", "/")
|
|
381
|
+
for rel in (path + ".py", path + "/__init__.py"):
|
|
382
|
+
if rel in files:
|
|
383
|
+
alias[name] = rel
|
|
384
|
+
return alias
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _documents(root: Path) -> tuple[re.Pattern, list[str] | None]:
|
|
388
|
+
"""`[documents]` (graphe.toml): the pattern of a document's identifier (IDENTIFIER otherwise), and the
|
|
389
|
+
patterns that restrict the documents (None: all Markdown files)."""
|
|
390
|
+
table = graphe_root.configuration(root).get("documents", {})
|
|
391
|
+
if not isinstance(table, dict):
|
|
392
|
+
raise RuntimeError(f"documents ({graphe_root.CONFIGURATION}): [documents] must be a table")
|
|
393
|
+
try:
|
|
394
|
+
pattern = re.compile(table.get("identifier", IDENTIFIER))
|
|
395
|
+
except (re.error, TypeError) as e:
|
|
396
|
+
raise RuntimeError(f"[documents] identifier ({graphe_root.CONFIGURATION}): {e}") from None
|
|
397
|
+
restricted = table.get("patterns")
|
|
398
|
+
if restricted is not None and not (isinstance(restricted, list) and all(isinstance(m, str) for m in restricted)):
|
|
399
|
+
raise RuntimeError(f"[documents] patterns ({graphe_root.CONFIGURATION}): it must be a list of patterns")
|
|
400
|
+
return pattern, restricted
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _document_id(prefix: str, name: str) -> str:
|
|
404
|
+
return prefix + re.sub(r"\W+", "_", name.lower()).strip("_")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _cited(pattern: re.Pattern, text: str) -> set[str]:
|
|
408
|
+
return {m.group(0) for m in pattern.finditer(text) if m.group(0)}
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _link_documents(graph: nx.DiGraph, root: Path, bodies: dict, texts: dict[str, list[str]]) -> None:
|
|
412
|
+
"""T-0010: each Markdown file of the host (`[documents] patterns` restricts them) is a document. One whose
|
|
413
|
+
name starts with an identifier is a ticket; it is cited by the code and by the documents that contain it.
|
|
414
|
+
A document names the functions it writes between backticks."""
|
|
415
|
+
pattern, restricted = _documents(root)
|
|
416
|
+
tickets: dict[str, str] = {} # identifier -> id
|
|
417
|
+
documents = []
|
|
418
|
+
for path in graphe_root.files(".md", root):
|
|
419
|
+
rel = path.relative_to(root).as_posix()
|
|
420
|
+
if restricted is not None and not graphe_root.designates(rel, restricted):
|
|
421
|
+
continue
|
|
422
|
+
text = path.read_bytes().decode("utf-8", "replace")
|
|
423
|
+
title = next((line.split(":", 1)[1].strip() for line in text.splitlines()[:8]
|
|
424
|
+
if line.startswith("title:")), path.stem)
|
|
425
|
+
m = pattern.match(path.name)
|
|
426
|
+
# shortcut: two files with the same identifier, the second is only a document; and two names that differ
|
|
427
|
+
# only by punctuation (`a-b.md`, `a_b.md`) make a single node. To revisit if a host has some.
|
|
428
|
+
if m and m.group(0) and m.group(0) not in tickets:
|
|
429
|
+
name, kind = m.group(0), "ticket"
|
|
430
|
+
tickets[name] = did = _document_id("ticket_", name)
|
|
431
|
+
else:
|
|
432
|
+
name, kind, did = rel, "document", _document_id("document_", rel)
|
|
433
|
+
graph.add_node(did, id=did, label=name, kind=kind, source_file=rel, source_location="L1",
|
|
434
|
+
name=name, notes=title, end=len(text.splitlines()))
|
|
435
|
+
documents.append((did, rel, text))
|
|
436
|
+
# The code that cites a ticket, in its body or its comment.
|
|
437
|
+
for n, (rel, start, end) in bodies.items():
|
|
438
|
+
lines = texts.get(rel, [])
|
|
439
|
+
cited = _cited(pattern, "\n".join(lines[start - 1:end])) | _cited(pattern, graph.nodes[n].get("notes", ""))
|
|
440
|
+
for ident in sorted(cited):
|
|
441
|
+
if ident in tickets:
|
|
442
|
+
_add_link(graph, n, tickets[ident], "cites", f"{rel}:{start}", "EXTRACTED")
|
|
443
|
+
# The tickets a document cites, and the functions it names: a name borne by a single body.
|
|
444
|
+
bearers: dict[str, list[str]] = defaultdict(list)
|
|
445
|
+
for n in bodies:
|
|
446
|
+
d = graph.nodes[n]
|
|
447
|
+
if d["kind"] in ("function", "method", "class"):
|
|
448
|
+
bearers[d["name"].rsplit(".", 1)[-1]].append(n)
|
|
449
|
+
for did, rel, text in documents:
|
|
450
|
+
for i, line in enumerate(text.splitlines(), start=1):
|
|
451
|
+
for ident in sorted(_cited(pattern, line)):
|
|
452
|
+
if ident in tickets and tickets[ident] != did: # not from itself to itself
|
|
453
|
+
_add_link(graph, did, tickets[ident], "cites", f"{rel}:{i}", "EXTRACTED")
|
|
454
|
+
for name in set(NAMED.findall(text)):
|
|
455
|
+
last = name.rsplit(".", 1)[-1]
|
|
456
|
+
if len(last) >= NAME_MIN and len(bearers.get(last, [])) == 1:
|
|
457
|
+
_add_link(graph, did, bearers[last][0], "names", rel, "INFERRED")
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def lines_without_comments(lines: list[str]) -> list[str]:
|
|
461
|
+
return [line for line in lines if _comment(line) is None]
|