Coverage for packages/workshop/src/livery/workshop/_contract.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"""Read a workshop contract; its keys are kebab-case, and the read enforces it.
2
3``workshop.toml`` is the workspace contract at the root and a
4package's contract in its directory. Every reader parses one through
5[livery.workshop._contract.load_contract][], or
6[livery.workshop._contract.parse_contract][] for text already in
7hand, and a key spelled with an underscore refuses at any depth,
8naming the key, its kebab-case spelling, and the file to fix. There
9is no rewrite: a wrong spelling is one edit where the refusal points.
10"""
11
12from __future__ import annotations(empty)
13
14import json(empty)
15import tomllib(empty)
16from collections.abc import Generator(empty)
17from contextlib import contextmanager(empty)
18from pathlib import Path(empty)
19from typing import Any(empty)
20
21from livery.footman import fail(empty)
22
23
24def toml_string(value: str) -> str:(empty)
25 """*value* as a TOML basic string, quotes and escapes included.
26
27 A Windows path carries backslashes, which a basic string must
28 escape; JSON's string syntax is the subset of TOML's that a
29 path or a URL needs, so the JSON encoder is the writer.
30 """
31 return json.dumps(value)
32
33
34#: The contract file's name, at the root and in each package directory.
35CONTRACT = "workshop.toml"(empty)
36
37
38def kebab(key: str) -> str:(empty)
39 """*key* with every underscore replaced by a hyphen."""
40 return key.replace("_", "-")
41
42
43def underscore_keys(table: dict[str, Any], *, prefix: str = "") -> list[str]:(empty)
44 """The dotted paths of every key under *table* spelled with an underscore.
45
46 Walks nested tables and arrays of tables, so ``[[depends]]``
47 entries and inline tables are judged like the top level.
48 """
49 found: list[str] = []
50 for key, value in table.items():
51 path = f"{prefix}{key}"
52 if "_" in key:
53 found.append(path)
54 if isinstance(value, dict):
55 found += underscore_keys(value, prefix=f"{path}.")
56 elif isinstance(value, list):
57 for item in value:
58 if isinstance(item, dict):
59 found += underscore_keys(item, prefix=f"{path}.")
60 return found
61
62
63def parse_contract(text: str, *, where: str) -> dict[str, Any]:(empty)
64 """Parse contract *text*; refuse a key spelled with an underscore.
65
66 Args:
67 text: The contract's TOML.
68 where: How a refusal names the contract: its path, or the git
69 ref it was read at.
70
71 Returns:
72 The parsed tables.
73
74 Raises:
75 Failed: when *text* is not TOML, or a key is spelled with an
76 underscore, naming *where*.
77 """
78 try:
79 data = tomllib.loads(text)
80 except tomllib.TOMLDecodeError as error:
81 fail(f"{where}: not valid TOML: {error}")
82 wrong = underscore_keys(data)
83 if wrong:
84 listed = ", ".join(
85 f"{key} (spell it {kebab(key.split('.')[-1])})" for key in wrong
86 )
87 fail(
88 f"{where}: contract keys are kebab-case; found {listed}."
89 f" Rename each key in {where}."
90 )
91 return data
92
93
94def spelled_list(names: tuple[str, ...] | list[str]) -> str:(empty)
95 """*names* as a contract spells a list of them: ``["cmake", "conan"]``."""
96 return "[" + ", ".join(toml_string(name) for name in names) + "]"
97
98
99#: The contracts this process loaded and judged, by path and the stamps
100#: of every file the judgement read: one parse serves the process, and a
101#: contract edited since is parsed and judged again. Package discovery
102#: loads every member's contract on each call, and a sync discovers
103#: many times.
104_CONTRACTS: dict[tuple[Any, ...], dict[str, Any]] = {}(empty)
105
106
107def _stamp(path: Path) -> tuple[int, int] | None:(empty)
108 """A file's modification time and size, or None when it is not there."""
109 try:
110 found = path.stat()
111 except OSError:
112 return None
113 return (found.st_mtime_ns, found.st_size)
114
115
116def _contract_key(path: Path, workspace: Path | None) -> tuple[Any, ...]:(empty)
117 """What a judgement of *path* depends on: its stamp and its workspace's.
118
119 A package's contract is judged against the root's list, so the
120 root's stamp is part of the key; a root's against every package's
121 set, so theirs are.
122 """
123 if workspace is not None:
124 return (str(path), _stamp(path), _stamp(workspace / CONTRACT))
125 return (
126 str(path),
127 _stamp(path),
128 tuple((str(member), _stamp(member)) for member in contract_paths(path.parent)),
129 )
130
131
132def forget_contracts() -> None:(empty)
133 """Drop every contract this process loaded, so the next load parses again."""
134 _CONTRACTS.clear()
135
136
137#: How many `unjudged` blocks are open in this process; while one is,
138#: a load parses and judges no key.
139_UNJUDGED: list[int] = [0](empty)
140
141
142@contextmanager(empty)
143def unjudged() -> Generator[None]:(empty)
144 """Load contracts inside the block without judging their keys.
145
146 The sync opens it while it installs the extensions the lists name
147 and no installed distribution declares yet: a key of such an
148 extension has no declaration to be judged by until the install, and
149 the judgement would refuse the very sync that installs it. A load
150 inside the block still refuses a file that is not TOML and a key
151 spelled with an underscore, and keeps nothing for a later load,
152 which judges as usual.
153 """
154 _UNJUDGED[0] += 1
155 try:
156 yield
157 finally:
158 _UNJUDGED[0] -= 1
159
160
161def load_contract(path: Path) -> dict[str, Any]:(empty)
162 """Parse the contract at *path* and judge its keys; a refusal names the file.
163
164 A contract is parsed and judged once per process; a later load
165 answers from the first until the file, or one the judgement read,
166 changes. The caller gets its own copy.
167
168 A contract under ``packages/<name>/`` or ``packages/<group>/<name>/``
169 is a package's, judged against the root's set, the extensions its
170 workspace's root contract lists and those they require, and the
171 package's own set, the extensions it lists and those they require.
172 So a package holds the keys of what the root lists and of what it
173 lists itself, and no other package's. Any other is a root contract,
174 judged against the workspace's installed set
175 ([livery.workshop._extensions.installed_set][]): the root's set and
176 every package's. Every problem is listed in one refusal
177 ([livery.workshop._contract_keys.judge][]). Inside an `unjudged`
178 block a load parses alone and keeps nothing.
179 """
180 import copy
181
182 from livery.workshop._composition import closure
183 from livery.workshop._contract_keys import judge, listed_extensions
184 from livery.workshop._extensions import (
185 installed_declaration,
186 installed_set,
187 listing,
188 )
189
190 workspace = _package_workspace(path)
191 if _UNJUDGED[0]:
192 return parse_contract(path.read_text("utf-8"), where=str(path))
193 key = _contract_key(path, workspace)
194 held = _CONTRACTS.get(key)
195 if held is not None:
196 return copy.deepcopy(held)
197 data = parse_contract(path.read_text("utf-8"), where=str(path))
198 if workspace is not None:
199 root = workspace / CONTRACT
200 listed = None
201 if root.is_file():
202 own = data.get("extensions")
203 entries = [str(name) for name in own] if isinstance(own, list) else []
204 names = [
205 *listed_extensions(_root_tables(root)),
206 *(listing(entry).name for entry in entries),
207 ]
208 listed = frozenset(closure(names, installed_declaration))
209 problems = judge(data, contract="package", where=str(path), listed=listed)
210 else:
211 listed = listed_extensions(data) | set(installed_set(path.parent))
212 problems = judge(data, contract="root", where=str(path), listed=listed)
213 if problems:
214 fail(f"{path}:\n" + "\n".join(f" {line}" for line in problems))
215 _CONTRACTS[key] = copy.deepcopy(data)
216 return data
217
218
219def read_contract(directory: Path) -> dict[str, Any]:(empty)
220 """The contract in *directory*, its keys judged: the workspace's or a package's.
221
222 *directory* is the workspace root or a package's directory, and the
223 contract is its ``workshop.toml``. A package's contract is judged
224 against the extensions the workspace lists, the root's against its
225 own list, so a key of an extension the workspace does not list
226 refuses naming the extension.
227
228 Raises:
229 Failed: when the contract holds a key no listed extension and
230 not the workshop declares, or a value of the wrong type,
231 naming the file and every such key.
232 FileNotFoundError: when *directory* holds no contract.
233 """
234 return load_contract(directory / CONTRACT)
235
236
237def _package_workspace(path: Path) -> Path | None:(empty)
238 """The workspace root of the package contract at *path*; None for a root's.
239
240 A package sits at ``packages/<name>/`` or, in a group directory, at
241 ``packages/<group>/<name>/``; a group has no contract of its own.
242 """
243 if path.parent.parent.name == "packages":
244 return path.parent.parent.parent
245 group = path.parent.parent
246 if group.parent.name == "packages" and not (group / CONTRACT).is_file():
247 return group.parent.parent
248 return None
249
250
251def _root_tables(path: Path) -> dict[str, Any]:(empty)
252 """The root contract's tables, unjudged: a package's read needs its list."""
253 try:
254 return tomllib.loads(path.read_text("utf-8"))
255 except (OSError, tomllib.TOMLDecodeError):
256 return {}
257
258
259def contract_paths(root: Path) -> list[Path]:(empty)
260 """The root contract and every member's, the ones that exist."""
261 paths = [root / CONTRACT]
262 packages = root / "packages"
263 if packages.is_dir():
264 found: list[Path] = []
265 for directory in (p for p in packages.iterdir() if p.is_dir()):
266 if (directory / CONTRACT).is_file():
267 found.append(directory / CONTRACT)
268 else:
269 # A group directory: its packages are one level down.
270 found += (p / CONTRACT for p in directory.iterdir() if p.is_dir())
271 paths += sorted(found)
272 return [path for path in paths if path.is_file()]