Coverage for packages/workshop/src/livery/workshop/_contract_keys.py: 99%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""Which keys a contract may hold, who owns each, and the judge that refuses the rest.
2
3Every key of a ``workshop.toml`` is declared by its owner: the base
4declares its own in ``contract.toml`` beside this module, the tool
5store declares the ``[toolroom]`` table in the fragment it ships
6([livery.toolroom.store.SCHEMA_FRAGMENT][]), and an extension declares
7the keys it reads under ``[contract.<contract>.<table>]`` in its
8``extension.toml``, read without importing the extension. The base's
9file declares the keys of ``extension.toml`` itself as well, the
10``extension`` contract.
11
12[livery.workshop._contract.load_contract][] judges every contract it
13reads against the JSON Schema the declarations compose
14([livery.workshop._schema.composed][]): a key no owner declares, a key
15whose owner the root's ``[workspace] extensions`` does not list, a value
16of the wrong type and a value outside its allowed set each refuse,
17naming the file, the key, what the table takes, and the nearest match.
18
19A path is dotted. ``*`` stands for any one name in a table whose
20keys are the user's (``toolroom.modes.*``); ``[]`` stands for the
21entries of a list (``ci.schedule[].every``). A key the user names may
22hold a dot itself (``".vscode/settings.json"``): the judge walks a
23contract's keys one table at a time, so such a key is one name.
24"""
25
26from __future__ import annotations(empty)
27
28import functools(empty)
29from dataclasses import dataclass, replace(empty)
30from pathlib import Path(empty)
31from typing import Any, Literal, get_args(empty)
32
33from livery.footman import fail(empty)
34
35#: The kinds of contract: the workspace's at the root, a package's in
36#: its directory, and an extension's declaration file.
37ContractKind = Literal["root", "package", "extension"](empty)
38
39#: The value types a key may take. ``strs`` is a list of strings;
40#: ``list`` is a list whose entries the ``[]`` path declares; ``table``
41#: is a table whose keys are declared beneath it; ``any`` is a value
42#: the reader judges itself, nothing beneath it declared here.
43Type = Literal["str", "int", "number", "bool", "strs", "list", "table", "any"](empty)
44
45#: The value types, as a declaration file spells them.
46TYPES: tuple[str, ...] = get_args(Type)(empty)
47
48#: The base extension's name, always mounted.
49BASE = "livery.workshop"(empty)
50
51#: The owner of the ``[toolroom]`` table: the tool store, a dependency
52#: of the base whose schema fragment every workspace composes with the
53#: base's own keys, whatever its root lists.
54TOOLROOM = "livery.toolroom.store"(empty)
55
56#: The owners every workspace composes, whatever its root lists.
57ALWAYS: tuple[str, ...] = (BASE, TOOLROOM)(empty)
58
59
60@dataclass(frozen=True)(empty)
61class Declared:(empty)
62 """One key a contract may hold.
63
64 Attributes:
65 contract: The contract it belongs in, ``root``, ``package`` or
66 ``extension``.
67 path: The dotted path, with ``*`` and ``[]`` as above.
68 types: The value types it takes, any one of them.
69 values: The values it takes, when it takes only some.
70 doc: One line saying what the key changes.
71 """
72
73 contract: ContractKind(empty)
74 path: str(empty)
75 types: tuple[Type, ...](empty)
76 values: tuple[str, ...] = ()(empty)
77 doc: str = ""(empty)
78
79
80#: The base's declaration of every key it reads, beside this module.
81BASE_FILE = Path(__file__).with_name("contract.toml")(empty)
82
83
84def base_contract() -> dict[str, Any]:(empty)
85 """The base's contract file, `BASE_FILE`, parsed once per process.
86
87 The file ships with the workshop and does not change while it runs,
88 so its readers share one parse: the base's keys, phases, queries,
89 tools and templates. The parse is kept by the file's path, so a
90 `BASE_FILE` that names another file is read afresh. A reader
91 copies what it changes: the parse it gets is the one every reader
92 gets.
93 """
94 return _parsed(BASE_FILE)
95
96
97@functools.cache(empty)
98def _parsed(path: Path) -> dict[str, Any]:(empty)
99 """The TOML file at *path*, parsed once per process."""
100 import tomllib
101
102 return tomllib.loads(path.read_text("utf-8"))
103
104
105#: The top-level tables of ``extension.toml`` that ``[for.<target>]``
106#: does not take again: the extension's identity, the targets table
107#: itself, and the contract keys it owns, which no target changes; the
108#: templates it declares, each of which names the extensions it needs in
109#: its own ``extensions``; and the environment variables it needs, which
110#: do not depend on what else is listed.
111_UNMIRRORED = ("extension", "for", "contract", "templates", "env")(empty)
112
113
114@functools.cache(empty)
115def base_keys() -> tuple[Declared, ...]:(empty)
116 """The base's keys, read from its ``contract.toml``, in every contract.
117
118 ``[for.<target>]`` in an ``extension.toml`` takes every table of
119 the file's top level again but ``[extension]``, ``[for]``,
120 ``[contract]``, ``[templates]`` and ``[env]``, so the file declares
121 each key once and they are repeated here under ``for.*``.
122
123 Raises:
124 DeclarationError: when the file declares a key off the shape an
125 extension's ``[contract]`` table has.
126 """
127 from livery.workshop._declaration import contract_keys_of
128
129 found = contract_keys_of(
130 base_contract(), BASE_FILE, contracts=("root", "package", "extension")
131 )
132 return found + _mirrored(found)
133
134
135@functools.cache(empty)
136def toolroom_keys() -> tuple[Declared, ...]:(empty)
137 """The ``[toolroom]`` keys the tool store's fragment declares, in every contract.
138
139 ``extension.toml`` takes them under ``for.*`` again, as it takes
140 the base's: a ``[for.<target>]`` table's ``[toolroom] requires``
141 names the tools required while that table applies.
142
143 Raises:
144 DeclarationError: when the fragment declares a key off the shape
145 an extension's ``[contract]`` table has.
146 """
147 import tomllib
148
149 from livery.toolroom.store import SCHEMA_FRAGMENT
150 from livery.workshop._declaration import contract_keys_of
151
152 found = contract_keys_of(
153 tomllib.loads(SCHEMA_FRAGMENT.read_text("utf-8")),
154 SCHEMA_FRAGMENT,
155 contracts=("root", "package", "extension"),
156 )
157 return found + _mirrored(found)
158
159
160def _mirrored(found: tuple[Declared, ...]) -> tuple[Declared, ...]:(empty)
161 """*found*'s ``extension.toml`` keys again under ``for.*``, their docs unchanged.
162
163 Every key of the file's top-level tables but those of
164 ``[extension]``, ``[for]``, ``[contract]``, ``[templates]`` and
165 ``[env]``, which no target changes.
166 """
167 return tuple(
168 replace(item, path=f"for.*.{item.path}")
169 for item in found
170 if item.contract == "extension" and item.path.split(".")[0] not in _UNMIRRORED
171 )
172
173
174@functools.cache(empty)
175def extension_keys() -> tuple[Declared, ...]:(empty)
176 """The keys of ``extension.toml``: the base's and the tool store's alone."""
177 return tuple(
178 item
179 for item in (*base_keys(), *toolroom_keys())
180 if item.contract == "extension"
181 )
182
183
184@dataclass(frozen=True)(empty)
185class _Owned:(empty)
186 declared: Declared(empty)
187 owner: str(empty)
188
189
190@functools.cache(empty)
191def declarations() -> dict[tuple[ContractKind, str], _Owned]:(empty)
192 """Every installed owner's declarations, by contract and path.
193
194 The base's come from this module and the readers it names, the
195 tool store's from its fragment; every
196 extension's from the ``[contract]`` tables of its declaration file,
197 installed or not listed alike, so a key of an unlisted extension is
198 named as that extension's. Two owners declaring one path refuse,
199 naming both.
200 """
201 from livery.footman import installed_entry_points
202 from livery.workshop._declaration import contract_keys
203
204 found: dict[tuple[ContractKind, str], _Owned] = {}
205
206 def take(owner: str, items: tuple[Declared, ...]) -> None:
207 for item in items:
208 key = (item.contract, item.path)
209 if key in found and found[key].owner != owner:
210 fail(
211 f"the {item.contract} contract key {item.path} is declared by"
212 f" both {found[key].owner} and {owner}; one owner declares a key"
213 )
214 found[key] = _Owned(item, owner)
215
216 take(BASE, base_keys())
217 take(TOOLROOM, toolroom_keys())
218 for entry in installed_entry_points("workshop.extensions"):
219 take(entry.name, contract_keys(entry.value))
220 return found
221
222
223def shown(path: tuple[str, ...]) -> str:(empty)
224 """*path* dotted, a name holding a dot quoted, as a reader writes it."""
225 return ".".join(f'"{part}"' if "." in part else part for part in path)
226
227
228def judge((empty)
229 data: dict[str, Any],
230 *,
231 contract: ContractKind,
232 where: str,
233 listed: frozenset[str] | None,
234) -> list[str]:
235 """The refusals *data* earns as a *contract*; empty when it is sound.
236
237 Judged against the contract's composed schema
238 ([livery.workshop._schema.composed][]), the one `fm sync` writes
239 for the editor, in the judge's words
240 ([livery.workshop._schema.problems][]).
241
242 A set that holds an extension no installed distribution declares
243 is judged as ``None``: what that extension requires is unknown
244 until it is installed, so no installed owner's key can be called
245 unlisted. A key no installed owner declares still refuses. The
246 mount names the extension, and `fm sync` installs it, or refuses
247 naming it, before it renders anything.
248
249 Args:
250 data: The parsed contract.
251 contract: Which contract it is.
252 where: The file, for the caller's message.
253 listed: The extensions the contract's lists and what they
254 require hold, the base among them; ``None`` takes every
255 installed owner as listed.
256
257 Returns:
258 One line per problem, in the contract's order.
259 """
260 from livery.workshop._schema import composed, problems
261
262 del where
263 if listed is not None and _not_installed(listed):
264 listed = None
265 return problems(composed(contract, listed), data)
266
267
268def _not_installed(listed: frozenset[str]) -> bool:(empty)
269 """Whether *listed* holds an extension no installed distribution declares."""
270 from livery.workshop._extensions import installed_declaration
271
272 return any(
273 name not in ALWAYS and installed_declaration(name) is None for name in listed
274 )
275
276
277def listed_extensions(root_data: dict[str, Any]) -> frozenset[str]:(empty)
278 """The extensions a root contract lists, by name, the base always among them.
279
280 An entry is read as [livery.workshop._extensions.listing][] reads
281 it: its name, whatever else the entry carries.
282 """
283 names = {BASE}
284 workspace = root_data.get("workspace")
285 extensions = workspace.get("extensions", []) if isinstance(workspace, dict) else [] # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
286 from livery.workshop._extensions import listing
287
288 for entry in extensions if isinstance(extensions, list) else []: # pyright: ignore[reportUnknownVariableType]
289 if isinstance(entry, str):
290 names.add(listing(entry).name)
291 elif isinstance(entry, dict) and isinstance(entry.get("name"), str): # pyright: ignore[reportUnknownMemberType]291 ↛ 288line 291 didn't jump to line 288 because the condition on line 291 was always true
292 names.add(listing(entry["name"]).name) # pyright: ignore[reportUnknownArgumentType]
293 return frozenset(names)