systemap 1.0.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.
- systemap/__init__.py +48 -0
- systemap/__main__.py +6 -0
- systemap/change.py +328 -0
- systemap/check.py +873 -0
- systemap/cli.py +1006 -0
- systemap/config.py +710 -0
- systemap/delta.py +670 -0
- systemap/describe.py +254 -0
- systemap/evidence.py +157 -0
- systemap/extract.py +938 -0
- systemap/facts.py +218 -0
- systemap/figure.py +370 -0
- systemap/judgement.py +622 -0
- systemap/model.py +732 -0
- systemap/nest.py +199 -0
- systemap/page.py +1003 -0
- systemap/place.py +1053 -0
- systemap/py.typed +0 -0
- systemap/route.py +819 -0
- systemap/scaffold.py +404 -0
- systemap/schematic.py +1915 -0
- systemap/skill/SKILL.md +240 -0
- systemap/skill/references/example.md +201 -0
- systemap/skill/references/journeys-and-invariants.md +63 -0
- systemap/skill/references/layers.md +154 -0
- systemap/skill/references/layout.md +116 -0
- systemap/skill/references/maintenance.md +73 -0
- systemap/skill/references/pitfalls.md +152 -0
- systemap/skill/references/schema.md +336 -0
- systemap/skill/references/second-pass.md +149 -0
- systemap/skill.py +61 -0
- systemap/suggest.py +184 -0
- systemap/theme.py +521 -0
- systemap-1.0.0.dist-info/METADATA +253 -0
- systemap-1.0.0.dist-info/RECORD +38 -0
- systemap-1.0.0.dist-info/WHEEL +4 -0
- systemap-1.0.0.dist-info/entry_points.txt +2 -0
- systemap-1.0.0.dist-info/licenses/LICENSE +21 -0
systemap/extract.py
ADDED
|
@@ -0,0 +1,938 @@
|
|
|
1
|
+
"""Extract the derived tier of the system map from the working tree.
|
|
2
|
+
|
|
3
|
+
Everything here is a fact read out of the code: module graph, public surface,
|
|
4
|
+
owned types, refusals, every public module-level name, the third-party
|
|
5
|
+
imports, the tests that guard each component, and the entry points a run of
|
|
6
|
+
the system can start from. No prose is invented; what the system is MEANT
|
|
7
|
+
to do lives in the consumer's model module, and the page styles the two
|
|
8
|
+
differently on purpose.
|
|
9
|
+
|
|
10
|
+
Every field written is declared once, in `FIELDS`; the skill's schema
|
|
11
|
+
reference is generated from that table and a test compares the two, so
|
|
12
|
+
the facts file cannot carry a field the reader was not told about.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import ast
|
|
18
|
+
import contextlib
|
|
19
|
+
import hashlib
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
import tomllib
|
|
25
|
+
from collections import defaultdict
|
|
26
|
+
from collections.abc import Mapping
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from systemap.config import Config
|
|
31
|
+
from systemap.model import Model, is_symbol, module_matches, public_names
|
|
32
|
+
|
|
33
|
+
SKIP_PARTS = {".git", ".venv", "node_modules", "__pycache__", "build", "dist"}
|
|
34
|
+
# The facts format. 2 since a package __init__ records the names it
|
|
35
|
+
# re-exports; a stored file of an older format is reported as stale.
|
|
36
|
+
FORMAT = 2
|
|
37
|
+
TESTS_KEPT = 25
|
|
38
|
+
CONSTANTS_KEPT = 14
|
|
39
|
+
UPPER_NAME = re.compile(r"[A-Z][A-Z0-9_]{2,}")
|
|
40
|
+
|
|
41
|
+
# Every field the extractor writes: (scope, field, what it holds). The
|
|
42
|
+
# scopes are the file itself, each module record under `components`, and
|
|
43
|
+
# each record under `entry_points`. `facts_doc` renders this table for the
|
|
44
|
+
# skill's schema reference; the test compares the rendered text with the
|
|
45
|
+
# shipped reference and the table with what `build` actually writes.
|
|
46
|
+
FIELDS: tuple[tuple[str, str, str], ...] = (
|
|
47
|
+
(
|
|
48
|
+
"facts",
|
|
49
|
+
"version",
|
|
50
|
+
"the facts format; 2, since a package `__init__` records the names it re-exports; "
|
|
51
|
+
"`extract --check` reports a file of an older format as stale",
|
|
52
|
+
),
|
|
53
|
+
(
|
|
54
|
+
"facts",
|
|
55
|
+
"built_at_commit",
|
|
56
|
+
"the commit the tree was read at (HEAD when extract ran), or empty outside git; the "
|
|
57
|
+
"page prints it as `facts from <sha>`, and it is the commit before the one that "
|
|
58
|
+
"records the facts, since they are committed after they are read",
|
|
59
|
+
),
|
|
60
|
+
("facts", "packages", "the import names of the package roots"),
|
|
61
|
+
(
|
|
62
|
+
"facts",
|
|
63
|
+
"tests_dirs",
|
|
64
|
+
"the directories test files were read from, relative to the root: the "
|
|
65
|
+
"configured `tests_dir`, or every directory named `tests` or `test`",
|
|
66
|
+
),
|
|
67
|
+
("facts", "spec_sections", "the `##` headings of `spec_path`, each with `level` and `title`"),
|
|
68
|
+
("facts", "entry_points", "where a run can start: one record per point, fields below"),
|
|
69
|
+
("facts", "components", "one record per module, keyed by its dotted name, fields below"),
|
|
70
|
+
("module", "id", "the dotted module name"),
|
|
71
|
+
("module", "file", "the path relative to the root"),
|
|
72
|
+
("module", "package", "the first segment of the name"),
|
|
73
|
+
("module", "plane", "the second segment when `planes` names it, else `core`"),
|
|
74
|
+
("module", "loc", "lines in the file"),
|
|
75
|
+
("module", "sha", "twelve hex digits of the source's SHA-1: the change detector's key"),
|
|
76
|
+
("module", "docstring", "the first paragraph of the module docstring, capped"),
|
|
77
|
+
("module", "functions", "public functions: `name` and `signature`"),
|
|
78
|
+
(
|
|
79
|
+
"module",
|
|
80
|
+
"classes",
|
|
81
|
+
"public classes that are not errors: `name` and `methods` (public method signatures)",
|
|
82
|
+
),
|
|
83
|
+
("module", "errors", "public classes named or based on Error or Exception, the same fields"),
|
|
84
|
+
("module", "constants", "UPPER_CASE assignments: `name` and `value`, the first 14"),
|
|
85
|
+
(
|
|
86
|
+
"module",
|
|
87
|
+
"names",
|
|
88
|
+
"every public module-level name in source order, with its `kind`: `function`, "
|
|
89
|
+
"`class`, `error`, `constant` (UPPER_CASE) or `object` (any other assignment, "
|
|
90
|
+
"such as `app` or `root_agent`). A package `__init__` also lists every name it "
|
|
91
|
+
"imports from the package's own modules, with `reexport_of` naming the module "
|
|
92
|
+
"that defines it and the kind that module gives it (`module` for a submodule "
|
|
93
|
+
"imported whole). A component's `entry` and `interface` may name any of them",
|
|
94
|
+
),
|
|
95
|
+
(
|
|
96
|
+
"module",
|
|
97
|
+
"uses",
|
|
98
|
+
"the package's modules this one imports, each with the names taken from it, "
|
|
99
|
+
"or `*` for the whole module",
|
|
100
|
+
),
|
|
101
|
+
("module", "imports", "the keys of `uses`"),
|
|
102
|
+
("module", "imported_by", "the package's modules that import this one"),
|
|
103
|
+
(
|
|
104
|
+
"module",
|
|
105
|
+
"external",
|
|
106
|
+
"third-party modules imported, as the dotted names written in the import "
|
|
107
|
+
"(`anthropic`, `google.adk`); the standard library and the package's own "
|
|
108
|
+
"modules are left out. The judgement's `model sdk` line reads it",
|
|
109
|
+
),
|
|
110
|
+
("module", "tests_total", "how many test functions import this module"),
|
|
111
|
+
("module", "tests_primary", "how many of those sit in a file named after the module"),
|
|
112
|
+
("module", "tests", "the names of up to 25 of those tests, primary first"),
|
|
113
|
+
(
|
|
114
|
+
"entry point",
|
|
115
|
+
"kind",
|
|
116
|
+
"`console_script`, `main_module`, `main_function`, `subcommand` or `public_function`",
|
|
117
|
+
),
|
|
118
|
+
(
|
|
119
|
+
"entry point",
|
|
120
|
+
"name",
|
|
121
|
+
"the script name, the `python -m` line, `main`, the subcommand word, or the function name",
|
|
122
|
+
),
|
|
123
|
+
("entry point", "module", "the module that defines it"),
|
|
124
|
+
(
|
|
125
|
+
"entry point",
|
|
126
|
+
"target",
|
|
127
|
+
"the function a console script names, or the console script a subcommand "
|
|
128
|
+
"belongs to; else empty",
|
|
129
|
+
),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
SCOPE_TITLES = {
|
|
133
|
+
"facts": "The file",
|
|
134
|
+
"module": "Each module, under `components`",
|
|
135
|
+
"entry point": "Each entry point, under `entry_points`",
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def fields_of(scope: str) -> set[str]:
|
|
140
|
+
return {name for sc, name, _ in FIELDS if sc == scope}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def facts_doc() -> str:
|
|
144
|
+
"""The facts section of the skill's schema reference, from `FIELDS`."""
|
|
145
|
+
out = [
|
|
146
|
+
"## The facts file",
|
|
147
|
+
"",
|
|
148
|
+
"`docs/map/map.json` by default, written by `systemap extract`. Every field,",
|
|
149
|
+
"from the extractor's own table (`systemap.extract.FIELDS`):",
|
|
150
|
+
]
|
|
151
|
+
for scope, title in SCOPE_TITLES.items():
|
|
152
|
+
out += ["", f"**{title}**", ""]
|
|
153
|
+
out += [f"- `{name}`: {what}." for sc, name, what in FIELDS if sc == scope]
|
|
154
|
+
out += [
|
|
155
|
+
"",
|
|
156
|
+
"**The extract summary**",
|
|
157
|
+
"",
|
|
158
|
+
"The counts `systemap extract` prints, each mapped to a field above, and none of",
|
|
159
|
+
"them for the map: `modules` counts the records under `components`; `functions`,",
|
|
160
|
+
"`classes` and `errors` sum each module's field of that name; `tests` sums",
|
|
161
|
+
"`tests_total`, and the number in a file named after the module `tests_primary`;",
|
|
162
|
+
"`empty package markers` lists every `__init__` record with no public `names`",
|
|
163
|
+
"and nothing under `imports` or `external`, which the coverage rule leaves out on",
|
|
164
|
+
"its own.",
|
|
165
|
+
]
|
|
166
|
+
return "\n".join(out) + "\n"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def module_of(path: Path, pkg_dir: Path, pkg_name: str) -> str:
|
|
170
|
+
rel = path.relative_to(pkg_dir).with_suffix("")
|
|
171
|
+
parts = [p for p in rel.parts if p != "__init__"]
|
|
172
|
+
return ".".join([pkg_name, *parts]) if parts else pkg_name
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def plane_of(module: str, planes: tuple[str, ...]) -> str:
|
|
176
|
+
"""The architectural plane a module belongs to, from its dotted path."""
|
|
177
|
+
parts = module.split(".")
|
|
178
|
+
if len(parts) > 2 and parts[1] in planes:
|
|
179
|
+
return parts[1]
|
|
180
|
+
return "core"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def signature(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
|
|
184
|
+
try:
|
|
185
|
+
args = ast.unparse(node.args)
|
|
186
|
+
except (AttributeError, ValueError):
|
|
187
|
+
args = "..."
|
|
188
|
+
ret = ""
|
|
189
|
+
if node.returns is not None:
|
|
190
|
+
try:
|
|
191
|
+
ret = f" -> {ast.unparse(node.returns)}"
|
|
192
|
+
except (AttributeError, ValueError):
|
|
193
|
+
ret = ""
|
|
194
|
+
prefix = "async def " if isinstance(node, ast.AsyncFunctionDef) else "def "
|
|
195
|
+
return f"{prefix}{node.name}({args}){ret}"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def opening(text: str | None) -> str:
|
|
199
|
+
"""The first paragraph of a docstring, capped.
|
|
200
|
+
|
|
201
|
+
The map is read for orientation, not as a mirror of the source: the page
|
|
202
|
+
shows a module's opening line, and the file itself is one click away. Storing
|
|
203
|
+
every docstring in full doubled the facts file for text nobody rendered.
|
|
204
|
+
"""
|
|
205
|
+
if not text:
|
|
206
|
+
return ""
|
|
207
|
+
para = text.strip().split("\n\n")[0]
|
|
208
|
+
para = " ".join(para.split())
|
|
209
|
+
return para if len(para) <= 320 else para[:319] + "\u2026"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def first_line(text: str | None) -> str:
|
|
213
|
+
if not text:
|
|
214
|
+
return ""
|
|
215
|
+
for line in text.strip().splitlines():
|
|
216
|
+
stripped = line.strip()
|
|
217
|
+
if stripped:
|
|
218
|
+
return stripped
|
|
219
|
+
return ""
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def sentence(test_name: str) -> str:
|
|
223
|
+
body = test_name[5:] if test_name.startswith("test_") else test_name
|
|
224
|
+
return body.replace("_", " ").strip() or test_name
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def parse_surface(
|
|
228
|
+
raw: str,
|
|
229
|
+
*,
|
|
230
|
+
module: str = "",
|
|
231
|
+
is_package: bool = False,
|
|
232
|
+
prefixes: frozenset[str] = frozenset(),
|
|
233
|
+
) -> dict[str, Any] | None:
|
|
234
|
+
"""The public surface of one module's source, or None if it cannot parse.
|
|
235
|
+
|
|
236
|
+
This is the ONE definition of "public surface" in the map: the extractor
|
|
237
|
+
stores it and the change detector diffs it between two git blobs, so the
|
|
238
|
+
two can never disagree about what a module exports.
|
|
239
|
+
|
|
240
|
+
A package `__init__` (`is_package`, with its dotted `module` name and
|
|
241
|
+
the package `prefixes`) also records the names it imports from the
|
|
242
|
+
package's own modules, under `names` with `reexport_of`: the package's
|
|
243
|
+
public face is those names, and a card may name one as its entry. The
|
|
244
|
+
kind is filled in by `build`, which knows the defining module; here it
|
|
245
|
+
is `reexport`.
|
|
246
|
+
"""
|
|
247
|
+
try:
|
|
248
|
+
tree = ast.parse(raw)
|
|
249
|
+
except (SyntaxError, ValueError):
|
|
250
|
+
return None
|
|
251
|
+
functions: list[dict[str, Any]] = []
|
|
252
|
+
classes: list[dict[str, Any]] = []
|
|
253
|
+
errors: list[dict[str, Any]] = []
|
|
254
|
+
constants: list[dict[str, str]] = []
|
|
255
|
+
# Every public module-level name with its kind, so an `entry` can be a
|
|
256
|
+
# lower-case object (`app`, `root_agent`) as well as a function or class.
|
|
257
|
+
names: list[dict[str, str]] = []
|
|
258
|
+
for node in tree.body:
|
|
259
|
+
if isinstance(node, ast.ImportFrom) and is_package and module:
|
|
260
|
+
source = _reexport_source(node, module, prefixes)
|
|
261
|
+
if source is None:
|
|
262
|
+
continue
|
|
263
|
+
for alias in node.names:
|
|
264
|
+
public = alias.asname or alias.name
|
|
265
|
+
if alias.name == "*" or public.startswith("_"):
|
|
266
|
+
continue
|
|
267
|
+
entry = {"name": public, "kind": "reexport", "reexport_of": source}
|
|
268
|
+
if alias.asname:
|
|
269
|
+
# The defining module knows it by its own name; `build`
|
|
270
|
+
# reads that for the kind and drops it.
|
|
271
|
+
entry["defined_as"] = alias.name
|
|
272
|
+
names.append(entry)
|
|
273
|
+
elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
274
|
+
if node.name.startswith("_"):
|
|
275
|
+
continue
|
|
276
|
+
names.append({"name": node.name, "kind": "function"})
|
|
277
|
+
# The signature is the surface; a docstring is prose nobody
|
|
278
|
+
# renders, and it doubled the facts file on a real tree.
|
|
279
|
+
functions.append({"name": node.name, "signature": signature(node)})
|
|
280
|
+
elif isinstance(node, ast.ClassDef):
|
|
281
|
+
if node.name.startswith("_"):
|
|
282
|
+
continue
|
|
283
|
+
bases = []
|
|
284
|
+
for b in node.bases:
|
|
285
|
+
with contextlib.suppress(AttributeError, ValueError):
|
|
286
|
+
bases.append(ast.unparse(b))
|
|
287
|
+
is_error = node.name.endswith(("Error", "Exception")) or any(
|
|
288
|
+
"Error" in b or "Exception" in b for b in bases
|
|
289
|
+
)
|
|
290
|
+
record = {
|
|
291
|
+
"name": node.name,
|
|
292
|
+
# Full signatures, not names: a class's surface includes what
|
|
293
|
+
# its methods accept and return, so a parameter change is a
|
|
294
|
+
# change to the type.
|
|
295
|
+
"methods": [
|
|
296
|
+
signature(n)
|
|
297
|
+
for n in node.body
|
|
298
|
+
if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)
|
|
299
|
+
and not n.name.startswith("_")
|
|
300
|
+
],
|
|
301
|
+
}
|
|
302
|
+
(errors if is_error else classes).append(record)
|
|
303
|
+
names.append({"name": node.name, "kind": "error" if is_error else "class"})
|
|
304
|
+
elif isinstance(node, ast.Assign | ast.AnnAssign):
|
|
305
|
+
# A measured cap declared as `NAME: Final = ...` is an AnnAssign;
|
|
306
|
+
# handling only Assign missed every tuning module.
|
|
307
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
308
|
+
for target in targets:
|
|
309
|
+
if not isinstance(target, ast.Name) or target.id.startswith("_"):
|
|
310
|
+
continue
|
|
311
|
+
if node.value is None:
|
|
312
|
+
continue
|
|
313
|
+
if not UPPER_NAME.fullmatch(target.id):
|
|
314
|
+
names.append({"name": target.id, "kind": "object"})
|
|
315
|
+
continue
|
|
316
|
+
try:
|
|
317
|
+
value = ast.unparse(node.value)
|
|
318
|
+
except (AttributeError, ValueError):
|
|
319
|
+
value = "?"
|
|
320
|
+
constants.append({"name": target.id, "value": value[:80]})
|
|
321
|
+
names.append({"name": target.id, "kind": "constant"})
|
|
322
|
+
return {
|
|
323
|
+
"docstring": opening(ast.get_docstring(tree)),
|
|
324
|
+
"functions": functions,
|
|
325
|
+
"classes": classes,
|
|
326
|
+
"errors": errors,
|
|
327
|
+
"constants": constants,
|
|
328
|
+
"names": names,
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _reexport_source(node: ast.ImportFrom, module: str, prefixes: frozenset[str]) -> str | None:
|
|
333
|
+
"""The dotted module a `from ... import` in a package `__init__` reads from,
|
|
334
|
+
when it is one of the package's own; None for anything else."""
|
|
335
|
+
if node.level:
|
|
336
|
+
# Relative to the package itself: `.mod` is a sibling module of
|
|
337
|
+
# the __init__, each further level one package up.
|
|
338
|
+
anchor = module.split(".")
|
|
339
|
+
if node.level > 1:
|
|
340
|
+
anchor = anchor[: len(anchor) - (node.level - 1)]
|
|
341
|
+
if not anchor:
|
|
342
|
+
return None
|
|
343
|
+
return ".".join([*anchor, *node.module.split(".")] if node.module else anchor)
|
|
344
|
+
if not node.module or node.module.split(".")[0] not in prefixes:
|
|
345
|
+
return None
|
|
346
|
+
return node.module
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def resolve_reexports(components: dict[str, Any]) -> None:
|
|
350
|
+
"""Give every re-exported name the kind its defining module records.
|
|
351
|
+
|
|
352
|
+
`from . import mod` re-exports a module: its kind is `module` and
|
|
353
|
+
`reexport_of` the module itself. A name the source module does not
|
|
354
|
+
define (imported from elsewhere in turn, or from a module the facts
|
|
355
|
+
lack) keeps `reexport_of` and takes the kind `object`.
|
|
356
|
+
"""
|
|
357
|
+
for record in components.values():
|
|
358
|
+
for entry in record.get("names", []):
|
|
359
|
+
if entry.get("kind") != "reexport":
|
|
360
|
+
continue
|
|
361
|
+
source = entry["reexport_of"]
|
|
362
|
+
original = entry.pop("defined_as", entry["name"])
|
|
363
|
+
as_module = f"{source}.{original}"
|
|
364
|
+
if as_module in components:
|
|
365
|
+
entry["reexport_of"] = as_module
|
|
366
|
+
entry["kind"] = "module"
|
|
367
|
+
continue
|
|
368
|
+
defined = {n["name"]: n["kind"] for n in components.get(source, {}).get("names", [])}
|
|
369
|
+
entry["kind"] = defined.get(original, "object")
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def collect_module(
|
|
373
|
+
path: Path, repo: Path, module: str = "", prefixes: frozenset[str] = frozenset()
|
|
374
|
+
) -> dict[str, Any] | None:
|
|
375
|
+
try:
|
|
376
|
+
raw = path.read_text(encoding="utf-8")
|
|
377
|
+
except OSError:
|
|
378
|
+
return None
|
|
379
|
+
surface = parse_surface(
|
|
380
|
+
raw, module=module, is_package=path.name == "__init__.py", prefixes=prefixes
|
|
381
|
+
)
|
|
382
|
+
if surface is None:
|
|
383
|
+
return None
|
|
384
|
+
return {
|
|
385
|
+
"file": path.relative_to(repo).as_posix(),
|
|
386
|
+
"loc": len(raw.splitlines()),
|
|
387
|
+
# A change detector for the map, never a security claim: usedforsecurity=False
|
|
388
|
+
# states that and keeps the digest byte-identical, so committed facts files
|
|
389
|
+
# stay comparable across the flag.
|
|
390
|
+
"sha": hashlib.sha1(raw.encode("utf-8"), usedforsecurity=False).hexdigest()[:12],
|
|
391
|
+
**surface,
|
|
392
|
+
"constants": surface["constants"][:CONSTANTS_KEPT],
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
# In a `uses` mapping, this marks "the whole module": `import m` gives access
|
|
397
|
+
# to every name in m, so no list of names would be honest.
|
|
398
|
+
WHOLE_MODULE = "*"
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def internal_uses(
|
|
402
|
+
raw: str,
|
|
403
|
+
prefixes: set[str],
|
|
404
|
+
known: set[str],
|
|
405
|
+
module: str = "",
|
|
406
|
+
is_package: bool = False,
|
|
407
|
+
) -> dict[str, set[str]]:
|
|
408
|
+
"""target module -> the names this source takes from it.
|
|
409
|
+
|
|
410
|
+
A value containing WHOLE_MODULE means the source imported the module
|
|
411
|
+
itself, so any name in it may be used. Relative imports resolve against
|
|
412
|
+
`module` (the importer's own dotted name); without it they are skipped.
|
|
413
|
+
"""
|
|
414
|
+
try:
|
|
415
|
+
tree = ast.parse(raw)
|
|
416
|
+
except (SyntaxError, ValueError):
|
|
417
|
+
return {}
|
|
418
|
+
|
|
419
|
+
def resolve(name: str) -> str | None:
|
|
420
|
+
if name in known:
|
|
421
|
+
return name
|
|
422
|
+
parts = name.split(".")
|
|
423
|
+
while len(parts) > 1:
|
|
424
|
+
parts.pop()
|
|
425
|
+
candidate = ".".join(parts)
|
|
426
|
+
if candidate in known:
|
|
427
|
+
return candidate
|
|
428
|
+
return None
|
|
429
|
+
|
|
430
|
+
uses: dict[str, set[str]] = defaultdict(set)
|
|
431
|
+
for node in ast.walk(tree):
|
|
432
|
+
if isinstance(node, ast.Import):
|
|
433
|
+
for alias in node.names:
|
|
434
|
+
if alias.name.split(".")[0] in prefixes:
|
|
435
|
+
target = resolve(alias.name)
|
|
436
|
+
if target:
|
|
437
|
+
uses[target].add(WHOLE_MODULE)
|
|
438
|
+
elif isinstance(node, ast.ImportFrom):
|
|
439
|
+
if node.level:
|
|
440
|
+
if not module:
|
|
441
|
+
continue
|
|
442
|
+
# The anchor package: a module's own package, or the package
|
|
443
|
+
# itself when the source is an __init__. Each further level
|
|
444
|
+
# climbs one package up.
|
|
445
|
+
anchor = module.split(".")
|
|
446
|
+
if not is_package:
|
|
447
|
+
anchor = anchor[:-1]
|
|
448
|
+
if node.level > 1:
|
|
449
|
+
anchor = anchor[: len(anchor) - (node.level - 1)]
|
|
450
|
+
if not anchor:
|
|
451
|
+
continue
|
|
452
|
+
parts = [*anchor, *node.module.split(".")] if node.module else anchor
|
|
453
|
+
src = ".".join(parts)
|
|
454
|
+
else:
|
|
455
|
+
if not node.module:
|
|
456
|
+
continue
|
|
457
|
+
src = node.module
|
|
458
|
+
if src.split(".")[0] not in prefixes:
|
|
459
|
+
continue
|
|
460
|
+
base = resolve(src)
|
|
461
|
+
for alias in node.names:
|
|
462
|
+
if alias.name == "*":
|
|
463
|
+
if base:
|
|
464
|
+
uses[base].add(WHOLE_MODULE)
|
|
465
|
+
continue
|
|
466
|
+
# Exact membership only: resolve() walks prefixes upward, so it
|
|
467
|
+
# would resolve a class name to its module and misread every
|
|
468
|
+
# from-import as a whole-module import.
|
|
469
|
+
if f"{src}.{alias.name}" in known:
|
|
470
|
+
uses[f"{src}.{alias.name}"].add(WHOLE_MODULE)
|
|
471
|
+
elif base:
|
|
472
|
+
uses[base].add(alias.name)
|
|
473
|
+
return dict(uses)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def external_imports(raw: str, prefixes: set[str]) -> list[str]:
|
|
477
|
+
"""The third-party modules one source imports, as the dotted names written.
|
|
478
|
+
|
|
479
|
+
The standard library, `__future__` and the package's own modules are
|
|
480
|
+
left out; relative imports are the package's own. The names are kept
|
|
481
|
+
dotted (`google.adk`, not `google`) because that is the level at which
|
|
482
|
+
a model SDK is told apart from its namespace.
|
|
483
|
+
"""
|
|
484
|
+
try:
|
|
485
|
+
tree = ast.parse(raw)
|
|
486
|
+
except (SyntaxError, ValueError):
|
|
487
|
+
return []
|
|
488
|
+
out: set[str] = set()
|
|
489
|
+
for node in ast.walk(tree):
|
|
490
|
+
if isinstance(node, ast.Import):
|
|
491
|
+
candidates = [alias.name for alias in node.names]
|
|
492
|
+
elif isinstance(node, ast.ImportFrom) and not node.level and node.module:
|
|
493
|
+
candidates = [node.module]
|
|
494
|
+
else:
|
|
495
|
+
continue
|
|
496
|
+
for name in candidates:
|
|
497
|
+
top = name.split(".")[0]
|
|
498
|
+
if top in prefixes or top in sys.stdlib_module_names or top == "__future__":
|
|
499
|
+
continue
|
|
500
|
+
out.add(name)
|
|
501
|
+
return sorted(out)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def internal_imports(path: Path, prefixes: set[str], known: set[str]) -> set[str]:
|
|
505
|
+
try:
|
|
506
|
+
raw = path.read_text(encoding="utf-8")
|
|
507
|
+
except OSError:
|
|
508
|
+
return set()
|
|
509
|
+
return set(internal_uses(raw, prefixes, known))
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def test_names(raw: str) -> list[str]:
|
|
513
|
+
"""Test functions in one test file's source, at any nesting depth."""
|
|
514
|
+
try:
|
|
515
|
+
tree = ast.parse(raw)
|
|
516
|
+
except (SyntaxError, ValueError):
|
|
517
|
+
return []
|
|
518
|
+
return [
|
|
519
|
+
n.name
|
|
520
|
+
for n in ast.walk(tree)
|
|
521
|
+
if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef) and n.name.startswith("test_")
|
|
522
|
+
]
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def collect_tests(
|
|
526
|
+
repo: Path, tests_dirs: tuple[str, ...], prefixes: set[str], known: set[str]
|
|
527
|
+
) -> dict[str, list[dict[str, Any]]]:
|
|
528
|
+
"""module -> the behaviours asserted by tests that import it.
|
|
529
|
+
|
|
530
|
+
`tests_dirs` are read in order; a file under two of them is read once.
|
|
531
|
+
"""
|
|
532
|
+
guards: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
533
|
+
seen: set[Path] = set()
|
|
534
|
+
files: list[Path] = []
|
|
535
|
+
for rel in tests_dirs:
|
|
536
|
+
test_dir = repo / rel
|
|
537
|
+
if not rel or not test_dir.is_dir():
|
|
538
|
+
continue
|
|
539
|
+
for path in sorted(test_dir.rglob("test_*.py")):
|
|
540
|
+
if path in seen or any(p in SKIP_PARTS for p in path.parts):
|
|
541
|
+
continue
|
|
542
|
+
seen.add(path)
|
|
543
|
+
files.append(path)
|
|
544
|
+
for path in files:
|
|
545
|
+
try:
|
|
546
|
+
raw = path.read_text(encoding="utf-8")
|
|
547
|
+
except OSError:
|
|
548
|
+
continue
|
|
549
|
+
targets = set(internal_uses(raw, prefixes, known))
|
|
550
|
+
if not targets:
|
|
551
|
+
continue
|
|
552
|
+
names = test_names(raw)
|
|
553
|
+
stem = path.stem[5:] if path.stem.startswith("test_") else path.stem
|
|
554
|
+
for target in targets:
|
|
555
|
+
# A test file named after the module is its primary guard; a file
|
|
556
|
+
# that merely imports it exercises it. Both are true, and the
|
|
557
|
+
# distinction is what stops a shared helper from claiming every test.
|
|
558
|
+
primary = stem == target.split(".")[-1]
|
|
559
|
+
for name in names:
|
|
560
|
+
guards[target].append({"name": name, "primary": primary})
|
|
561
|
+
return guards
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def spec_sections(repo: Path, spec_path: str) -> list[dict[str, str]]:
|
|
565
|
+
if not spec_path:
|
|
566
|
+
return []
|
|
567
|
+
path = repo / spec_path
|
|
568
|
+
if not path.is_file():
|
|
569
|
+
return []
|
|
570
|
+
out: list[dict[str, str]] = []
|
|
571
|
+
try:
|
|
572
|
+
text = path.read_text(encoding="utf-8")
|
|
573
|
+
except OSError:
|
|
574
|
+
return []
|
|
575
|
+
for match in re.finditer(r"^(#{2,4})\s+(.+)$", text, re.M):
|
|
576
|
+
out.append({"level": str(len(match.group(1))), "title": match.group(2).strip()})
|
|
577
|
+
return out
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
# ---- entry points: where a run of the system starts ----------------------------
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def subcommands(raw: str) -> list[str]:
|
|
584
|
+
"""The argparse subcommand names one module's source adds, where detectable.
|
|
585
|
+
|
|
586
|
+
A call `<anything>.add_parser("name", ...)` with a literal first
|
|
587
|
+
argument is a subcommand. A name built from a variable is not
|
|
588
|
+
detected; the judgement can only ask about what the tree states.
|
|
589
|
+
"""
|
|
590
|
+
try:
|
|
591
|
+
tree = ast.parse(raw)
|
|
592
|
+
except (SyntaxError, ValueError):
|
|
593
|
+
return []
|
|
594
|
+
out: list[str] = []
|
|
595
|
+
for node in ast.walk(tree):
|
|
596
|
+
if (
|
|
597
|
+
isinstance(node, ast.Call)
|
|
598
|
+
and isinstance(node.func, ast.Attribute)
|
|
599
|
+
and node.func.attr == "add_parser"
|
|
600
|
+
and node.args
|
|
601
|
+
and isinstance(node.args[0], ast.Constant)
|
|
602
|
+
and isinstance(node.args[0].value, str)
|
|
603
|
+
):
|
|
604
|
+
out.append(node.args[0].value)
|
|
605
|
+
return out
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def console_scripts(repo: Path) -> dict[str, tuple[str, str]]:
|
|
609
|
+
"""name -> (module, function) from `[project.scripts]` in pyproject.toml."""
|
|
610
|
+
path = repo / "pyproject.toml"
|
|
611
|
+
if not path.is_file():
|
|
612
|
+
return {}
|
|
613
|
+
try:
|
|
614
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
615
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
616
|
+
return {}
|
|
617
|
+
scripts = data.get("project", {}).get("scripts", {})
|
|
618
|
+
out: dict[str, tuple[str, str]] = {}
|
|
619
|
+
if isinstance(scripts, dict):
|
|
620
|
+
for name, target in scripts.items():
|
|
621
|
+
if isinstance(target, str) and ":" in target:
|
|
622
|
+
module, func = target.split(":", 1)
|
|
623
|
+
out[str(name)] = (module.strip(), func.strip())
|
|
624
|
+
return out
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def entry_points(
|
|
628
|
+
repo: Path, prefixes: set[str], components: dict[str, Any], sources: dict[str, str]
|
|
629
|
+
) -> list[dict[str, str]]:
|
|
630
|
+
"""Where a run of the system can start, read out of the tree.
|
|
631
|
+
|
|
632
|
+
Console scripts in pyproject.toml, `__main__` modules, `main`
|
|
633
|
+
functions, argparse subcommands where detectable, and the public
|
|
634
|
+
functions of each package root. Every one is a walk a reader may
|
|
635
|
+
need; `systemap judgement` asks about each that has no journey.
|
|
636
|
+
A subcommand carries the console script that reaches its module, so
|
|
637
|
+
the judgement can name it the way a person types it.
|
|
638
|
+
"""
|
|
639
|
+
scripts = {
|
|
640
|
+
name: (module, func)
|
|
641
|
+
for name, (module, func) in sorted(console_scripts(repo).items())
|
|
642
|
+
if module in components
|
|
643
|
+
}
|
|
644
|
+
script_of_module = {module: name for name, (module, _f) in scripts.items()}
|
|
645
|
+
out: list[dict[str, str]] = []
|
|
646
|
+
for name, (module, func) in scripts.items():
|
|
647
|
+
out.append({"kind": "console_script", "name": name, "module": module, "target": func})
|
|
648
|
+
for module, record in sorted(components.items()):
|
|
649
|
+
if module.endswith(".__main__"):
|
|
650
|
+
pkg = module[: -len(".__main__")]
|
|
651
|
+
out.append(
|
|
652
|
+
{"kind": "main_module", "name": f"python -m {pkg}", "module": module, "target": ""}
|
|
653
|
+
)
|
|
654
|
+
if any(f["name"] == "main" for f in record["functions"]):
|
|
655
|
+
out.append(
|
|
656
|
+
{"kind": "main_function", "name": "main", "module": module, "target": "main"}
|
|
657
|
+
)
|
|
658
|
+
for sub in subcommands(sources.get(module, "")):
|
|
659
|
+
out.append(
|
|
660
|
+
{
|
|
661
|
+
"kind": "subcommand",
|
|
662
|
+
"name": sub,
|
|
663
|
+
"module": module,
|
|
664
|
+
"target": script_of_module.get(module, ""),
|
|
665
|
+
}
|
|
666
|
+
)
|
|
667
|
+
if module in prefixes:
|
|
668
|
+
for f in record["functions"]:
|
|
669
|
+
out.append(
|
|
670
|
+
{"kind": "public_function", "name": f["name"], "module": module, "target": ""}
|
|
671
|
+
)
|
|
672
|
+
return out
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def entry_label(point: dict[str, str]) -> str:
|
|
676
|
+
"""The entry point the way a person would name it."""
|
|
677
|
+
kind, name, module, target = point["kind"], point["name"], point["module"], point["target"]
|
|
678
|
+
if kind == "console_script":
|
|
679
|
+
return f"{name} (console script)"
|
|
680
|
+
if kind == "main_module":
|
|
681
|
+
return name
|
|
682
|
+
if kind == "main_function":
|
|
683
|
+
return f"main() in {module}"
|
|
684
|
+
if kind == "subcommand":
|
|
685
|
+
return f"{target} {name} (subcommand)" if target else f"{name} (subcommand in {module})"
|
|
686
|
+
return f"{name}() in {module}"
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def build(cfg: Config) -> dict[str, Any]:
|
|
690
|
+
"""The facts for the tree at `cfg.root`, ready to be written as JSON."""
|
|
691
|
+
repo = cfg.root
|
|
692
|
+
roots = cfg.roots
|
|
693
|
+
prefixes = {name for _, name in roots}
|
|
694
|
+
paths: dict[str, Path] = {}
|
|
695
|
+
for pkg_dir, pkg_name in roots:
|
|
696
|
+
for path in pkg_dir.rglob("*.py"):
|
|
697
|
+
if any(p in SKIP_PARTS for p in path.parts):
|
|
698
|
+
continue
|
|
699
|
+
paths[module_of(path, pkg_dir, pkg_name)] = path
|
|
700
|
+
known = set(paths)
|
|
701
|
+
|
|
702
|
+
components: dict[str, Any] = {}
|
|
703
|
+
imports: dict[str, set[str]] = {}
|
|
704
|
+
sources: dict[str, str] = {}
|
|
705
|
+
for module, path in sorted(paths.items()):
|
|
706
|
+
record = collect_module(path, repo, module, frozenset(prefixes))
|
|
707
|
+
if record is None:
|
|
708
|
+
continue
|
|
709
|
+
record["id"] = module
|
|
710
|
+
record["package"] = module.split(".")[0]
|
|
711
|
+
record["plane"] = plane_of(module, cfg.planes)
|
|
712
|
+
try:
|
|
713
|
+
raw = path.read_text(encoding="utf-8")
|
|
714
|
+
except OSError:
|
|
715
|
+
raw = ""
|
|
716
|
+
sources[module] = raw
|
|
717
|
+
uses = internal_uses(
|
|
718
|
+
raw, prefixes, known, module=module, is_package=path.name == "__init__.py"
|
|
719
|
+
)
|
|
720
|
+
uses.pop(module, None)
|
|
721
|
+
record["uses"] = {
|
|
722
|
+
target: [WHOLE_MODULE] if WHOLE_MODULE in names else sorted(names)
|
|
723
|
+
for target, names in sorted(uses.items())
|
|
724
|
+
}
|
|
725
|
+
record["external"] = external_imports(raw, prefixes)
|
|
726
|
+
imports[module] = set(uses)
|
|
727
|
+
components[module] = record
|
|
728
|
+
|
|
729
|
+
# Every module is parsed before a re-export can be given the kind its
|
|
730
|
+
# defining module records.
|
|
731
|
+
resolve_reexports(components)
|
|
732
|
+
importers: dict[str, set[str]] = defaultdict(set)
|
|
733
|
+
for module, deps in imports.items():
|
|
734
|
+
for dep in deps:
|
|
735
|
+
importers[dep].add(module)
|
|
736
|
+
for module, record in components.items():
|
|
737
|
+
record["imports"] = sorted(imports.get(module, set()))
|
|
738
|
+
record["imported_by"] = sorted(importers.get(module, set()))
|
|
739
|
+
|
|
740
|
+
tests_dirs = cfg.test_dirs
|
|
741
|
+
guards = collect_tests(repo, tests_dirs, prefixes, known)
|
|
742
|
+
for module, record in components.items():
|
|
743
|
+
seen: set[str] = set()
|
|
744
|
+
unique: list[dict[str, Any]] = []
|
|
745
|
+
for item in guards.get(module, []):
|
|
746
|
+
if item["name"] in seen:
|
|
747
|
+
continue
|
|
748
|
+
seen.add(item["name"])
|
|
749
|
+
unique.append(item)
|
|
750
|
+
unique.sort(key=lambda t: (not t["primary"], t["name"]))
|
|
751
|
+
record["tests_total"] = len(unique)
|
|
752
|
+
record["tests_primary"] = sum(1 for t in unique if t["primary"])
|
|
753
|
+
# The full list is recoverable from the tree; the map keeps a sample so
|
|
754
|
+
# a committed file that changes on every merge stays diffable by eye.
|
|
755
|
+
# Names only: the sentence is derived where it is displayed.
|
|
756
|
+
record["tests"] = [t["name"] for t in unique[:TESTS_KEPT]]
|
|
757
|
+
|
|
758
|
+
head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, capture_output=True, text=True)
|
|
759
|
+
return {
|
|
760
|
+
"version": FORMAT,
|
|
761
|
+
"built_at_commit": head.stdout.strip() if head.returncode == 0 else "",
|
|
762
|
+
"packages": sorted(prefixes),
|
|
763
|
+
"tests_dirs": list(tests_dirs),
|
|
764
|
+
"spec_sections": spec_sections(repo, cfg.spec_path),
|
|
765
|
+
"entry_points": entry_points(repo, prefixes, components, sources),
|
|
766
|
+
"components": components,
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def drift(fresh: dict[str, Any], stored: dict[str, Any]) -> list[str]:
|
|
771
|
+
"""Ways the stored facts no longer describe the tree. Empty means current."""
|
|
772
|
+
out: list[str] = []
|
|
773
|
+
new_c, old_c = fresh["components"], (stored or {}).get("components", {})
|
|
774
|
+
# A file written by an older extractor records less than this one
|
|
775
|
+
# reads (a re-export, say), whatever the tree did since.
|
|
776
|
+
if stored and stored.get("version") != fresh.get("version"):
|
|
777
|
+
out.append(
|
|
778
|
+
f"facts format {stored.get('version')} is older than the extractor's "
|
|
779
|
+
f"{fresh.get('version')}; the file records less than the extractor reads"
|
|
780
|
+
)
|
|
781
|
+
# Entry points come partly from pyproject.toml, which no module hash
|
|
782
|
+
# covers, so they are compared on their own.
|
|
783
|
+
new_e = {entry_label(e) for e in fresh.get("entry_points", [])}
|
|
784
|
+
old_e = {entry_label(e) for e in (stored or {}).get("entry_points", [])}
|
|
785
|
+
for label in sorted(new_e - old_e):
|
|
786
|
+
out.append(f"entry point not in the map: {label}")
|
|
787
|
+
for label in sorted(old_e - new_e):
|
|
788
|
+
out.append(f"entry point in the map but gone from the tree: {label}")
|
|
789
|
+
added = sorted(set(new_c) - set(old_c))
|
|
790
|
+
gone = sorted(set(old_c) - set(new_c))
|
|
791
|
+
moved = sorted(m for m in set(new_c) & set(old_c) if new_c[m]["sha"] != old_c[m]["sha"])
|
|
792
|
+
# A source module's hash says nothing about the TESTS that guard it. A new
|
|
793
|
+
# test file changes what the system guarantees without touching a single
|
|
794
|
+
# module, and comparing only shas would let that pass as current. `fresh`
|
|
795
|
+
# is a full rebuild, so the attribution is authoritative here.
|
|
796
|
+
guards_changed = sorted(
|
|
797
|
+
m
|
|
798
|
+
for m in set(new_c) & set(old_c)
|
|
799
|
+
if new_c[m].get("tests_total") != old_c[m].get("tests_total")
|
|
800
|
+
)
|
|
801
|
+
for m in added:
|
|
802
|
+
out.append(f"missing from the map: {m}")
|
|
803
|
+
for m in gone:
|
|
804
|
+
out.append(f"in the map but gone from the tree: {m}")
|
|
805
|
+
for m in moved:
|
|
806
|
+
out.append(f"code changed since the map was built: {m}")
|
|
807
|
+
for m in guards_changed:
|
|
808
|
+
was = (old_c[m] or {}).get("tests_total", 0)
|
|
809
|
+
now = new_c[m].get("tests_total", 0)
|
|
810
|
+
out.append(f"tests guarding it changed ({was} -> {now}): {m}")
|
|
811
|
+
return out
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def mapping_drift(fresh: dict[str, Any], model: Model, prefixes: set[str]) -> list[str]:
|
|
815
|
+
"""Modules the model claims but the tree does not have.
|
|
816
|
+
|
|
817
|
+
The component-to-module mapping is the one hand-authored input the facts
|
|
818
|
+
have. Left unchecked, a rename would quietly leave a card on the page
|
|
819
|
+
for code that is gone instead of failing loudly. The layout itself is
|
|
820
|
+
checked too, since a card drawn outside its band is the same kind of
|
|
821
|
+
quiet lie.
|
|
822
|
+
"""
|
|
823
|
+
known = set(fresh["components"])
|
|
824
|
+
out: list[str] = []
|
|
825
|
+
for c in model.components:
|
|
826
|
+
for m in c.implemented_by:
|
|
827
|
+
# A symbol claim names its module before the colon; the name
|
|
828
|
+
# itself is the entry rule's business.
|
|
829
|
+
module = m.partition(":")[0] if is_symbol(m) else m
|
|
830
|
+
if module.split(".")[0] in prefixes and not any(
|
|
831
|
+
module_matches(module, k) for k in known
|
|
832
|
+
):
|
|
833
|
+
out.append(f"{c.id} names module {module} which is not in the facts")
|
|
834
|
+
out.extend(f"layout: {p}" for p in model.layout_problems())
|
|
835
|
+
return out
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def read_facts(path: Path) -> dict[str, Any]:
|
|
839
|
+
"""The stored facts, or an empty table when there are none or they do not parse."""
|
|
840
|
+
if not path.is_file():
|
|
841
|
+
return {}
|
|
842
|
+
try:
|
|
843
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
844
|
+
except (OSError, json.JSONDecodeError):
|
|
845
|
+
return {}
|
|
846
|
+
return dict(data) if isinstance(data, dict) else {}
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def dumps(facts: dict[str, Any]) -> str:
|
|
850
|
+
"""The facts as committed: compact, keys sorted, one module record per line.
|
|
851
|
+
|
|
852
|
+
A pretty-printed file was 635 KB on a 144-module tree and tripped a
|
|
853
|
+
repository's large-file hook. Each module's record is one line with no
|
|
854
|
+
spaces, so the file stays small and a diff between two commits still
|
|
855
|
+
reads module by module; the top-level keys are one per line too.
|
|
856
|
+
"""
|
|
857
|
+
|
|
858
|
+
def compact(value: Any) -> str:
|
|
859
|
+
return json.dumps(value, separators=(",", ":"), sort_keys=True, ensure_ascii=False)
|
|
860
|
+
|
|
861
|
+
parts: list[str] = []
|
|
862
|
+
for key in sorted(facts):
|
|
863
|
+
value = facts[key]
|
|
864
|
+
if key == "components" and isinstance(value, dict):
|
|
865
|
+
records = ",\n".join(
|
|
866
|
+
f"{json.dumps(module)}:{compact(record)}"
|
|
867
|
+
for module, record in sorted(value.items())
|
|
868
|
+
)
|
|
869
|
+
parts.append(f'"components":{{\n{records}\n}}')
|
|
870
|
+
else:
|
|
871
|
+
parts.append(f"{json.dumps(key)}:{compact(value)}")
|
|
872
|
+
return "{\n" + ",\n".join(parts) + "\n}\n"
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def write_facts(path: Path, facts: dict[str, Any]) -> None:
|
|
876
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
877
|
+
path.write_text(dumps(facts), encoding="utf-8", newline="\n")
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def is_empty_marker(record: Mapping[str, Any]) -> bool:
|
|
881
|
+
"""Is one module record an empty package marker?
|
|
882
|
+
|
|
883
|
+
An `__init__.py` with no public names and no imports, inside or
|
|
884
|
+
outside the package: a file that marks a directory as a package and
|
|
885
|
+
nothing else. It has no place on the map, so the coverage rule leaves
|
|
886
|
+
it out on its own and the extract summary lists it once; a package
|
|
887
|
+
root that re-exports its modules, or imports anything, is a module
|
|
888
|
+
like any other. This is the one definition; the summary and the
|
|
889
|
+
coverage rule both read it.
|
|
890
|
+
"""
|
|
891
|
+
if not str(record.get("file", "")).endswith("__init__.py"):
|
|
892
|
+
return False
|
|
893
|
+
return not public_names(record) and not record.get("imports") and not record.get("external")
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def empty_markers(facts: Mapping[str, Any]) -> list[str]:
|
|
897
|
+
"""Every empty package marker in the facts, by name."""
|
|
898
|
+
return sorted(m for m, r in facts.get("components", {}).items() if is_empty_marker(r))
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def summary(facts: dict[str, Any]) -> list[str]:
|
|
902
|
+
"""The counts printed after an extract, labelled by the field each sums.
|
|
903
|
+
|
|
904
|
+
The map carries no counts (the skill's rule); these feed the change
|
|
905
|
+
detector, and the header says so, so an agent reading the numbers does
|
|
906
|
+
not copy them onto a card. Each label is a field of the facts file, so
|
|
907
|
+
the reference maps every word: `modules` counts `components`, the next
|
|
908
|
+
three sum each module's `functions`, `classes` and `errors`, `tests`
|
|
909
|
+
sums `tests_total` and `tests_primary`, and the markers are the
|
|
910
|
+
`__init__` records with no public names and no imports.
|
|
911
|
+
"""
|
|
912
|
+
comps = facts["components"]
|
|
913
|
+
guarded = sum(c["tests_total"] for c in comps.values())
|
|
914
|
+
primary = sum(c["tests_primary"] for c in comps.values())
|
|
915
|
+
dirs: list[str] = list(facts.get("tests_dirs", []))
|
|
916
|
+
if guarded:
|
|
917
|
+
tests = f"{guarded} test functions import a module, {primary} in a file named after it"
|
|
918
|
+
elif dirs:
|
|
919
|
+
# Zero is a finding, not a count: say where the extractor looked, so
|
|
920
|
+
# a tests directory it did not find is set in `tests_dir`.
|
|
921
|
+
tests = f"none import a module; searched {', '.join(dirs)}"
|
|
922
|
+
else:
|
|
923
|
+
tests = "none import a module; no directory named tests or test was found"
|
|
924
|
+
out = [
|
|
925
|
+
"facts for the change detector (these never appear on the map):",
|
|
926
|
+
f" modules: {len(comps)}",
|
|
927
|
+
f" functions: {sum(len(c['functions']) for c in comps.values())}",
|
|
928
|
+
f" classes: {sum(len(c['classes']) for c in comps.values())}",
|
|
929
|
+
f" errors: {sum(len(c['errors']) for c in comps.values())}",
|
|
930
|
+
f" tests: {tests}",
|
|
931
|
+
]
|
|
932
|
+
markers = empty_markers(facts)
|
|
933
|
+
if markers:
|
|
934
|
+
out.append(
|
|
935
|
+
f" empty package markers: {len(markers)} ({', '.join(markers)}); an __init__ with "
|
|
936
|
+
"no public names and no imports, left out of the coverage rule"
|
|
937
|
+
)
|
|
938
|
+
return out
|