roadkeep 0.2.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.
Files changed (67) hide show
  1. roadkeep/__init__.py +79 -0
  2. roadkeep/adopting.py +2347 -0
  3. roadkeep/attesting.py +293 -0
  4. roadkeep/authoring.py +2117 -0
  5. roadkeep/backlog.py +767 -0
  6. roadkeep/blocking.py +1622 -0
  7. roadkeep/briefing.py +970 -0
  8. roadkeep/budgeting.py +2056 -0
  9. roadkeep/capturing.py +1699 -0
  10. roadkeep/claiming.py +1019 -0
  11. roadkeep/cli.py +638 -0
  12. roadkeep/commanding.py +487 -0
  13. roadkeep/config.py +1832 -0
  14. roadkeep/counting.py +376 -0
  15. roadkeep/criteria.py +933 -0
  16. roadkeep/deferring.py +708 -0
  17. roadkeep/describing.py +568 -0
  18. roadkeep/exporting.py +808 -0
  19. roadkeep/fixing.py +629 -0
  20. roadkeep/governing.py +934 -0
  21. roadkeep/graph.py +395 -0
  22. roadkeep/guarding.py +1028 -0
  23. roadkeep/history.py +2403 -0
  24. roadkeep/ids.py +301 -0
  25. roadkeep/installing.py +2145 -0
  26. roadkeep/kernel/__init__.py +24 -0
  27. roadkeep/kernel/document.py +1719 -0
  28. roadkeep/kernel/schema.py +2308 -0
  29. roadkeep/linting.py +4420 -0
  30. roadkeep/locking.py +209 -0
  31. roadkeep/markers.py +172 -0
  32. roadkeep/merging.py +1159 -0
  33. roadkeep/picking.py +772 -0
  34. roadkeep/provenance.py +789 -0
  35. roadkeep/queueing.py +752 -0
  36. roadkeep/ranking.py +139 -0
  37. roadkeep/referring.py +231 -0
  38. roadkeep/remaining.py +336 -0
  39. roadkeep/remedying.py +1989 -0
  40. roadkeep/rendering.py +1601 -0
  41. roadkeep/renumbering.py +503 -0
  42. roadkeep/repairing.py +295 -0
  43. roadkeep/reverting.py +144 -0
  44. roadkeep/scoping.py +708 -0
  45. roadkeep/screening.py +196 -0
  46. roadkeep/sections.py +4121 -0
  47. roadkeep/serving.py +2909 -0
  48. roadkeep/shipping.py +3993 -0
  49. roadkeep/showing.py +613 -0
  50. roadkeep/storing.py +224 -0
  51. roadkeep/verbs/__init__.py +26 -0
  52. roadkeep/verbs/adopting.py +974 -0
  53. roadkeep/verbs/authoring.py +566 -0
  54. roadkeep/verbs/declaring.py +335 -0
  55. roadkeep/verbs/linting.py +645 -0
  56. roadkeep/verbs/querying.py +2138 -0
  57. roadkeep/verbs/reading.py +307 -0
  58. roadkeep/verbs/refusing.py +146 -0
  59. roadkeep/verbs/sections.py +1433 -0
  60. roadkeep/verbs/shipping.py +819 -0
  61. roadkeep/weighing.py +380 -0
  62. roadkeep-0.2.0.dist-info/METADATA +453 -0
  63. roadkeep-0.2.0.dist-info/RECORD +67 -0
  64. roadkeep-0.2.0.dist-info/WHEEL +5 -0
  65. roadkeep-0.2.0.dist-info/entry_points.txt +2 -0
  66. roadkeep-0.2.0.dist-info/licenses/LICENSE +202 -0
  67. roadkeep-0.2.0.dist-info/top_level.txt +1 -0
roadkeep/describing.py ADDED
@@ -0,0 +1,568 @@
1
+ """What `roadkeep.toml` may declare, answered by the package that refuses the rest (RK1270).
2
+
3
+ The frozensets in :mod:`roadkeep.config` — `_TOP_KEYS`, `_LIMIT_KEYS`, `_MARKER_KEYS` and
4
+ twelve more — are the complete statement of what that file may say, and their only reader was
5
+ `_reject_unknown`. That is enough to refuse a typo and not enough to answer the question asked
6
+ *before* anything is typed: what may go here, and what does it mean.
7
+
8
+ Every consumer needing that answer had written it again. The scaffold `init` emits knows the
9
+ tables, `declare` knows `[files]`, and a completion list in an editor would know all of them —
10
+ each copy L6 broken from a different side, the shape of a project's own declaration decided
11
+ somewhere other than the package that reads it.
12
+
13
+ **Nothing here is a second statement of the shape.** The keys are read off those frozensets;
14
+ the sentence is harvested from the `#:` comment already above each one; the default is read
15
+ off a :meth:`~roadkeep.config.Config.default` project, which is the same code the parser runs;
16
+ and whether *this* project declared a key is read back off the file it wrote. The one thing
17
+ written here is :data:`WHERE` — where each key's value lands — and `tests/test_describing.py`
18
+ holds it total against those sets, so a key added tomorrow is a red rather than a silence.
19
+
20
+ What this is not is a schema for somebody else's validator. What is published is what **this
21
+ build** accepts, which is the distinction `ConfigError`'s skew clause exists for: a key nothing
22
+ declares is a typo, a key this build predates is an upgrade, and the file cannot tell them
23
+ apart. So the answer names the version that gave it, and a reader can conclude the second.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ import tomllib
30
+ from collections.abc import Mapping, Sequence
31
+ from dataclasses import dataclass
32
+ from pathlib import Path
33
+
34
+ from roadkeep.budgeting import Fixed, conversion
35
+ from roadkeep.config import (
36
+ CLAIM_HELD,
37
+ PROSE_ROLES,
38
+ ROLES,
39
+ Config,
40
+ Scope,
41
+ _BUDGET_KEYS,
42
+ _CLAIMS_KEYS,
43
+ _GRAMMAR_KEYS,
44
+ _HEADING_KEYS,
45
+ _IDS_KEYS,
46
+ _INSTALL_KEYS,
47
+ _LEDGER_KEYS,
48
+ _LIMIT_KEYS,
49
+ _MARKER_KEYS,
50
+ _REPORT_KEYS,
51
+ _READS_KEYS,
52
+ _REQUIREMENTS_KEYS,
53
+ _RULE_KEYS,
54
+ _SCOPE_KEYS,
55
+ _TOOLS_KEYS,
56
+ _TOP_KEYS,
57
+ )
58
+
59
+ __all__ = ["Key", "Shape", "TABLES", "WHERE", "notes", "shape"]
60
+
61
+ #: Every table this file may carry, and the closed set of names it accepts. The **prefix**
62
+ #: `_reject_unknown` is called with is the key, `""` being the top level, so a reader here and
63
+ #: the refusal one module over cannot come to disagree about what a table is called — and
64
+ #: `tests/test_describing.py` reads those call sites out of the source and holds this total
65
+ #: against them. A `<role>` or a `<path>` in a name is a table declared once per something the
66
+ #: project names, which is a fact about the address and not about the keys under it.
67
+ TABLES: Mapping[str, frozenset[str]] = {
68
+ "": _TOP_KEYS,
69
+ "files": frozenset(ROLES),
70
+ # Keyed by role like `[files]`, and refused by `_refs` rather than by `_reject_unknown`:
71
+ # it is a prose role only, under an outline only, and unique — three refusals a name set
72
+ # cannot make. The names it accepts are still the roles, which is what this answers.
73
+ "refs": frozenset(PROSE_ROLES),
74
+ "ids": _IDS_KEYS,
75
+ "headings": _HEADING_KEYS,
76
+ "install": _INSTALL_KEYS,
77
+ "markers": _MARKER_KEYS,
78
+ "ledger": _LEDGER_KEYS,
79
+ "limits": frozenset(_LIMIT_KEYS),
80
+ "rules.<role>": frozenset(_RULE_KEYS),
81
+ "non_goals": _SCOPE_KEYS,
82
+ "criteria": _SCOPE_KEYS,
83
+ "claims": _CLAIMS_KEYS,
84
+ "requirements": _REQUIREMENTS_KEYS,
85
+ "report": _REPORT_KEYS,
86
+ "budgets.<path>": _BUDGET_KEYS,
87
+ "grammar.<role>": _GRAMMAR_KEYS,
88
+ "tools": _TOOLS_KEYS,
89
+ "reads": _READS_KEYS,
90
+ }
91
+
92
+
93
+ def _is_table(name: str) -> bool:
94
+ """Whether a top-level key opens a table rather than carrying a value.
95
+
96
+ Asked of :data:`TABLES` and never listed a second time: a table a project declares once
97
+ per role or per path is spelled with the placeholder there, so `budgets` is found by the
98
+ prefix and `limits` by the name — one reading, and a table added above is covered by it.
99
+ """
100
+ return any(one == name or one.startswith(f"{name}.") for one in TABLES)
101
+
102
+
103
+ def _limit(key: str) -> object:
104
+ return getattr(Config.default().schema, _LIMIT_KEYS[key])
105
+
106
+
107
+ def _rule(key: str) -> object:
108
+ return getattr(Config.default().schema, _RULE_KEYS[key])
109
+
110
+
111
+ #: How each key's value is reached on a project that declared nothing — the one thing this
112
+ #: module states rather than derives, and the reason it is a lookup and not a sentence. Every
113
+ #: entry is a *call into the code the parser runs*, so a default changed in `Schema` or in
114
+ #: `config` changes what this prints without anybody editing it; `None` is a key with no
115
+ #: default at all, which is a different fact from a default of `false` and is said as such.
116
+ #:
117
+ #: Held total against :data:`TABLES` by a test, for `composing.SITES`' reason: a key nobody
118
+ #: accounted for reads exactly like a key that has no default.
119
+ WHERE: Mapping[tuple[str, str], object] = {
120
+ # The top level. Every table name among them is a table and carries no value of its own,
121
+ # which is why they answer `None` here and are listed under their own name below.
122
+ ("", "prefix"): lambda: Config.default().schema.prefixes[0],
123
+ ("", "ref_scheme"): lambda: Config.default().schema.ref_scheme,
124
+ ("", "id_sources"): lambda: (),
125
+ ("", "reserved_ids"): lambda: (),
126
+ ("", "priority"): lambda: (),
127
+ ("", "blocks"): lambda: (),
128
+ **{("", name): None for name in _TOP_KEYS if _is_table(name)},
129
+ # `[files]`, whose keys are the roles: no default beyond the three a scaffold writes, and
130
+ # `Config.default()` declares none at all — an absent role is absent and not empty.
131
+ **{("files", role): None for role in ROLES},
132
+ **{("refs", role): None for role in PROSE_ROLES},
133
+ ("ids", "pad"): lambda: Config.default().schema.id_pad,
134
+ ("ids", "suffix"): lambda: Config.default().schema.id_suffix,
135
+ ("headings", "word"): lambda: Config.default().schema.heading_word,
136
+ ("headings", "permanent"): lambda: False,
137
+ ("install", "pinned"): lambda: False,
138
+ ("install", "enforced"): lambda: False,
139
+ ("markers", "open"): lambda: Config.default().schema.markers,
140
+ ("markers", "shipped"): lambda: Config.default().schema.shipped_marker,
141
+ ("markers", "retired"): lambda: Config.default().schema.retired_marker,
142
+ ("markers", "deferred"): lambda: Config.default().schema.deferred_marker,
143
+ ("markers", "undesigned"): lambda: Config.default().schema.undesigned,
144
+ ("ledger", "marker"): lambda: Config.default().schema.ledger_marker,
145
+ ("ledger", "symptom"): lambda: Config.default().schema.ledger_symptom,
146
+ **{("limits", key): (lambda k=key: _limit(k)) for key in _LIMIT_KEYS},
147
+ **{("rules.<role>", key): (lambda k=key: _rule(k)) for key in _RULE_KEYS},
148
+ ("non_goals", "lead"): lambda: Scope().lead,
149
+ ("non_goals", "why"): lambda: Scope().why,
150
+ ("criteria", "lead"): lambda: Scope().lead,
151
+ ("criteria", "why"): lambda: Scope().why,
152
+ ("claims", "held"): lambda: CLAIM_HELD,
153
+ ("requirements", "declared"): lambda: Config.default().schema.requirements,
154
+ ("report", "upstream"): None,
155
+ ("budgets.<path>", "lines"): None,
156
+ ("budgets.<path>", "bytes"): None,
157
+ ("grammar.<role>", "extends"): lambda: "roadmap",
158
+ ("grammar.<role>", "markers"): lambda: (),
159
+ ("grammar.<role>", "drop"): lambda: (),
160
+ ("tools", "characters"): None,
161
+ ("tools", "session"): None,
162
+ ("reads", "brief"): None,
163
+ }
164
+
165
+
166
+ @dataclass(frozen=True, slots=True)
167
+ class Key:
168
+ """One key this file may carry, as a reader outside the package needs it."""
169
+
170
+ #: The table it lives under, `""` for the top level. `<role>` and `<path>` stand for the
171
+ #: name the project chooses, which is the address and never one of the keys.
172
+ table: str
173
+ name: str
174
+ #: The Python type of the default, or `""` where there is no default to read one off.
175
+ type: str
176
+ #: What this build uses when nobody declares it, already rendered — or `None`, which says
177
+ #: there is no default rather than that the default is empty.
178
+ default: str | None
179
+ #: Did *this* project declare it, read back off the file the project wrote.
180
+ declared: bool
181
+ #: What it wrote there, rendered the way the default is (RK1278) — `None` where nobody
182
+ #: declared it, which is a different fact from one declared as zero and is said as such.
183
+ #: A table's own row carries none: what a table *is* is the keys under it. `None` too
184
+ #: where **several** addresses declared it (RK1282) — one of them printed as the value is
185
+ #: a number a reader can act on and should not, and :attr:`at` is the fact instead.
186
+ set: str | None = None
187
+ #: How many addresses declared it (RK1282). 0 or 1 for an ordinary table, and above one
188
+ #: where a placeholder table was written per role or per path; which of them applies is
189
+ #: `budget --file`'s and `govern`'s, both of which take the address.
190
+ at: int = 0
191
+ #: The sentence the source already carries above the set this key belongs to, harvested
192
+ #: and never restated. `""` where the source is not readable or carries none.
193
+ note: str = ""
194
+
195
+ @property
196
+ def address(self) -> str:
197
+ return f"{self.table}.{self.name}" if self.table else self.name
198
+
199
+
200
+ @dataclass(frozen=True, slots=True)
201
+ class Shape:
202
+ """Every key, and the build that answered — which is half of what makes it usable."""
203
+
204
+ keys: tuple[Key, ...]
205
+ version: str
206
+ #: The file read back for :attr:`Key.declared`, or `None` on a project with no config.
207
+ source: str | None = None
208
+ #: What this build fixes from a corpus instead of accepting (RK1381). Empty where the
209
+ #: reading could not be taken — a project whose files this process cannot read — which is
210
+ #: the honest answer and not a figure stated without the corpus behind it.
211
+ fixed: tuple[Fixed, ...] = ()
212
+
213
+ def under(self, table: str) -> tuple[Key, ...]:
214
+ return tuple(one for one in self.keys if one.table == table)
215
+
216
+ def tables(self) -> tuple[str, ...]:
217
+ """Every table, in declaration order, so a listing groups the way the file does."""
218
+ return tuple(dict.fromkeys(one.table for one in self.keys))
219
+
220
+
221
+ #: A run of `#:` comment lines immediately above a name this module reads. Sphinx's own
222
+ #: spelling, which is what the source already uses — so nothing here asks an author to write a
223
+ #: second kind of comment for this reader's benefit.
224
+ _DOC = re.compile(
225
+ r"((?:^#:.*\n)+)^(?P<name>_?[A-Za-z][A-Za-z0-9_]*)\s*[:=]", re.MULTILINE
226
+ )
227
+
228
+ #: The same run above an **indented** name — a dataclass field (RK1314). Its own pattern and
229
+ #: not a relaxation of the one above, because the two answer different questions: a
230
+ #: module-level name is a key set and a field is the table itself, and the sentence a table
231
+ #: needs is the one written about it rather than about the shape it shares with another.
232
+ #: Harvested under a `.` prefix, so a field and a module-level name of the same spelling
233
+ #: cannot come to answer for each other.
234
+ _FIELD_DOC = re.compile(
235
+ r"((?:^[ \t]+#:.*\n)+)^[ \t]+(?P<name>_?[A-Za-z][A-Za-z0-9_]*)\s*[:=]", re.MULTILINE
236
+ )
237
+
238
+
239
+ def notes(source: Path | None = None) -> Mapping[str, str]:
240
+ """The `#:` sentence above each module-level name in `config.py`, by name (RK1270).
241
+
242
+ Harvested rather than restated, which is the whole of why the note is worth printing: the
243
+ sentence above `_MARKER_KEYS` is the one an author of that table already wrote, and a
244
+ second copy here would be the one that goes stale the first time somebody edits the real
245
+ one — which is the failure this task is an instance of, one file out.
246
+
247
+ Read off the text and not the AST: a `#:` run is a *comment*, so no tree carries it, and
248
+ the alternative is a tokenize pass to find what one regular expression anchored on the
249
+ assignment already answers. Empty where the source cannot be read — a build without it
250
+ answers the shape and not the prose, which is an absence and never an invention.
251
+ """
252
+ from roadkeep import config as module # noqa: PLC0415 - RK260
253
+
254
+ path = source or Path(module.__file__ or "")
255
+ try:
256
+ text = path.read_text(encoding="utf-8")
257
+ except OSError:
258
+ return {}
259
+ out: dict[str, str] = {}
260
+ for match in _DOC.finditer(text):
261
+ out[match.group("name")] = _run(match.group(1))
262
+ # And the fields (RK1314), under a `.` prefix. A second pass rather than a looser pattern,
263
+ # so the two name spaces stay apart: a field and a module-level name may share a spelling,
264
+ # and one answering for the other is the defect this task is an instance of. A spelling two
265
+ # fields carry is dropped — which of them a table meant is not a question this may guess,
266
+ # and an absent note is an absence where a picked one would be an invention.
267
+ seen: dict[str, str] = {}
268
+ for match in _FIELD_DOC.finditer(text):
269
+ name = match.group("name")
270
+ seen[name] = "" if name in seen else _run(match.group(1))
271
+ out.update({f".{name}": note for name, note in seen.items() if note})
272
+ return out
273
+
274
+
275
+ def _run(comment: str) -> str:
276
+ """One `#:` run as a single line of prose, its markers and its indentation stripped."""
277
+ lines = [line.strip().removeprefix("#:").strip() for line in comment.splitlines()]
278
+ return " ".join(part for part in lines if part)
279
+
280
+
281
+ #: Which name's `#:` sentence describes each table. The frozenset itself wherever one exists,
282
+ #: because that is where the author wrote it; `_TOP_KEYS` carries none and says so.
283
+ #:
284
+ #: **Per table and not per key set** (RK1314). Two tables share `_SCOPE_KEYS` — one value
285
+ #: reader is right and RK1265 argued it, `[criteria]` being the same two numbers about the
286
+ #: positive twin — and the sentence rode across with the shape: `config` printed, under
287
+ #: `[criteria]`, *"`[non_goals]` — the two fields the roadmap's other bullet has (RK70)"*.
288
+ #: A row whose words describe a different table is worse than a row with none: nothing in it
289
+ #: disagrees with itself, the two carry the same two key names, and a reader has no way to
290
+ #: tell it from a correct row — on the one surface whose whole claim is that it is not a
291
+ #: second copy of a rule. So a table may name a **field** (`.criteria`), which is where that
292
+ #: table is documented as itself rather than as the shape it shares.
293
+ _DESCRIBED = {
294
+ "files": "ROLES",
295
+ "ids": "_IDS_KEYS",
296
+ "headings": "_HEADING_KEYS",
297
+ "install": "_INSTALL_KEYS",
298
+ "markers": "_MARKER_KEYS",
299
+ "ledger": "_LEDGER_KEYS",
300
+ "limits": "_LIMIT_KEYS",
301
+ "rules.<role>": "_RULE_KEYS",
302
+ "non_goals": "_SCOPE_KEYS",
303
+ "criteria": ".criteria",
304
+ "claims": "_CLAIMS_KEYS",
305
+ "report": "_REPORT_KEYS",
306
+ "budgets.<path>": "_BUDGET_KEYS",
307
+ "grammar.<role>": "_GRAMMAR_KEYS",
308
+ "tools": "_TOOLS_KEYS",
309
+ "reads": "_READS_KEYS",
310
+ }
311
+
312
+
313
+ #: A sentence's end, where the stop is not inside a parenthesised citation or a version. The
314
+ #: harvested prose is this repository's own, so `(RK106).` and `0.1.1` are the two shapes that
315
+ #: are not ends, and both are excluded by requiring whitespace after the stop.
316
+ _STOP = re.compile(r"(?<=[.!?])\s")
317
+
318
+
319
+ def _opening(note: str) -> str:
320
+ """The first sentence of a harvested run — what a listing prints (RK1270)."""
321
+ parts = _STOP.split(note, maxsplit=1)
322
+ return parts[0].strip()
323
+
324
+
325
+ def _how(one: Key) -> str:
326
+ """What a listing says about a key this project declared, or did not (RK1278, RK1282).
327
+
328
+ Three answers and not two, because a placeholder table is declared per address: nothing,
329
+ the value where exactly one address wrote it, and the count where several did. The last
330
+ is the one this exists for — printing one of them looked exactly like a key with one
331
+ value, and `budget --file` and `govern` are the reads that take the address.
332
+ """
333
+ if not one.declared:
334
+ return "—"
335
+ if one.at > 1:
336
+ return f"declared at {one.at} addresses"
337
+ return "declared" if one.set is None else f"declared {one.set}"
338
+
339
+
340
+ def _rendered(value: object) -> str:
341
+ """A default as the file would spell it, so what is printed is what may be typed."""
342
+ if isinstance(value, bool):
343
+ return "true" if value else "false"
344
+ if isinstance(value, str):
345
+ return f'"{value}"'
346
+ if isinstance(value, tuple | list):
347
+ return "[" + ", ".join(_rendered(one) for one in value) + "]"
348
+ return str(value)
349
+
350
+
351
+ def _named(value: object) -> str:
352
+ """The TOML type of a default, named as that format names it and not as Python does."""
353
+ if isinstance(value, bool):
354
+ return "boolean"
355
+ if isinstance(value, str):
356
+ return "string"
357
+ if isinstance(value, int):
358
+ return "integer"
359
+ if isinstance(value, tuple | list):
360
+ return "array"
361
+ return "table"
362
+
363
+
364
+ def _declared(source: Path | None) -> Mapping[tuple[str, str], tuple[object, ...]]:
365
+ """Every `(table, key)` the project wrote, and **every value it wrote there** (RK1278).
366
+
367
+ The file and not the parsed :class:`~roadkeep.config.Config`, and the difference is the
368
+ question: a config carries the *effective* value, where a limit left out and a limit
369
+ declared at the default are the same number and a different fact about the project.
370
+
371
+ The value comes with it because the same parse already had it, and printing the default
372
+ beside a key somebody set is two true statements arranged to read as one false one — met
373
+ by the reader hovering the key they are about to change, which is the moment the value
374
+ matters and the default does not.
375
+
376
+ A **tuple** and not one value (RK1282). A table spelled with a placeholder is declared once
377
+ per something the project names, so one published address can carry several — this project
378
+ budgets two files — and reporting the last of them looked exactly like a key with one
379
+ value. The count is the fact; which of the several applies is `budget --file`'s and
380
+ `govern`'s, both of which take the address.
381
+
382
+ What comes back is TOML's own scalar, string or list, rendered by the same writer the
383
+ default is: resolving it into what the schema makes of it would be this module re-deciding
384
+ what the parser decided, which is the second reading it exists to make unnecessary.
385
+ """
386
+ if source is None:
387
+ return {}
388
+ try:
389
+ raw = tomllib.loads(source.read_text(encoding="utf-8"))
390
+ except (OSError, tomllib.TOMLDecodeError):
391
+ return {}
392
+ if "tool" in raw and "roadkeep" in raw.get("tool", {}):
393
+ raw = raw["tool"]["roadkeep"]
394
+ out: dict[tuple[str, str], list[object]] = {}
395
+ for name, value in raw.items():
396
+ # A table's own row carries no value of its own: what it *is* is the keys under it,
397
+ # and a rendered dict there would be the whole subtree printed as a default.
398
+ out.setdefault(("", name), []).append(None if isinstance(value, Mapping) else value)
399
+ if isinstance(value, Mapping):
400
+ for address, each in _under(name, value):
401
+ out.setdefault(address, []).append(each)
402
+ return {key: tuple(values) for key, values in out.items()}
403
+
404
+
405
+ def _under(
406
+ name: str, value: Mapping[str, object]
407
+ ) -> tuple[tuple[tuple[str, str], object], ...]:
408
+ """One table's declared keys and their values, descending the level a placeholder adds.
409
+
410
+ Pairs and not a mapping (RK1282): under `budgets.<path>` or `limits.<role>` the address is
411
+ one the project chooses, so two of them can write the same published key — and a mapping
412
+ here would keep the last, which is the value that looked like the answer.
413
+ """
414
+ generic = next((one for one in TABLES if one.startswith(f"{name}.")), None)
415
+ under = generic or name
416
+ known = TABLES.get(under, frozenset())
417
+ out: list[tuple[tuple[str, str], object]] = []
418
+ for key, inner in value.items():
419
+ # A sub-table under a name this table has no key for is the **same** table declared
420
+ # once per something the project chose — `[limits.changelog]`, `[budgets."agents.md"]`
421
+ # — so its keys land on the published address rather than on the name it was spelled
422
+ # with, which is not a key and never appears in the shape.
423
+ if isinstance(inner, Mapping) and key not in known:
424
+ out.extend(((under, each), one) for each, one in inner.items())
425
+ continue
426
+ out.append(((under, key), inner))
427
+ return tuple(out)
428
+
429
+
430
+ def shape(config: Config, table: str | None = None) -> Shape:
431
+ """Every key this build accepts, with what this project declared (RK1270).
432
+
433
+ ``table`` narrows to one, spelled as :data:`TABLES` spells it — `""` for the top level,
434
+ and `rules.<role>` for a table a project declares once per role. A name nothing declares
435
+ is refused rather than answered empty, that answer being read as evidence.
436
+ """
437
+ from roadkeep import __version__ # noqa: PLC0415 - RK260
438
+
439
+ if table is not None and table not in TABLES:
440
+ known = ", ".join(repr(one) for one in TABLES)
441
+ raise KeyError(
442
+ f"no table {table!r} in roadkeep.toml: this build accepts {known} — a name it "
443
+ f"does not is a typo here and never a key this project has yet to declare"
444
+ )
445
+ sentences = notes()
446
+ written = _declared(config.source)
447
+ out: list[Key] = []
448
+ for name, keys in TABLES.items():
449
+ if table is not None and name != table:
450
+ continue
451
+ note = sentences.get(_DESCRIBED.get(name, ""), "")
452
+ for key in sorted(keys):
453
+ reader = WHERE[(name, key)]
454
+ value = None if reader is None else reader()
455
+ # What the project wrote, beside what this build would use (RK1278): the same
456
+ # parse that answers *whether* a key is declared already has *what* — and
457
+ # printing the default beside a key somebody set is two true statements arranged
458
+ # to read as one false one.
459
+ declared = written.get((name, key), ())
460
+ # One value or a count, never one of several (RK1282): a placeholder table is
461
+ # declared per address, so the number is the answer only where there is one.
462
+ only = declared[0] if len(declared) == 1 else None
463
+ out.append(
464
+ Key(
465
+ table=name,
466
+ name=key,
467
+ type="" if value is None else _named(value),
468
+ default=None if value is None else _rendered(value),
469
+ declared=bool(declared),
470
+ set=None if only is None else _rendered(only),
471
+ at=len(declared),
472
+ note=note,
473
+ )
474
+ )
475
+ return Shape(
476
+ keys=tuple(out),
477
+ version=__version__,
478
+ source=None if config.source is None else config.relative(config.source),
479
+ # Only on the whole listing (RK1381): `--table <name>` narrows to one table, and a
480
+ # figure that is under no table at all would arrive as an answer to a narrower
481
+ # question than the one asked.
482
+ fixed=() if table is not None else _fixed(config),
483
+ )
484
+
485
+
486
+ def _fixed(config: Config) -> tuple[Fixed, ...]:
487
+ """Every number this build fixes from a corpus, with the reading behind it (RK1381).
488
+
489
+ One today, and a tuple because the shape is what the row is for: a second such figure is a
490
+ row here rather than a second command, exactly as a governed key is a row in the listing
491
+ above rather than a verb of its own.
492
+
493
+ Swallows the read's own refusal, which is `_section_of`'s rule one file over: a caller
494
+ asked *what may I declare*, and a project whose prose this process cannot read still has
495
+ every answer above — so an unreadable corpus answers with no row and never with a figure
496
+ stated as though a reading had been taken.
497
+ """
498
+ try:
499
+ return (conversion(config),)
500
+ except (OSError, KeyError, ValueError):
501
+ return ()
502
+
503
+
504
+ def stated(found: Shape) -> str:
505
+ """The shape as a reader is told it: one row per key, grouped by the table it is under."""
506
+ where = found.source or "nothing (this project declares no roadkeep.toml)"
507
+ rows = [
508
+ f"{len(found.keys)} key(s) this build accepts, read against {where}",
509
+ f" build roadkeep {found.version} — what is listed is what *this* copy takes, "
510
+ f"which is how a key it predates is told from a typo",
511
+ ]
512
+ for name in found.tables():
513
+ under = found.under(name)
514
+ rows.append(f"[{name or 'top level'}]")
515
+ # The first sentence and not the run, which is the split between the two answers: a
516
+ # listing is read by somebody deciding what to declare, and the whole paragraph — 90
517
+ # words on `[files]` — is what `--json` carries for the completion list RK1271 hovers.
518
+ if under and under[0].note:
519
+ rows.append(f" {_opening(under[0].note)}")
520
+ for one in under:
521
+ default = "no default" if one.default is None else f"default {one.default}"
522
+ spelled = f"{one.type}, " if one.type else ""
523
+ # What the project set, where it set one (RK1278): the number in use is the one a
524
+ # reader hovering the key they are about to change is asking about, and the
525
+ # default is the fact that stops mattering the moment there is a value.
526
+ mark = _how(one)
527
+ rows.append(f" {one.name:<12} {spelled}{default} ({mark})")
528
+ if found.fixed:
529
+ # Last, and under its own heading (RK1381): the listing above is what a project may
530
+ # declare, and this is the boundary of that question rather than another table in it.
531
+ rows.append("[fixed by this build, and not a project's to declare]")
532
+ rows += [one.stated() for one in found.fixed]
533
+ return "\n".join(rows)
534
+
535
+
536
+ def payload(found: Shape) -> dict[str, object]:
537
+ """The same answer as data — what a completion list reads (RK1270, RK1271)."""
538
+ return {
539
+ "version": found.version,
540
+ "source": found.source,
541
+ # What this build fixes instead of accepting (RK1381). `[]` and never omitted, for the
542
+ # reason every other absence here is published: a consumer reading a missing key cannot
543
+ # tell "nothing is fixed" from "this build is older than the answer".
544
+ "fixed": [one.payload() for one in found.fixed],
545
+ "keys": [
546
+ {
547
+ "table": one.table,
548
+ "key": one.name,
549
+ "address": one.address,
550
+ "type": one.type,
551
+ "default": one.default,
552
+ "declared": one.declared,
553
+ # And what was declared (RK1278) — `null` where nobody did, which is a
554
+ # different fact from a value of zero and is said as such.
555
+ "set": one.set,
556
+ # And how many addresses wrote one (RK1282), which is the fact where the
557
+ # value is not: above one, `set` is null and this is why.
558
+ "addresses": one.at,
559
+ "note": one.note,
560
+ }
561
+ for one in found.keys
562
+ ],
563
+ }
564
+
565
+
566
+ def tables(names: Sequence[str] = ()) -> tuple[str, ...]:
567
+ """The table names, for a caller that wants the addresses and not the keys."""
568
+ return tuple(names) or tuple(TABLES)