Coverage for packages/workshop/src/livery/workshop/_declaration.py: 94%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_words.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_versions.py, packages/workshop/tests/test_workshop_variables.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_traces.py, packages/workshop/tests/test_workshop_test_reads.py, packages/workshop/tests/test_workshop_test_guard.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync_locked.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_sweep.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_store_tasks.py, packages/workshop/tests/test_workshop_steps.py, packages/workshop/tests/test_workshop_speed.py, packages/workshop/tests/test_workshop_skip_marks.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_shard.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_schema.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runtime_language.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_run.py, packages/workshop/tests/test_workshop_root_attribution.py, packages/workshop/tests/test_workshop_repair.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.py, packages/workshop/tests/test_workshop_release_point.py, packages/workshop/tests/test_workshop_release_fresh.py, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_release.py, packages/workshop/tests/test_workshop_registries.py, packages/workshop/tests/test_workshop_regions.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_provenance.py, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_parts.py, packages/workshop/tests/test_workshop_proved_flaky.py, packages/workshop/tests/test_workshop_proved_escapes.py, packages/workshop/tests/test_workshop_proved_decide.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_proof_pins.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_plugin_tools.py, packages/workshop/tests/test_workshop_phases.py, packages/workshop/tests/test_workshop_phase_verbs.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_package_level_fragments.py, packages/workshop/tests/test_workshop_package.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_metrics.py, packages/workshop/tests/test_workshop_lifecycle.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_invoke.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_influence.py, packages/workshop/tests/test_workshop_identity.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_graph.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_fragments.py, packages/workshop/tests/test_workshop_footprint.py, packages/workshop/tests/test_workshop_fold.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extensions.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_e2e_rows.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_due.py, packages/workshop/tests/test_workshop_doctor_unlisted.py, packages/workshop/tests/test_workshop_doctor.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/workshop/tests/test_workshop_declaration.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_cpp_kind.py, packages/workshop/tests/test_workshop_contributed_jobs.py, packages/workshop/tests/test_workshop_contract_file.py, packages/workshop/tests/test_workshop_contract.py, packages/workshop/tests/test_workshop_conformance.py, packages/workshop/tests/test_workshop_composition.py, packages/workshop/tests/test_workshop_commit.py, packages/workshop/tests/test_workshop_claims.py, packages/workshop/tests/test_workshop_ci_context.py, packages/workshop/tests/test_workshop_categories.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/workshop/tests/test_workshop_balance.py, packages/workshop/tests/test_workshop_affected_legs.py, packages/workshop/tests/test_tools_restub.py, packages/workshop/tests/test_tools_materialise.py, packages/workshop/tests/test_kind_tools.py, packages/extensions/ty/tests/test_ty.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/python/tests/test_runner_terminal.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_quality.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/python/tests/test_python_layering.py, packages/extensions/python/tests/test_private_reaches.py, packages/extensions/python/tests/test_plugin_reaches.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/python/tests/test_examples.py, packages/extensions/python/tests/test_declared_imports.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/pytest/tests/test_pytest_coverage.py, packages/extensions/pytest/tests/test_pytest_c6_selection.py, packages/extensions/pytest/tests/test_pytest_c5_repeats.py, packages/extensions/pytest/tests/test_pytest_c4_reads.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/pyrefly/tests/test_pyrefly.py, packages/extensions/nanobind/tests/test_nanobind_kind.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mypy/tests/test_mypy.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_refs.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_docstrings.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_digests.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_taskref.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_llms.py, packages/extensions/docs/tests/test_influence.py, packages/extensions/docs/tests/test_groups.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/docs/tests/test_docs_site.py, packages/extensions/docs/tests/test_docs_phase.py, packages/extensions/docs/tests/test_docs_contract.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/docs/tests/test_doc_steps.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_parts.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/coverage/tests/test_coverage_union_pins.py, packages/extensions/coverage/tests/test_coverage_store.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/coverage/tests/test_coverage_pages.py, packages/extensions/coverage/tests/test_coverage_accept.py, packages/extensions/coverage/tests/test_coverage.py, packages/extensions/coverage/tests/test_affected_legs.py, packages/extensions/conan/tests/test_layering.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/conan/tests/test_cross_kind.py, packages/extensions/conan/tests/test_conan_releases.py, packages/extensions/conan/tests/test_conan_publish.py, packages/extensions/conan/tests/test_conan_kind.py, packages/extensions/cmake/tests/test_measured_run.py, packages/extensions/cmake/tests/test_cpp_kind.py, packages/extensions/cmake/tests/test_coverage_parts.py, packages/extensions/cmake/tests/test_cmake.py, packages/extensions/clang-tidy/tests/test_clang_tidy.py, packages/extensions/clang-format/tests/test_clang_format.py, packages/extensions/changelog/tests/test_changelog.py, packages/extensions/basedpyright/tests/test_basedpyright.py, packages/extensions/agents/tests/test_agents.py ran.

1"""Read an extension's declaration file, ``extension.toml``, without importing it.
2
3An extension declares itself in one ``extension.toml``, beside the
4package its ``workshop.extensions`` entry point names: what it does, the
5workshop API version it is written for, its plugin, the extensions it
6requires, the
7phases it declares and the steps it adds to a package's lifecycle
8phases and to the gate's phases, the queries it declares and the ones
9it answers, the tools it runs, its CI jobs, the contract keys it owns,
10what it adds to another extension while that one is listed, and the
11shipped files of the base and of the extensions it requires that it
12replaces or deletes. The file is
13a contract, read as ``workshop.toml`` is: kebab-case keys, every key
14judged, every refusal naming the file. Every extension is one kind:
15the root's ``[workspace] extensions`` and a package's ``extensions``
16both list any of them, so the file says nothing about where it is
17listed.
18
19A ``[phases.<phase>]`` table declares the phase when it carries
20``level``, ``gated``, ``after``, ``verb`` or ``keys``
21([livery.workshop._phases.PhaseSpec][]), in the grammar the base's own
22contract file declares its phases in; a phase no declaration names
23refuses naming the declared ones. Beside those keys the table holds
24the phase's steps, and nothing else.
25
26A ``[queries.<name>]`` table declares the query when it carries
27``combine``, ``level``, ``default`` or ``values``
28([livery.workshop._queries.QuerySpec][]), in the grammar the base's own
29contract file declares its queries in; a table carrying ``value`` is a
30literal answer, and ``<name> = "module:function"`` under ``[queries]``
31answers by a function. An answer to a query no declaration names
32refuses naming the declared ones. A ``[for.<target>.queries]`` table
33answers in the same grammar, asked while the target is listed, and
34declares no query. A ``[for.<target>.fragments]`` table writes its files
35while the target is listed, and so are the files the extension ships
36under ``content/for/<target>/``; a directory there for a target the file
37declares no ``[for.<target>]`` table for refuses, naming both. A
38``[for.<target>.toolroom]`` table's ``requires`` names the tools the
39workspace requires while the table applies.
40
41A ``[templates.<name>]`` table declares a template, which
42``fm new.package.<name>`` creates a package from: its ``doc``, the
43``extensions`` such a package lists, ``extends``, the template whose
44files come first, its creation options under
45``[templates.<name>.options.<option>]`` (``TemplateOption``), and
46``fixes``, the answers it gives options of the templates it extends
47(``DeclaredTemplate``). The base declares its own in the same grammar,
48and a ``[for.<target>]`` table declares none: a template names the
49extensions it needs in its own ``extensions``, and a workspace offers
50it while its installed set holds the extension that declares it.
51
52``[extension] dormant-until`` names, as a verb, what another extension
53does for this one by declaring a ``[for.<this>]`` table: until a listed
54extension does, this one is dormant
55([livery.workshop._extensions.dormancy][]).
56
57An ``[env.<NAME>]`` table declares an environment variable the
58extension needs (``DeclaredVariable``): its ``value``, ``always``, and
59its ``doc``. A ``[for.<target>]`` table declares none, since a variable
60an extension needs does not depend on what else is listed.
61
62A step table's ``deletes`` names the steps of other extensions that
63never run for a package whose set holds this one, each
64``<owner>:<phase>.<step>`` to the reason: the base's, or those of an
65extension this one requires, or, in a ``[for.<target>]`` table, the
66target's, which the mount judges. A deletion naming no step an
67installed extension or the base declares, one naming a step that runs
68once over the workspace, and one without a reason refuse here.
69
70A step is declared at ``[phases.<phase>.<step>]`` and reads into one
71record whatever its phase's level
72([livery.workshop._steps.StepRecord][]): a workspace-level phase's
73steps register at mount, and a package-level phase's run over each
74package whose set holds the extension. ``fm check`` runs the tree
75side, so of a gated package-level phase, the build, a step serving
76the tree side registers at mount as well, and one serving the
77isolated side alone registers nothing. A step whose verdict is its
78tool's exit code is its tool's words (``main`` as a template, with
79``fix``, ``safe-fix``, ``env`` and ``matrix``), which the engine runs
80([livery.workshop._words.Command][]). Other behaviour is a reference,
81``"module:function"``, imported when it runs. The read imports
82nothing. A reference whose module is not in the extension's package,
83or whose module does not define the name at its top level, refuses
84here, read from the module's source.
85"""
86
87from __future__ import annotations
88
89import ast
90import difflib
91import importlib
92import importlib.util
93import keyword
94import re
95import sys
96import tomllib
97from dataclasses import dataclass, field
98from pathlib import Path
99from typing import TYPE_CHECKING, Any, cast
100
101if TYPE_CHECKING:
102 from collections.abc import Callable, Mapping
103
104 from livery.workshop._contract_keys import ContractKind, Declared, Type
105 from livery.workshop._influence import InputEntry, Inputs
106 from livery.workshop._phases import PhaseContext, PhaseSpec
107 from livery.workshop._points import JobContribution
108 from livery.workshop._queries import QuerySpec
109 from livery.workshop._steps import StepRecord
110 from livery.workshop._words import Words
111
112#: The declaration file's name, beside the package an entry point names.
113FILE = "extension.toml"
114
115#: The workshop API version a declaration takes when it names none.
116API_VERSION = 1
117
118#: The contracts an extension may declare keys in.
119CONTRACTS = ("root", "package")
120
121
122class DeclarationError(RuntimeError):
123 """An extension's declaration file says something the workshop cannot take.
124
125 The extension's own mistake, which no sync repairs: the message
126 names the file, the key, and what it takes.
127 """
128
129
130@dataclass(frozen=True)
131class Reference:
132 """A function a declaration names, ``"module:function"``, imported when it runs.
133
134 Attributes:
135 module: The module that defines it, in the extension's package.
136 name: The name the module defines it under, at its top level.
137 """
138
139 module: str
140 name: str
141
142 def resolve(self) -> Any:
143 """The object the reference names, its module imported now."""
144 return getattr(importlib.import_module(self.module), self.name)
145
146 def __call__(self, *args: Any, **kwargs: Any) -> Any:
147 """Call the named function with *args* and *kwargs*, importing it first."""
148 return self.resolve()(*args, **kwargs)
149
150 def __str__(self) -> str:
151 """The reference as the declaration spells it."""
152 return f"{self.module}:{self.name}"
153
154
155@dataclass(frozen=True)
156class CodedFix:
157 """A step's rewrite in code with a safe mode of its own, run as the record's fix.
158
159 Attributes:
160 fix: The function run under ``--fix``.
161 safe_fix: The function run under ``--safe-fix`` instead, which
162 removes no code.
163 """
164
165 fix: Reference
166 safe_fix: Reference
167
168 def __call__(self, ctx: PhaseContext) -> None:
169 """Run the mode the run asks for: the safe one under ``--safe-fix``."""
170 (self.safe_fix if ctx.safe else self.fix)(ctx)
171
172 def __str__(self) -> str:
173 """Both references, as the declaration spells them."""
174 return f"{self.fix} (safe-fix: {self.safe_fix})"
175
176
177@dataclass(frozen=True)
178class Additions:
179 """What a declaration adds while it is mounted.
180
181 Attributes:
182 steps: The steps of the ``[phases.<phase>.<step>]`` tables the
183 mount registers, as records under the extension's name:
184 those of the workspace-level phases and those of the gated
185 package-level phases, less each that serves the isolated
186 side alone.
187 jobs: The CI jobs it adds to the builtin points, with their entries.
188 """
189
190 steps: tuple[StepRecord, ...] = ()
191 jobs: tuple[JobContribution, ...] = ()
192
193
194@dataclass(frozen=True)
195class DeclaredValue:
196 """A literal answer to a query: ``[queries.<name>] value = ...``.
197
198 Attributes:
199 value: The answer, as the file spells it.
200 """
201
202 value: object
203
204
205@dataclass(frozen=True)
206class DeclaredOutput:
207 """A file an extension's code writes: a ``[fragments."<target>"]`` table.
208
209 The file is written while the workspace's installed set holds the
210 extension, the root's list or a package's set, and withdrawn when
211 none does.
212
213 Attributes:
214 target: The file's path from the workspace root; a path ending
215 in ``/`` is a directory whose files the render names.
216 render: The function the workshop calls with the workspace root.
217 For a file it answers the text, or nothing for no file; for
218 a directory, each file's path under it to its text, or to
219 the shipped file or directory the file links to.
220 local: Whether the files belong to this checkout alone and are
221 never committed.
222 """
223
224 target: str
225 render: Reference
226 local: bool = False
227
228
229@dataclass(frozen=True)
230class DeclaredVariable:
231 """An environment variable an extension needs: an ``[env.<NAME>]`` table.
232
233 The workshop sets it for every ``fm`` run, in a CI job's entry, in a
234 pass of the loop and in the scale fixture.
235
236 Attributes:
237 name: The variable's name.
238 value: Its value, as the file spells it. ``{place}`` in it
239 stands for a directory of the variable's own, which each
240 place the variable is set in names; no other brace form is
241 taken.
242 doc: What the variable is for.
243 always: Whether the value beats one the environment already
244 carries where an environment is formed for what runs inside
245 it: a CI job's, by its entry, a loop pass's and the scale
246 fixture's. Everywhere else, and without it, the
247 environment's value wins.
248 extension: The extension that declares it.
249 """
250
251 name: str
252 value: str
253 doc: str
254 always: bool = False
255 extension: str = ""
256
257 @property
258 def placed(self) -> bool:
259 """Whether the value names ``{place}``, so it is set only where one is named."""
260 from livery.workshop._variables import PLACE_WORD
261
262 return PLACE_WORD in self.value
263
264 def render(self, place: str) -> str:
265 """The value with *place* where ``{place}`` stands."""
266 from livery.workshop._variables import PLACE_WORD
267
268 return self.value.replace(PLACE_WORD, place)
269
270
271@dataclass(frozen=True)
272class Declaration:
273 """An extension's declaration file, read and judged.
274
275 Attributes:
276 extension: The name the extension is listed by.
277 package: The package its entry point names, where its references live.
278 path: The declaration file.
279 description: What the extension does, in a sentence or two,
280 which the agent's guidance and the site's development pages
281 open its block with; empty for none.
282 api_version: The workshop API version it is written for.
283 plugin: The footman plugin carrying its verbs; empty for none.
284 requires: The extensions it cannot work without.
285 dormant_until: What another extension does for this one by
286 declaring a ``[for.<this>]`` table, a verb; empty for an
287 extension that is never dormant.
288 tools: The tools it runs, its verbs' and its steps', as
289 requirement strings.
290 additions: What it adds whenever it is mounted.
291 targets: What it adds to each target while the target is listed.
292 target_tables: Each ``[for.<target>]`` table as the file holds it.
293 tables: The file's top-level tables but ``[extension]`` and
294 ``[for]``, as the file holds them.
295 replaces: Each shipped file of the base or of an extension it
296 requires, ``<owner>:<name>``, its own file of that name
297 replaces, to the reason.
298 deletes: Each shipped file of the base or of an extension it
299 requires that it deletes, to the reason.
300 fragments: The files its code writes, by target.
301 target_fragments: The files each ``[for.<target>]`` table's code
302 writes, by target; a target whose table writes none is left
303 out.
304 target_tools: The tools each ``[for.<target>]`` table requires
305 under ``[toolroom] requires``, by target, as requirement
306 strings; a target whose table requires none is left out.
307 phase_specs: The phases it declares, by name.
308 phases: The steps its top-level ``[phases.<phase>.<step>]``
309 tables add, by phase, each the one step record whatever
310 the phase's level: a package-level phase's run through the
311 walk of a package's phase
312 ([livery.workshop._phases.walk_steps][]), and those the
313 mount registers are among ``additions`` too.
314 query_specs: The queries it declares, by name.
315 queries: The queries it answers, each query's name to the
316 function that answers it or to its literal answer.
317 target_queries: The queries each ``[for.<target>]`` table
318 answers, by target, in the shape of ``queries``; a target
319 whose table answers none is left out.
320 categories: The categories it gives its packages' paths, each
321 category to the patterns it takes, relative to the package.
322 templates: The templates it declares, by name, in the file's
323 order.
324 env: The environment variables it needs, in the file's order.
325 """
326
327 extension: str
328 package: str
329 path: Path
330 description: str = ""
331 api_version: int = API_VERSION
332 plugin: str = ""
333 requires: tuple[str, ...] = ()
334 dormant_until: str = ""
335 tools: tuple[str, ...] = ()
336 additions: Additions = Additions()
337 targets: dict[str, Additions] = field(default_factory=dict[str, Additions])
338 target_tables: dict[str, dict[str, Any]] = field(
339 default_factory=dict[str, dict[str, Any]]
340 )
341 tables: dict[str, Any] = field(default_factory=dict[str, Any])
342 replaces: dict[str, str] = field(default_factory=dict[str, str])
343 deletes: dict[str, str] = field(default_factory=dict[str, str])
344 fragments: tuple[DeclaredOutput, ...] = ()
345 target_fragments: dict[str, tuple[DeclaredOutput, ...]] = field(
346 default_factory=dict[str, tuple[DeclaredOutput, ...]]
347 )
348 target_tools: dict[str, tuple[str, ...]] = field(
349 default_factory=dict[str, tuple[str, ...]]
350 )
351 phase_specs: dict[str, PhaseSpec] = field(default_factory=dict[str, "PhaseSpec"])
352 phases: dict[str, tuple[StepRecord, ...]] = field(
353 default_factory=dict[str, tuple["StepRecord", ...]]
354 )
355 query_specs: dict[str, QuerySpec] = field(default_factory=dict[str, "QuerySpec"])
356 queries: dict[str, Reference | DeclaredValue] = field(
357 default_factory=dict[str, "Reference | DeclaredValue"]
358 )
359 target_queries: dict[str, dict[str, Reference | DeclaredValue]] = field(
360 default_factory=dict[str, "dict[str, Reference | DeclaredValue]"]
361 )
362 categories: tuple[tuple[str, tuple[str, ...]], ...] = ()
363 templates: dict[str, DeclaredTemplate] = field(
364 default_factory=dict[str, "DeclaredTemplate"]
365 )
366 env: tuple[DeclaredVariable, ...] = ()
367
368
369_LOCATED: dict[tuple[str, tuple[str, ...]], Path] = {}
370
371
372def directory(package: str) -> Path | None:
373 """Where *package* lives, found without importing it; None when it is absent.
374
375 The directory that carries the declaration file when several hold
376 the package's parts, as a namespace's portions do. Found once per
377 import path, since a mount asks for each extension's several times;
378 an absence is never kept, so a package installed later is found.
379 """
380 key = (package, tuple(sys.path))
381 if key in _LOCATED:
382 return _LOCATED[key]
383 found = _locate(package)
384 if found is not None:
385 _LOCATED[key] = found
386 return found
387
388
389def _locate(package: str) -> Path | None:
390 try:
391 spec = importlib.util.find_spec(package)
392 except (ImportError, ValueError):
393 return None
394 if spec is None or not spec.submodule_search_locations:
395 return None
396 locations = [Path(location) for location in spec.submodule_search_locations]
397 for location in locations:
398 if (location / FILE).is_file():
399 return location
400 return locations[0]
401
402
403def declaration_file(package: str) -> Path | None:
404 """*package*'s declaration file; None when the package or its file is absent."""
405 found = directory(package)
406 if found is None or not (found / FILE).is_file():
407 return None
408 return found / FILE
409
410
411#: The tables whose keys the author names, a file or a query's answer or
412#: a shipped file's reference or an environment variable: their keys are
413#: data, never judged kebab-case.
414_NAMED = (
415 ("phases", "*", "*", "fragments"),
416 ("for", "*", "phases", "*", "*", "fragments"),
417 ("phases", "*", "*", "env"),
418 ("for", "*", "phases", "*", "*", "env"),
419 ("phases", "*", "*", "replaces"),
420 ("phases", "*", "*", "deletes"),
421 ("replaces",),
422 ("for", "*", "replaces"),
423 ("deletes",),
424 ("for", "*", "deletes"),
425 ("queries", "*", "default"),
426 ("queries", "*", "value"),
427 ("for", "*", "queries", "*", "value"),
428 ("fragments",),
429 ("for", "*", "fragments"),
430 ("env",),
431)
432
433
434def _underscored(table: dict[str, Any], parts: tuple[str, ...] = ()) -> list[str]:
435 """Each key under *table* spelled with an underscore that is not a name."""
436 from livery.workshop._contract_keys import shown
437
438 named = any(
439 len(pattern) == len(parts)
440 and all(want in ("*", part) for want, part in zip(pattern, parts, strict=True))
441 for pattern in _NAMED
442 )
443 found: list[str] = []
444 for key, value in table.items():
445 path = (*parts, key)
446 if "_" in key and not named:
447 found.append(shown(path))
448 if isinstance(value, dict):
449 found += _underscored(cast("dict[str, Any]", value), path)
450 elif isinstance(value, list):
451 for item in cast("list[object]", value):
452 if isinstance(item, dict):
453 found += _underscored(cast("dict[str, Any]", item), path)
454 return found
455
456
457_PARSED: dict[tuple[Path, str], dict[str, Any]] = {}
458
459
460def _parsed(path: Path, text: str) -> dict[str, Any]:
461 """*path*'s *text* parsed, its keys judged kebab-case; refused naming the file.
462
463 Parsed once per content: the result is kept by the text itself,
464 since a file rewritten within one tick of the clock keeps its
465 modification time.
466 """
467 key = (path, text)
468 if key not in _PARSED:
469 _PARSED[key] = _parse(path, text)
470 return _PARSED[key]
471
472
473def _parse(path: Path, text: str) -> dict[str, Any]:
474 try:
475 data = tomllib.loads(text)
476 except tomllib.TOMLDecodeError as error:
477 raise DeclarationError(f"{path}: not valid TOML: {error}") from error
478 wrong = _underscored(data)
479 if wrong:
480 listed = ", ".join(
481 f"{key} (spell it {key.rpartition('.')[2].replace('_', '-')})"
482 for key in wrong
483 )
484 raise DeclarationError(f"{path}: keys are kebab-case; found {listed}")
485 return data
486
487
488_CACHE: dict[tuple[str, str, Path, str, frozenset[str]], Declaration] = {}
489
490
491def read(extension: str, package: str) -> Declaration | None:
492 """*extension*'s declaration, from the file beside *package*; None without one.
493
494 A ``[for.<target>]`` table is read while an installed distribution
495 ships the target's declaration, since its steps and answers name
496 what the target declares; until then it adds nothing. Judged once
497 per content and per set of targets read: the result is kept by the
498 file's text and those targets.
499
500 Raises:
501 DeclarationError: when the file does not parse, a key is unknown
502 or of the wrong type, or a reference does not resolve.
503 """
504 from livery.workshop._extensions import ships_declaration
505
506 path = declaration_file(package)
507 if path is None:507 ↛ 508line 507 didn't jump to line 508 because the condition on line 507 was never true
508 return None
509 text = path.read_text("utf-8")
510 readable = frozenset(
511 str(target)
512 for target in _parsed(path, text).get("for", {})
513 if ships_declaration(str(target))
514 )
515 key = (extension, package, path, text, readable)
516 found = _CACHE.get(key)
517 if found is None:
518 found = _read(extension, package, path, text, readable)
519 _CACHE[key] = found
520 return found
521
522
523def _read(
524 extension: str, package: str, path: Path, text: str, readable: frozenset[str]
525) -> Declaration:
526 from livery.workshop._contract_keys import judge
527
528 data = _parsed(path, text)
529 reader = _Reader(extension, package, path)
530 problems = judge(data, contract="extension", where=str(path), listed=None)
531 if problems:
532 raise DeclarationError(
533 f"{path}:\n" + "\n".join(f" {line}" for line in problems)
534 )
535 reader.shipped_for(data)
536 own = phase_specs_of(data, path, extension=extension)
537 reader.specs = _known_phases(own, path)
538 own_queries = query_specs_of(data, path, extension=extension, package=package)
539 reader.query_specs = _known_queries(own_queries, path)
540 from livery.workshop._categories import known_categories
541
542 own_categories = {str(name) for name in data.get("categories", ())}
543 for sub in data.get("for", {}).values():
544 if isinstance(sub, dict):544 ↛ 543line 544 didn't jump to line 543 because the condition on line 544 was always true
545 own_categories.update(str(name) for name in sub.get("categories", ()))
546 reader.categories = set(known_categories()) | own_categories
547 identity = data.get("extension", {})
548 phases = reader.steps(data, ())
549 additions = reader.additions(data, (), steps=phases)
550 # A [for.<target>] table names the phases and queries the target
551 # declares, so it is read while an installed distribution ships the
552 # target's declaration; until then it adds nothing.
553 held = {
554 str(target): table
555 for target, table in data.get("for", {}).items()
556 if str(target) in readable
557 }
558 targets = {
559 target: reader.additions(table, ("for", target))
560 for target, table in held.items()
561 }
562 contract_keys_of(data, path) # judged here as well, so a mount names it
563 templates = template_specs_of(data, path, extension=extension)
564 queries = reader.answers(data, ())
565 answered = {
566 target: reader.answers(table, ("for", target)) for target, table in held.items()
567 }
568 if "executables" in queries and not phases.get("run"):
569 raise reader.refuse(
570 ("queries", "executables"),
571 "names the executables fm run starts, and no [phases.run.<step>] starts"
572 " them; add a step to the run phase",
573 )
574 return Declaration(
575 extension,
576 package,
577 path,
578 description=str(identity.get("description", "")).strip(),
579 api_version=int(identity.get("api-version", API_VERSION)),
580 plugin=str(identity.get("plugin", "")),
581 requires=tuple(str(name) for name in identity.get("requires", ())),
582 dormant_until=str(identity.get("dormant-until", "")),
583 tools=tuple(str(text) for text in data.get("toolroom", {}).get("requires", ())),
584 additions=additions,
585 targets=targets,
586 target_tables={
587 str(target): dict(table) for target, table in data.get("for", {}).items()
588 },
589 tables={
590 key: value for key, value in data.items() if key not in ("extension", "for")
591 },
592 replaces={str(ref): str(why) for ref, why in data.get("replaces", {}).items()},
593 deletes={str(ref): str(why) for ref, why in data.get("deletes", {}).items()},
594 fragments=tuple(
595 reader.output(str(target), table)
596 for target, table in data.get("fragments", {}).items()
597 ),
598 target_fragments={
599 str(target): tuple(
600 reader.output(str(written), table, ("for", str(target)))
601 for written, table in held["fragments"].items()
602 )
603 for target, held in data.get("for", {}).items()
604 if held.get("fragments")
605 },
606 target_tools={
607 str(target): tuple(str(text) for text in held["toolroom"]["requires"])
608 for target, held in data.get("for", {}).items()
609 if held.get("toolroom", {}).get("requires")
610 },
611 phase_specs=own,
612 phases=phases,
613 query_specs=own_queries,
614 queries=queries,
615 target_queries={target: found for target, found in answered.items() if found},
616 categories=tuple(
617 (str(category), tuple(str(pattern) for pattern in patterns))
618 for category, patterns in data.get("categories", {}).items()
619 ),
620 templates=templates,
621 env=reader.variables(data),
622 )
623
624
625class _Reader:
626 """Build what one declaration file declares, refusing what does not resolve."""
627
628 def __init__(self, extension: str, package: str, path: Path) -> None:
629 self.extension = extension
630 self.package = package
631 self.path = path
632 #: The declared phases a table of this file may name: every
633 #: installed declaration's and this file's own.
634 self.specs: dict[str, PhaseSpec] = {}
635 #: The declared queries an answer in this file may name, the
636 #: same way.
637 self.query_specs: dict[str, QuerySpec] = {}
638 #: The category names an inputs entry in this file may name.
639 self.categories: set[str] = set()
640
641 def refuse(self, where: tuple[str, ...], text: str) -> DeclarationError:
642 from livery.workshop._contract_keys import shown
643
644 return DeclarationError(f"{self.path}: {shown(where)} {text}")
645
646 def spec(self, name: str, prefix: tuple[str, ...]) -> PhaseSpec:
647 """The declared phase *name* a ``[phases.<name>]`` table names.
648
649 Refuses one no declaration names, naming the declared ones and
650 the nearest spelling.
651 """
652 found = self.specs.get(name)
653 if found is None:
654 near = difflib.get_close_matches(name, list(self.specs), n=1)
655 hint = f"; did you mean {near[0]!r}?" if near else ""
656 raise self.refuse(
657 (*prefix, "phases", name),
658 f"names no phase; the phases are {', '.join(self.specs)}{hint}",
659 )
660 return found
661
662 def additions(
663 self,
664 data: dict[str, Any],
665 prefix: tuple[str, ...],
666 *,
667 steps: Mapping[str, tuple[StepRecord, ...]] | None = None,
668 ) -> Additions:
669 """What *data* adds: the gate phases' steps and jobs.
670
671 The steps are those of the workspace-level phases among
672 *steps*, read from *data* when none are given, and those of the
673 gated package-level phases: the gate builds each package on the
674 build phase's tree side, so a build step serving that side
675 registers. A package-level phase the gate does not run, the
676 release's stamp or publish, runs its steps through the walk of
677 a package's phase and registers none. A step serving a phase's
678 isolated side alone registers nothing either: the gate runs the
679 tree side, and the release train runs that step through the
680 walk of the package's phase.
681 """
682 from livery.workshop._phases import WORKSPACE_LEVEL
683
684 found = steps if steps is not None else self.steps(data, prefix)
685 registered = [
686 record
687 for phase, records in found.items()
688 if self.specs[phase].level == WORKSPACE_LEVEL or self.specs[phase].gated
689 for record in records
690 if record.isolated is not True
691 ]
692 jobs: list[JobContribution] = []
693 for point, named in data.get("ci", {}).get("jobs", {}).items():
694 for name, entry in named.items():
695 jobs.append(
696 self.job(
697 str(point),
698 str(name),
699 entry,
700 (*prefix, "ci", "jobs"),
701 earlier=tuple(jobs),
702 )
703 )
704 return Additions(tuple(registered), tuple(jobs))
705
706 def job(
707 self,
708 point: str,
709 name: str,
710 entry: dict[str, Any],
711 prefix: tuple[str, ...],
712 *,
713 earlier: tuple[JobContribution, ...] = (),
714 ) -> JobContribution:
715 """The job *entry* adds to the builtin *point*, its functions resolved.
716
717 A table naming a job the point already has, declared,
718 inherited, contributed, or declared *earlier* in this file,
719 joins that job: its entries and plumbing become the job's on
720 this point. A join that ``gates`` refuses, since the verdict's
721 needs are the job's own. A join's ``needs`` join the needs of a
722 job the point has of its own; on a job the point inherits they
723 refuse, since that job's needs are the point's it inherits
724 from, whose runs never have the joining point's jobs. A job
725 naming ``labels`` fans out to one leg per runner label the
726 function names (a ``runners`` matrix). ``judges`` names the
727 tasks that judge the run before the verdict, on a join of a
728 point's own verdict job alone; on any other job they refuse
729 ([livery.workshop._points.judges_refusal][]).
730 """
731 from livery.workshop._points import (
732 DECLARED,
733 Entry,
734 Job,
735 JobContribution,
736 contributed_jobs,
737 judges_refusal,
738 point_has_job,
739 )
740
741 where = (*prefix, point, name)
742 builtin = {declared.name: declared for declared in DECLARED}
743 if point not in builtin:
744 raise self.refuse(
745 where,
746 f"names the point {point!r}, which is not builtin; a job joins"
747 f" one of {', '.join(builtin)}",
748 )
749 lineage = (point, builtin[point].inherits)
750 joins = point_has_job(point, name) or any(
751 item.point in lineage and item.job.name == name for item in earlier
752 )
753 if "judges" in entry and (why := judges_refusal(point, name)):
754 raise self.refuse((*where, "judges"), why)
755 if joins and entry.get("gates"):
756 raise self.refuse(
757 (*where, "gates"),
758 f"joins the {point} point's {name} job and gates; a join adds"
759 " entries and plumbing, and the verdict's needs stay the job's own",
760 )
761 own = {job.name for job in builtin[point].jobs}
762 own |= {item.job.name for item in contributed_jobs(point)}
763 own |= {
764 item.job.name
765 for item in earlier
766 if item.point == point and not item.job.joins
767 }
768 if joins and "needs" in entry and name not in own:
769 parent = builtin[point].inherits
770 raise self.refuse(
771 (*where, "needs"),
772 f"joins the {name} job the {point} point inherits from the"
773 f" {parent} point; that job waits for the {parent} point's jobs"
774 " alone, so a join of it names no needs",
775 )
776 labels = (
777 self.reference(entry["labels"], (*where, "labels"))
778 if "labels" in entry
779 else None
780 )
781 job = Job(
782 name,
783 matrix="runners" if labels is not None else "",
784 labels=labels,
785 needs=tuple(str(need) for need in entry.get("needs", ())),
786 fetch=str(entry.get("fetch", "")),
787 token=str(entry.get("token", "")),
788 installs=self.reference(entry["installs"], (*where, "installs"))
789 if "installs" in entry
790 else None,
791 conan_cache=bool(entry.get("conan-cache", False)),
792 cache_dir=str(entry.get("cache-dir", "")),
793 deploy=self.reference(entry["deploy"], (*where, "deploy"))
794 if "deploy" in entry
795 else None,
796 publishes=str(entry.get("publishes", "")),
797 paths=tuple(str(path) for path in entry.get("paths", ())),
798 collects=str(entry.get("collects", "")),
799 inputs=self.inputs(entry["inputs"], (*where, "inputs"))
800 if "inputs" in entry
801 else None,
802 note=str(entry.get("note", "")),
803 joins=joins,
804 )
805 return JobContribution(
806 point,
807 job,
808 entries=tuple(
809 Entry(point, name, str(task), source=self.extension)
810 for task in entry.get("entries", ())
811 )
812 + tuple(
813 Entry(point, name, str(task), source=self.extension, judges=True)
814 for task in entry.get("judges", ())
815 ),
816 gates=bool(entry.get("gates", False)),
817 extension=self.extension,
818 )
819
820 def steps(
821 self, data: dict[str, Any], prefix: tuple[str, ...]
822 ) -> dict[str, tuple[StepRecord, ...]]:
823 """Every step *data*'s ``[phases.<phase>.<step>]`` tables declare, by phase.
824
825 A phase with no step is left out. A step of a package-level
826 phase runs over the packages whose set holds the extension.
827 """
828 found: dict[str, tuple[StepRecord, ...]] = {}
829 for phase, table in data.get("phases", {}).items():
830 self.spec(str(phase), prefix)
831 named = _step_tables(table)
832 if not named:
833 continue
834 found[str(phase)] = tuple(
835 self.step(str(phase), step, entry, (*prefix, "phases"))
836 for step, entry in named.items()
837 )
838 return found
839
840 def step(
841 self, phase: str, step: str, entry: dict[str, Any], prefix: tuple[str, ...]
842 ) -> StepRecord:
843 """The step ``[phases.<phase>.<step>]`` declares: a record placing its paths.
844
845 ``main`` is the body: a template, the tool's name as ``tools``
846 names it then its arguments, or a reference to its code,
847 ``module:function``; ``fix`` and ``safe-fix`` take the body's
848 shape. A template narrows by the paths the run reaches when
849 ``{paths}`` stands among its words and runs whole without it,
850 and takes the words after ``--`` where ``{arguments}`` stands.
851 A step in code places neither, so its record says what its code
852 does: a workspace step that declares no ``inputs`` narrows by
853 the packages the run reaches, which its code asks
854 [livery.workshop.scoped_packages][] for, and one with ``inputs``
855 is selected by them and judges the whole; a step that names
856 ``tools`` wraps them and takes the words after ``--``, and one
857 that names none refuses them. ``isolated`` names the side of the
858 phase the step serves, and refuses on a step of a phase whose
859 declaration gives no ``isolated`` key.
860 """
861 from dataclasses import replace
862
863 from livery.workshop._phases import ISOLATED, PACKAGE_LEVEL
864 from livery.workshop._steps import NONE, PACKAGE, PACKAGES, PATHS, WORKSPACE
865
866 where = (*prefix, phase, step)
867 if ISOLATED in entry and ISOLATED not in self.specs[phase].keys:
868 raise self.refuse(
869 (*where, ISOLATED),
870 f"is not read on a step of the {phase} phase, which has one side:"
871 " its declaration gives no isolated key",
872 )
873 run, fix, words = self.step_bodies(entry, where)
874 provides, reads = self.context_keys(entry, where, "another step")
875 others = {
876 key: self.other_steps(entry.get(key, {}), (*where, key))
877 for key in ("replaces", "deletes")
878 }
879 for address, _reason in others["deletes"]:
880 self.deletion(address, (*where, "deletes", address))
881 record = self.record(step, phase, entry, where, run, fix, words)
882 if self.specs[phase].level == PACKAGE_LEVEL:
883 # The phase's level says how often the step runs: once per
884 # package whose set holds the extension.
885 for key in ("scope", "extensions"):
886 if key in entry:
887 raise self.refuse(
888 (*where, key),
889 f"is not read on a step of the {phase} phase, which runs"
890 " once per package whose set holds the extension, as the"
891 " phase's level says",
892 )
893 record = replace(record, scope=PACKAGE, extensions=(self.extension,))
894 if words is not None:
895 named = words.placeholders()
896 narrowing = PATHS if "paths" in named else NONE
897 arguments = "arguments" in named
898 else:
899 narrowing = (
900 PACKAGES
901 if record.scope == WORKSPACE
902 and (record.inputs is None or bool(record.extensions))
903 else NONE
904 )
905 arguments = bool(record.tools)
906 return replace(
907 record,
908 narrowing=narrowing,
909 arguments=arguments,
910 enabled=bool(entry.get("enabled", True)),
911 provides=tuple(provides.items()),
912 reads=reads,
913 isolated=None if "isolated" not in entry else bool(entry["isolated"]),
914 replaces=others["replaces"],
915 deletes=others["deletes"],
916 )
917
918 def other_steps(
919 self, table: dict[str, Any], where: tuple[str, ...]
920 ) -> tuple[tuple[str, str], ...]:
921 """The steps of other extensions *table* names, each to the reason it states.
922
923 A step is ``<owner>:<phase>.<step>``, and the reason is a line
924 of text; a step named with no reason refuses.
925 """
926 found: list[tuple[str, str]] = []
927 for text, reason in table.items():
928 if not _step_address(text):
929 raise self.refuse(
930 where,
931 f"names {text!r}; a step of another extension is"
932 " <owner>:<phase>.<step>",
933 )
934 if not str(reason).strip():
935 raise self.refuse(
936 (*where, text),
937 "states no reason; a step names each step it replaces or"
938 " deletes with the reason",
939 )
940 found.append((text, str(reason)))
941 return tuple(found)
942
943 def deletion(self, address: str, where: tuple[str, ...]) -> None:
944 """Refuse a deletion of a step nothing installed declares, or of a workspace's.
945
946 A deletion takes a step off each package whose set holds this
947 extension, so it names a step that runs once per package.
948 """
949 from livery.workshop._steps import PACKAGE
950
951 steps = installed_steps()
952 scope = steps.get(address)
953 if scope is None:
954 phase = address.partition(":")[2].partition(".")[0]
955 held = sorted(
956 other
957 for other in steps
958 if other.partition(":")[2].partition(".")[0] == phase
959 )
960 listed = (
961 f"the {phase} phase's are {', '.join(held)}"
962 if held
963 else f"the {phase} phase has none"
964 )
965 raise self.refuse(
966 where,
967 f"names no step an installed extension or the base declares; {listed}",
968 )
969 if scope != PACKAGE:
970 raise self.refuse(
971 where,
972 "names a step that runs once over the workspace; a deletion takes"
973 " a step off each package whose set holds this extension, so it"
974 " names a step that runs once per package",
975 )
976
977 def record(
978 self,
979 step: str,
980 phase: str,
981 entry: dict[str, Any],
982 where: tuple[str, ...],
983 run: Callable[[PhaseContext], None],
984 fix: Callable[[PhaseContext], None] | None,
985 words: Words | None,
986 ) -> StepRecord:
987 """The record from a step table's shared keys, its body resolved.
988
989 ``scope``, ``claims``, ``extensions``, ``options``, ``fragments``,
990 ``inputs``, ``after``, ``tools``, ``tests-only``, ``flags`` and
991 ``outputs``;
992 ``step`` sets the step's own fields after.
993 """
994 from livery.workshop._fragments import verify
995 from livery.workshop._steps import Option, StepRecord
996
997 inputs = (
998 self.inputs(entry["inputs"], (*where, "inputs"))
999 if "inputs" in entry
1000 else None
1001 )
1002 record = StepRecord(
1003 step,
1004 phase,
1005 run,
1006 scope=str(entry.get("scope", "workspace")),
1007 fix=fix,
1008 words=words,
1009 extensions=tuple(str(name) for name in entry.get("extensions", ())),
1010 tests_only=bool(entry.get("tests-only", False)),
1011 after=tuple(entry.get("after", ())),
1012 extension=self.extension,
1013 tools=tuple(entry.get("tools", ())),
1014 options=tuple(
1015 Option(
1016 str(name),
1017 str(option.get("type", "")),
1018 option.get("default"),
1019 str(option.get("doc", "")),
1020 )
1021 for name, option in entry.get("options", {}).items()
1022 ),
1023 fragments=self.fragments(entry.get("fragments", {}), (*where, "fragments")),
1024 flags=tuple(entry.get("flags", ())),
1025 inputs=inputs,
1026 outputs=self.outputs(entry.get("outputs", ()), (*where, "outputs")),
1027 )
1028 for option in record.options:
1029 if option.kind not in ("bool", "str", "int", "strs"):1029 ↛ 1030line 1029 didn't jump to line 1030 because the condition on line 1029 was never true
1030 raise self.refuse(
1031 (*where, "options", option.name, "type"),
1032 "is required: bool, str, int or strs",
1033 )
1034 try:
1035 verify(record.fragments, record.name)
1036 except ValueError as error:
1037 raise self.refuse((*where, "fragments"), f"refuses: {error}") from error
1038 return record
1039
1040 def outputs(self, listed: list[str], where: tuple[str, ...]) -> tuple[str, ...]:
1041 """The paths a step declares it writes, each below the root and never docs/.
1042
1043 Refuses an output that leaves the root, names the root or a
1044 package itself, or names ``docs/`` itself, which holds the
1045 authored pages.
1046 """
1047 from livery.workshop._phases import output_refusal
1048
1049 for output in listed:
1050 refusal = output_refusal(output)
1051 if refusal:
1052 raise self.refuse(where, refusal)
1053 return tuple(listed)
1054
1055 def step_bodies(
1056 self, entry: dict[str, Any], where: tuple[str, ...]
1057 ) -> tuple[
1058 Callable[[PhaseContext], None],
1059 Callable[[PhaseContext], None] | None,
1060 Words | None,
1061 ]:
1062 """A step's main and fix, from its template or from references to its code.
1063
1064 ``main`` is a list, the template, or a string, the reference;
1065 ``fix`` and ``safe-fix`` take its shape, and ``env`` and
1066 ``matrix`` vary a template's calls alone. ``{paths}`` and
1067 ``{arguments}`` each stand alone as one word of a template.
1068 """
1069 from livery.workshop._words import PATHS_WORD, PLACED, Command
1070
1071 if "main" not in entry:
1072 raise self.refuse(
1073 where,
1074 "names no main: a step's body is a template, the tool's name then"
1075 " its arguments, or a reference to its code, module:function",
1076 )
1077 if isinstance(entry["main"], list):
1078 words = self.words(entry, where)
1079 spelled = [
1080 ("main", words.judge),
1081 ("fix", words.fix),
1082 ("safe-fix", words.safe_fix),
1083 ("env", tuple(value for _name, value in words.env)),
1084 ]
1085 for key, texts in spelled:
1086 for text in texts:
1087 for placed in PLACED:
1088 if placed in text and text != placed:
1089 goes = (
1090 "the run's paths"
1091 if placed == PATHS_WORD
1092 else "the words after --"
1093 )
1094 raise self.refuse(
1095 (*where, key),
1096 f"names {placed} in {text!r}; it stands alone as one"
1097 f" word, where {goes} go",
1098 )
1099 name = f"{where[-2]}.{where[-1]}"
1100 fixing = Command(words, name, fixing=True) if words.fix else None
1101 return Command(words, name), fixing, words
1102 for key in ("env", "matrix"):
1103 if key in entry:
1104 raise self.refuse(
1105 (*where, key),
1106 "belongs to a step in words, and this one runs code; declare"
1107 " main as words, the tool's name then its arguments, or drop"
1108 " the key",
1109 )
1110 for key in ("fix", "safe-fix"):
1111 if key in entry and not isinstance(entry[key], str):
1112 raise self.refuse(
1113 (*where, key),
1114 "is words, and main is a reference to code: a step that runs"
1115 " code fixes with code, module:function",
1116 )
1117 if "safe-fix" in entry and "fix" not in entry:
1118 raise self.refuse(
1119 (*where, "safe-fix"),
1120 "is declared without fix: a step that fixes safely fixes too",
1121 )
1122 coded: Callable[[PhaseContext], None] | None = None
1123 if "fix" in entry:
1124 fix = self.reference(entry["fix"], (*where, "fix"))
1125 coded = fix
1126 if "safe-fix" in entry:
1127 coded = CodedFix(
1128 fix, self.reference(entry["safe-fix"], (*where, "safe-fix"))
1129 )
1130 return self.reference(entry["main"], (*where, "main")), coded, None
1131
1132 def words(self, entry: dict[str, Any], where: tuple[str, ...]) -> Words:
1133 """The words *entry* declares: its main, fix, safe-fix, env and matrix."""
1134 from livery.workshop._words import Words
1135
1136 def argv(key: str) -> tuple[str, ...]:
1137 value = entry.get(key, [])
1138 if isinstance(value, str):
1139 raise self.refuse(
1140 (*where, key),
1141 f"is {value!r}, a reference to code; in a step in words,"
1142 f" {key} is words: the tool's name, then its arguments",
1143 )
1144 return tuple(str(word) for word in value)
1145
1146 judge, fix, safe_fix = argv("main"), argv("fix"), argv("safe-fix")
1147 if not judge:
1148 raise self.refuse((*where, "main"), "is empty: the tool's name comes first")
1149 if safe_fix and not fix:
1150 raise self.refuse(
1151 (*where, "safe-fix"),
1152 "is declared without fix: a step that fixes safely fixes too",
1153 )
1154 for key, value in (("fix", fix), ("safe-fix", safe_fix)):
1155 if value and value[0] != judge[0]:
1156 raise self.refuse(
1157 (*where, key),
1158 f"runs {value[0]}, and main runs {judge[0]}: a step runs one tool",
1159 )
1160 matrix: list[tuple[str, tuple[str, ...]]] = []
1161 for key, values in entry.get("matrix", {}).items():
1162 if not values:
1163 raise self.refuse(
1164 (*where, "matrix", key),
1165 "has no values: a matrix key runs one call per value",
1166 )
1167 matrix.append((str(key), tuple(str(value) for value in values)))
1168 env = tuple(
1169 (str(name), str(value)) for name, value in entry.get("env", {}).items()
1170 )
1171 return Words(judge, fix, safe_fix, env, tuple(matrix))
1172
1173 def fragments(
1174 self, table: dict[str, Any], where: tuple[str, ...]
1175 ) -> tuple[Any, ...]:
1176 """A project file's fragment from its text; a package file's, its extensions."""
1177 from livery.workshop._fragments import Fragment
1178
1179 found: list[Fragment] = []
1180 for file, value in table.items():
1181 if isinstance(value, str):
1182 found.append(Fragment(file, value))
1183 continue
1184 entry = cast("dict[str, Any]", value)
1185 if "text" not in entry or not entry.get("extensions"):
1186 raise self.refuse(
1187 (*where, file),
1188 "is a package file's fragment: its text, and the extensions"
1189 " whose packages render it",
1190 )
1191 extensions = tuple(str(name) for name in entry["extensions"])
1192 found.append(Fragment(file, str(entry["text"]), extensions=extensions))
1193 return tuple(found)
1194
1195 def output(
1196 self, target: str, table: dict[str, Any], prefix: tuple[str, ...] = ()
1197 ) -> DeclaredOutput:
1198 """The file *target* names, written by the render its table references.
1199
1200 *prefix* is the ``[for.<target>]`` table the fragment is under,
1201 empty for the top level.
1202 """
1203 where = (*prefix, "fragments", target)
1204 if "render" not in table:
1205 raise self.refuse(
1206 where,
1207 "names no render; a fragment's code is render = 'module:function'",
1208 )
1209 return DeclaredOutput(
1210 target,
1211 self.reference(table["render"], (*where, "render")),
1212 local=bool(table.get("local", False)),
1213 )
1214
1215 def variables(self, data: dict[str, Any]) -> tuple[DeclaredVariable, ...]:
1216 """The environment variables *data*'s ``[env]`` table declares, in its order.
1217
1218 The schema judged the types of ``value``, ``doc`` and ``always``
1219 before this read. Refuses a name no shell exports, a missing
1220 ``value`` or ``doc``, an empty ``doc``, a value holding a line
1221 break, and a brace form in the value other than ``{place}``,
1222 naming it: so a later placeholder never changes what a declared
1223 value means.
1224 """
1225 from livery.workshop._variables import NAME, PLACE_WORD, unanswered
1226
1227 found: list[DeclaredVariable] = []
1228 for name, table in data.get("env", {}).items():
1229 where = ("env", str(name))
1230 if not NAME.fullmatch(str(name)):
1231 raise self.refuse(
1232 where,
1233 "is no variable name: letters, digits and underscores, not"
1234 " starting with a digit, as a shell exports one",
1235 )
1236 entry = cast("dict[str, Any]", table)
1237 for key, what in (
1238 ("value", "the variable's value"),
1239 ("doc", "what the variable is for"),
1240 ):
1241 if key not in entry:
1242 raise self.refuse((*where, key), f"is missing: {what}")
1243 value, doc = str(entry["value"]), str(entry["doc"]).strip()
1244 if not doc:
1245 raise self.refuse(
1246 (*where, "doc"), "is empty: say what the variable is for"
1247 )
1248 if "\n" in value or "\r" in value:
1249 raise self.refuse(
1250 (*where, "value"), "holds a line break, which no export can carry"
1251 )
1252 wrong = unanswered(value)
1253 if wrong:
1254 raise self.refuse(
1255 (*where, "value"),
1256 f"names {', '.join(wrong)}, which an [env] value does not"
1257 f" answer; it answers {PLACE_WORD} alone, a directory of the"
1258 " variable's own",
1259 )
1260 found.append(
1261 DeclaredVariable(
1262 str(name),
1263 value,
1264 doc,
1265 always=bool(entry.get("always", False)),
1266 extension=self.extension,
1267 )
1268 )
1269 return tuple(found)
1270
1271 def shipped_for(self, data: dict[str, Any]) -> None:
1272 """Refuse ``content/for/<target>/`` for a target with no ``[for]`` table.
1273
1274 The files under it are delivered while the extension contributes
1275 to the target, which a ``[for.<target>]`` table declares, so a
1276 directory for a target the file declares nothing for would never
1277 be delivered: a misspelled target, or a table that went.
1278 """
1279 from livery.workshop._contract_keys import shown
1280
1281 shipped = self.path.parent / "content" / "for"
1282 if not shipped.is_dir():
1283 return
1284 declared = data.get("for", {})
1285 for held in sorted(shipped.iterdir()):
1286 if held.is_dir() and held.name not in declared:
1287 raise DeclarationError(
1288 f"{self.path}: content/for/{held.name}/ ships files for"
1289 f" {held.name}, and the file declares no"
1290 f" [{shown(('for', held.name))}] table; declare one, or"
1291 " move the files"
1292 )
1293
1294 def context_keys(
1295 self, table: dict[str, Any], where: tuple[str, ...], provider: str
1296 ) -> tuple[dict[str, str], tuple[str, ...]]:
1297 """The context keys *table* provides, each to its type, and reads.
1298
1299 A key in both refuses, naming *provider* as who provides what a
1300 step reads.
1301 """
1302 provides = {
1303 str(key): str(kind) for key, kind in table.get("provides", {}).items()
1304 }
1305 reads = tuple(str(key) for key in table.get("reads", ()))
1306 both = sorted(set(provides) & set(reads))
1307 if both:
1308 raise self.refuse(
1309 (*where, "reads"),
1310 f"names {', '.join(both)}, which its provides names too; a step"
1311 f" reads what {provider} provides",
1312 )
1313 return provides, reads
1314
1315 def answers(
1316 self, data: dict[str, Any], prefix: tuple[str, ...]
1317 ) -> dict[str, Reference | DeclaredValue]:
1318 """The queries *data*'s ``[queries]`` table answers, each to its answer.
1319
1320 Under a ``[for.<target>]`` table, *prefix*, a table that declares
1321 a query refuses: a declaration holds whatever is listed, so it
1322 belongs to the file's top level.
1323 """
1324 from livery.workshop._contract_keys import shown
1325
1326 found: dict[str, Reference | DeclaredValue] = {}
1327 for name, value in data.get("queries", {}).items():
1328 if not _declares_query(value):
1329 found[str(name)] = self.query(str(name), value, prefix)
1330 elif prefix:
1331 raise self.refuse(
1332 (*prefix, "queries", str(name)),
1333 "declares a query, and a [for] table only answers one; declare"
1334 f" it at the top level, [{shown(('queries', str(name)))}]",
1335 )
1336 return found
1337
1338 def query(
1339 self, name: str, value: object, prefix: tuple[str, ...] = ()
1340 ) -> Reference | DeclaredValue:
1341 """The answer to the query *name*: a function, resolved, or a literal.
1342
1343 The name is a declared query. A workspace-level query is asked
1344 of every extension the workspace mounts, a package-level one of
1345 each extension a package's set holds, so any extension answers
1346 either. A literal answer is one of the query's values when it
1347 declares them. *prefix* is the ``[for.<target>]`` table the
1348 answer is under, empty for the top level.
1349 """
1350 where = (*prefix, "queries", name)
1351 spec = self.query_specs.get(name)
1352 if spec is None:
1353 near = difflib.get_close_matches(name, list(self.query_specs), n=1)
1354 hint = f"; did you mean {near[0]!r}?" if near else ""
1355 raise self.refuse(
1356 where,
1357 f"names no query; the queries are {', '.join(self.query_specs)}{hint}",
1358 )
1359 if isinstance(value, dict):
1360 table = cast("dict[str, Any]", value)
1361 if "value" not in table:
1362 raise self.refuse(
1363 where,
1364 "is a table without value; an answer is 'module:function', or"
1365 " a table with value alone",
1366 )
1367 held: object = table["value"]
1368 if spec.values is not None and held not in spec.values:
1369 listed = ", ".join(repr(known) for known in spec.values)
1370 raise self.refuse(
1371 (*where, "value"),
1372 f"is {held!r}; the query's values are {listed}",
1373 )
1374 return DeclaredValue(held)
1375 return self.reference(value, where)
1376
1377 def _input_entries(
1378 self,
1379 raw: list[Any],
1380 where: tuple[str, ...],
1381 *,
1382 allow_ignore: bool,
1383 ) -> tuple[InputEntry, ...]:
1384 """Parse and validate a ``reads`` or ``widens`` list of set entries."""
1385 from livery.workshop._categories import known_categories, known_channels
1386 from livery.workshop._influence import NAMED_SETS, InputEntry
1387
1388 categories = self.categories or known_categories()
1389 channels = known_channels()
1390 entries: list[InputEntry] = []
1391 for index, item in enumerate(raw):
1392 at = (*where[:-1], f"{where[-1]}[{index}]")
1393 if not isinstance(item, dict):1393 ↛ 1394line 1393 didn't jump to line 1394 because the condition on line 1393 was never true
1394 raise self.refuse(
1395 at, "is not a table naming a category, channel or set"
1396 )
1397 keys = [key for key in ("category", "channel", "set") if key in item]
1398 if len(keys) != 1:
1399 raise self.refuse(
1400 at,
1401 "names "
1402 + (
1403 "none of category, channel or set"
1404 if not keys
1405 else f"both {' and '.join(keys)}"
1406 )
1407 + ": name exactly one",
1408 )
1409 category = str(item.get("category", ""))
1410 channel = str(item.get("channel", ""))
1411 named_set = str(item.get("set", ""))
1412 if named_set and named_set not in NAMED_SETS:
1413 listed = ", ".join(sorted(NAMED_SETS))
1414 raise self.refuse(
1415 at,
1416 f"names unknown set {named_set!r}; the named sets are {listed}",
1417 )
1418 if category and category not in categories:
1419 listed = ", ".join(sorted(categories))
1420 raise self.refuse(
1421 at,
1422 f"names unknown category {category!r}; known categories: {listed}",
1423 )
1424 if channel and channel not in channels:
1425 listed = ", ".join(sorted(channels))
1426 raise self.refuse(
1427 at,
1428 f"names unknown channel {channel!r}; known channels: {listed}",
1429 )
1430 suffixes = tuple(str(s) for s in item.get("suffixes", ()))
1431 for suffix in suffixes:
1432 if not suffix.startswith("."):1432 ↛ 1433line 1432 didn't jump to line 1433 because the condition on line 1432 was never true
1433 raise self.refuse(
1434 at,
1435 f"names suffix {suffix!r}; a suffix starts with a dot,"
1436 f" {'.' + suffix!r}",
1437 )
1438 ignore = tuple(str(code) for code in item.get("ignore", ()))
1439 if ignore and (not allow_ignore or not category):
1440 raise self.refuse(at, "sets ignore outside a category entry of reads")
1441 entries.append(
1442 InputEntry(
1443 category=category,
1444 channel=channel,
1445 set=named_set,
1446 suffixes=suffixes,
1447 ignore=ignore,
1448 )
1449 )
1450 return tuple(entries)
1451
1452 def inputs(self, table: dict[str, Any], where: tuple[str, ...]) -> Inputs:
1453 """The file sets a step or CI job reads and widens on, from ``inputs``."""
1454 from livery.workshop._influence import Inputs
1455
1456 if "reads" not in table:
1457 raise self.refuse(where, "names no reads: inputs name the files it reads")
1458 return Inputs(
1459 reads=self._input_entries(
1460 table["reads"], (*where, "reads"), allow_ignore=True
1461 ),
1462 per_file=bool(table.get("per-file", True)),
1463 widens=self._input_entries(
1464 table.get("widens", []), (*where, "widens"), allow_ignore=False
1465 ),
1466 on_removal=bool(table.get("on-removal", False)),
1467 widen=self.reference(table["widen"], (*where, "widen"))
1468 if "widen" in table
1469 else None,
1470 )
1471
1472 def reference(self, text: object, where: tuple[str, ...]) -> Reference:
1473 """The reference *text* spells, resolved against the package's sources."""
1474 module, colon, name = str(text).partition(":")
1475 if not colon or not module or not name.isidentifier():
1476 raise self.refuse(where, f"is {text!r}; a reference is 'module:function'")
1477 if module != self.package and not module.startswith(f"{self.package}."):
1478 raise self.refuse(
1479 where,
1480 f"names {module}, outside the extension's package {self.package};"
1481 " a reference names the extension's own code",
1482 )
1483 source = self.source(module)
1484 if source is None:
1485 raise self.refuse(
1486 where, f"names {module}, which {self.package} does not contain"
1487 )
1488 defined = top_level_names(source)
1489 if name not in defined:
1490 near = difflib.get_close_matches(name, sorted(defined), n=1)
1491 hint = f"; did you mean {near[0]!r}?" if near else ""
1492 raise self.refuse(
1493 where,
1494 f"names {name}, which {module} does not define at its top level{hint}",
1495 )
1496 return Reference(module, name)
1497
1498 def source(self, module: str) -> Path | None:
1499 """*module*'s source file beside the declaration; None when it is absent."""
1500 parts = [part for part in module[len(self.package) :].split(".") if part]
1501 base = self.path.parent.joinpath(*parts)
1502 candidates = [base / "__init__.py"]
1503 if parts:1503 ↛ 1505line 1503 didn't jump to line 1505 because the condition on line 1503 was always true
1504 candidates.insert(0, base.with_suffix(".py"))
1505 return next((path for path in candidates if path.is_file()), None)
1506
1507
1508#: The keys that declare a phase in its ``[phases.<phase>]`` table,
1509#: beside which a sub-table is a step.
1510_DECLARATION_KEYS = ("level", "gated", "after", "verb", "keys")
1511
1512
1513def phase_specs_of(
1514 data: dict[str, Any], path: Path, *, extension: str
1515) -> dict[str, PhaseSpec]:
1516 """The phases *data*'s ``[phases.<phase>]`` tables declare, judged, by name.
1517
1518 A table declares its phase when it carries ``level``, ``gated``,
1519 ``after``, ``verb`` or ``keys``; one that adds steps alone declares
1520 nothing. The same reader serves the base's contract file and an
1521 extension's declaration file, *extension* naming the declarer.
1522
1523 Raises:
1524 DeclarationError: when a declaration is off its shape: a level
1525 that is not ``package`` or ``workspace``, a key of a type
1526 no context value has, or a value of the wrong type.
1527 """
1528 from livery.workshop._contract_keys import shown
1529 from livery.workshop._phases import LEVELS, PACKAGE_LEVEL, TYPES, PhaseSpec
1530
1531 def refuse(where: tuple[str, ...], text: str) -> DeclarationError:
1532 return DeclarationError(f"{path}: {shown(where)} {text}")
1533
1534 found: dict[str, PhaseSpec] = {}
1535 phases = data.get("phases")
1536 if not isinstance(phases, dict):
1537 return found
1538 for name, table in cast("dict[str, Any]", phases).items():
1539 if not isinstance(table, dict):1539 ↛ 1540line 1539 didn't jump to line 1540 because the condition on line 1539 was never true
1540 continue
1541 entry = cast("dict[str, Any]", table)
1542 if not any(key in entry for key in _DECLARATION_KEYS):
1543 continue
1544 where = ("phases", name)
1545 level = entry.get("level", PACKAGE_LEVEL)
1546 if level not in LEVELS:
1547 raise refuse(
1548 (*where, "level"),
1549 f"is {level!r}; a phase runs at one of {', '.join(LEVELS)}",
1550 )
1551 for key in ("gated", "verb"):
1552 if not isinstance(entry.get(key, False), bool):
1553 raise refuse((*where, key), "is true or false")
1554 after = entry.get("after", [])
1555 if not isinstance(after, list) or not all(
1556 isinstance(item, str) for item in cast("list[object]", after)
1557 ):
1558 raise refuse((*where, "after"), "is a list of the phases this one follows")
1559 keys = entry.get("keys", {})
1560 if not isinstance(keys, dict):1560 ↛ 1561line 1560 didn't jump to line 1561 because the condition on line 1560 was never true
1561 raise refuse(
1562 (*where, "keys"), "is a table of the engine's keys, each to its type"
1563 )
1564 typed = cast("dict[str, Any]", keys)
1565 for key, kind in typed.items():
1566 if kind not in TYPES:
1567 raise refuse(
1568 (*where, "keys", key),
1569 f"is {kind!r}; a key's type is one of {', '.join(TYPES)}",
1570 )
1571 found[name] = PhaseSpec(
1572 name,
1573 keys={key: str(kind) for key, kind in typed.items()},
1574 level=str(level),
1575 gated=bool(entry.get("gated", False)),
1576 after=tuple(str(item) for item in cast("list[object]", after)),
1577 verb=bool(entry.get("verb", False)),
1578 extension=extension,
1579 )
1580 return found
1581
1582
1583def phase_declarations(extension: str, package: str) -> tuple[PhaseSpec, ...]:
1584 """The phases the declaration beside *package* declares, for *extension*.
1585
1586 Empty without a declaration file. Read without judging the rest of
1587 the file, and without importing anything, so every installed
1588 extension's phases are known before any declaration is judged.
1589
1590 Raises:
1591 DeclarationError: when the file does not parse or a phase's
1592 declaration is off its shape.
1593 """
1594 path = declaration_file(package)
1595 if path is None:1595 ↛ 1596line 1595 didn't jump to line 1596 because the condition on line 1595 was never true
1596 return ()
1597 data = _parsed(path, path.read_text("utf-8"))
1598 return tuple(phase_specs_of(data, path, extension=extension).values())
1599
1600
1601#: The keys that declare a query in its ``[queries.<name>]`` table.
1602_QUERY_KEYS = ("combine", "level", "default", "values")
1603
1604
1605def _declares_query(entry: object) -> bool:
1606 """Whether a ``[queries.<name>]`` entry declares the query, not answers it."""
1607 return isinstance(entry, dict) and any(
1608 key in cast("dict[str, Any]", entry) for key in _QUERY_KEYS
1609 )
1610
1611
1612def query_specs_of(
1613 data: dict[str, Any], path: Path, *, extension: str, package: str
1614) -> dict[str, QuerySpec]:
1615 """The queries *data*'s ``[queries.<name>]`` tables declare, judged, by name.
1616
1617 A table declares its query when it carries ``combine``, ``level``,
1618 ``default`` or ``values``; one carrying ``value`` answers a query
1619 instead. The same reader serves the base's contract file and an
1620 extension's declaration file, *extension* naming the declarer and
1621 *package* the package a ``combine`` function lives in.
1622
1623 Raises:
1624 DeclarationError: when a declaration is off its shape: a
1625 ``combine`` that is no rule and no reference, a level that
1626 is not ``package`` or ``workspace``, ``values`` that are no
1627 list, or a table that declares and answers at once.
1628 """
1629 from livery.workshop._queries import LEVELS, PACKAGE_LEVEL, RULES, UNION, QuerySpec
1630
1631 reader = _Reader(extension, package, path)
1632 found: dict[str, QuerySpec] = {}
1633 queries = data.get("queries")
1634 if not isinstance(queries, dict):
1635 return found
1636 for name, table in cast("dict[str, Any]", queries).items():
1637 if not _declares_query(table):
1638 continue
1639 entry = cast("dict[str, Any]", table)
1640 where = ("queries", name)
1641 if "value" in entry:
1642 raise reader.refuse(
1643 where,
1644 "declares the query and answers it in one table; a declaration"
1645 " takes default for the answer while nobody answers",
1646 )
1647 rule = entry.get("combine", UNION)
1648 if isinstance(rule, str) and rule in RULES:
1649 combine: str | Reference = rule
1650 elif isinstance(rule, str) and ":" in rule:
1651 combine = reader.reference(rule, (*where, "combine"))
1652 else:
1653 rules = ", ".join(repr(known) for known in RULES)
1654 raise reader.refuse(
1655 (*where, "combine"),
1656 f"is {rule!r}; a query combines its answers by {rules}, or a"
1657 " function 'module:name'",
1658 )
1659 level = entry.get("level", PACKAGE_LEVEL)
1660 if level not in LEVELS:
1661 raise reader.refuse(
1662 (*where, "level"),
1663 f"is {level!r}; a query is asked at one of {', '.join(LEVELS)}",
1664 )
1665 values = entry.get("values")
1666 if values is not None and not isinstance(values, list):
1667 raise reader.refuse(
1668 (*where, "values"), "is a list of the answers the query takes"
1669 )
1670 found[name] = QuerySpec(
1671 name,
1672 combine,
1673 level=str(level),
1674 default=entry.get("default"),
1675 values=tuple(cast("list[object]", values)) if values is not None else None,
1676 extension=extension,
1677 )
1678 return found
1679
1680
1681def query_declarations(extension: str, package: str) -> tuple[QuerySpec, ...]:
1682 """The queries the declaration beside *package* declares, for *extension*.
1683
1684 Empty without a declaration file. Read without judging the rest of
1685 the file, and without importing anything, so every installed
1686 extension's queries are known before any declaration is judged.
1687
1688 Raises:
1689 DeclarationError: when the file does not parse or a query's
1690 declaration is off its shape.
1691 """
1692 path = declaration_file(package)
1693 if path is None:1693 ↛ 1694line 1693 didn't jump to line 1694 because the condition on line 1693 was never true
1694 return ()
1695 data = _parsed(path, path.read_text("utf-8"))
1696 return tuple(
1697 query_specs_of(data, path, extension=extension, package=package).values()
1698 )
1699
1700
1701#: A template's name: the last word of its verb, ``fm new.package.<name>``.
1702_TEMPLATE_NAME = re.compile(r"[a-z][a-z0-9-]*")
1703
1704#: The keys a ``[templates.<name>]`` table takes.
1705_TEMPLATE_KEYS = ("doc", "extensions", "extends", "options", "fixes")
1706
1707#: The keys a ``[templates.<name>.options.<option>]`` table takes.
1708_OPTION_KEYS = ("doc", "choices", "type", "default")
1709
1710#: The types a template's option takes in place of choices, each to the
1711#: Python type of its answer.
1712OPTION_TYPES: dict[str, type] = {"str": str, "int": int, "bool": bool}
1713
1714#: The option names a template's verb cannot take, each to the reason:
1715#: the verb's positional, and the flag footman reads on every line.
1716_TAKEN_OPTIONS = {
1717 "name": "the package's name, the word every template's verb takes first",
1718 "help": "footman's own flag, which shows the verb's help on any line",
1719}
1720
1721Answer = str | int | bool
1722"""The answer to a template's option: a string, an integer or a boolean."""
1723
1724
1725@dataclass(frozen=True)
1726class TemplateOption:
1727 """A creation option: a ``[templates.<name>.options.<option>]`` table.
1728
1729 ``fm new.package.<template> <name> --<option>=<answer>`` answers it,
1730 and the answer renders the template's files as the variable
1731 `variable`. A template that extends this one's template takes the
1732 option too, unless it fixes the answer under ``fixes``.
1733
1734 Attributes:
1735 name: The option's name on the command line, in kebab-case.
1736 doc: One line saying what the answer decides.
1737 choices: The answers it takes; empty for an option with a type.
1738 type: The type of its answer, ``str``, ``int`` or ``bool``;
1739 ``str`` for an option with choices.
1740 default: The answer when the command line gives none; None for
1741 a required option.
1742 """
1743
1744 name: str
1745 doc: str
1746 choices: tuple[str, ...]
1747 type: str
1748 default: Answer | None
1749
1750 @property
1751 def variable(self) -> str:
1752 """The template variable the answer renders as: the name, snake-cased."""
1753 return self.name.replace("-", "_")
1754
1755 @property
1756 def required(self) -> bool:
1757 """Whether a birth needs an answer: an option without a default does."""
1758 return self.default is None
1759
1760 def refusal(self, answer: object) -> str:
1761 """Why *answer* does not answer this option; empty when it does."""
1762 if self.choices:
1763 if answer in self.choices:
1764 return ""
1765 return (
1766 f"--{self.name} is {answer!r}, which is not one of its choices:"
1767 f" {', '.join(self.choices)}"
1768 )
1769 wanted = OPTION_TYPES[self.type]
1770 if isinstance(answer, wanted) and (wanted is bool or type(answer) is not bool):
1771 return ""
1772 return f"--{self.name} is {answer!r}, which is no {self.type}"
1773
1774
1775@dataclass(frozen=True)
1776class DeclaredTemplate:
1777 """A template a declaration file declares under ``[templates.<name>]``.
1778
1779 ``fm new.package.<name> <package>`` creates a package from it: the
1780 files of the template it extends first, then its own, which live
1781 under ``content/templates/<name>/`` beside the file that declares it.
1782
1783 Attributes:
1784 name: The template's name, the last word of its verb.
1785 extension: The extension that declares it, or the base.
1786 doc: One line saying what a package born from it is.
1787 extensions: The extensions a package born from it lists.
1788 extends: The template whose files a birth writes first; empty
1789 for none.
1790 path: The file that declares it.
1791 options: The creation options it declares beside those of the
1792 templates it extends.
1793 fixes: Each option of a template it extends to the answer it
1794 gives it, in declaration order: a birth from this template
1795 takes no answer for it.
1796 """
1797
1798 name: str
1799 extension: str
1800 doc: str
1801 extensions: tuple[str, ...]
1802 extends: str
1803 path: Path
1804 options: tuple[TemplateOption, ...] = ()
1805 fixes: tuple[tuple[str, Answer], ...] = ()
1806
1807
1808def _option_specs(
1809 reader: _Reader, where: tuple[str, ...], table: object
1810) -> tuple[TemplateOption, ...]:
1811 """The options a template's ``options`` table declares, judged.
1812
1813 Raises:
1814 DeclarationError: for an option off its shape: a name that is not
1815 kebab-case, or that is a Python keyword as a variable, or that
1816 the template's verb takes for itself, a key it
1817 does not take, a missing or blank ``doc``, ``choices`` and
1818 ``type`` both or neither, choices that are not distinct
1819 strings, a type outside ``OPTION_TYPES``, and a ``default``
1820 that does not answer the option.
1821 """
1822 if table is None:
1823 return ()
1824 if not isinstance(table, dict):1824 ↛ 1825line 1824 didn't jump to line 1825 because the condition on line 1824 was never true
1825 raise reader.refuse(
1826 (*where, "options"),
1827 "is a table of the template's creation options, each"
1828 " [templates.<name>.options.<option>]",
1829 )
1830 found: list[TemplateOption] = []
1831 for name, spec in cast("dict[str, Any]", table).items():
1832 at = (*where, "options", name)
1833 if not _TEMPLATE_NAME.fullmatch(name):
1834 raise reader.refuse(
1835 at,
1836 "is no option name: lower-case letters, digits and hyphens,"
1837 " starting with a letter, as --<option> spells it",
1838 )
1839 if keyword.iskeyword(name.replace("-", "_")):
1840 raise reader.refuse(
1841 at,
1842 "is a Python keyword once its hyphens are underscores, which"
1843 " the template variable it renders as cannot be",
1844 )
1845 if name in _TAKEN_OPTIONS:
1846 raise reader.refuse(
1847 at,
1848 f"is taken: --{name} is {_TAKEN_OPTIONS[name]}; rename the option",
1849 )
1850 if not isinstance(spec, dict):1850 ↛ 1851line 1850 didn't jump to line 1851 because the condition on line 1850 was never true
1851 raise reader.refuse(at, "is a table: doc, choices or type, and default")
1852 entry = cast("dict[str, Any]", spec)
1853 for key in entry:
1854 if key not in _OPTION_KEYS:1854 ↛ 1855line 1854 didn't jump to line 1855 because the condition on line 1854 was never true
1855 raise reader.refuse(
1856 (*at, key),
1857 "is not a key of a template's option: it takes doc, choices,"
1858 " type and default",
1859 )
1860 doc = entry.get("doc")
1861 if not isinstance(doc, str) or not doc.strip():
1862 raise reader.refuse(
1863 (*at, "doc"),
1864 "is one line of text saying what the answer decides, which"
1865 " the template's verb shows in its help and completion",
1866 )
1867 choices = entry.get("choices")
1868 kind = entry.get("type")
1869 if (choices is None) == (kind is None):
1870 raise reader.refuse(
1871 at,
1872 "takes choices, the answers it takes, or type, one of"
1873 f" {', '.join(OPTION_TYPES)}: one of the two",
1874 )
1875 answer_type = "str"
1876 if choices is not None:
1877 listed = cast("list[object]", choices) if isinstance(choices, list) else []
1878 if (
1879 not listed
1880 or not all(isinstance(item, str) and item for item in listed)
1881 or len(set(map(str, listed))) != len(listed)
1882 ):
1883 raise reader.refuse(
1884 (*at, "choices"), "is a list of the answers it takes, each once"
1885 )
1886 elif isinstance(kind, str) and kind in OPTION_TYPES:1886 ↛ 1889line 1886 didn't jump to line 1889 because the condition on line 1886 was always true
1887 answer_type = kind
1888 else:
1889 raise reader.refuse((*at, "type"), f"is one of {', '.join(OPTION_TYPES)}")
1890 option = TemplateOption(
1891 name,
1892 doc.strip(),
1893 tuple(cast("list[str]", choices or [])),
1894 answer_type,
1895 None,
1896 )
1897 if "default" in entry:
1898 default: object = entry["default"]
1899 if refusal := option.refusal(default):
1900 raise reader.refuse((*at, "default"), f"does not answer it: {refusal}")
1901 option = TemplateOption(
1902 option.name,
1903 option.doc,
1904 option.choices,
1905 option.type,
1906 cast("Answer", default),
1907 )
1908 found.append(option)
1909 return tuple(found)
1910
1911
1912def _fix_specs(
1913 reader: _Reader, where: tuple[str, ...], table: object
1914) -> tuple[tuple[str, Answer], ...]:
1915 """The answers a template's ``fixes`` table gives, judged.
1916
1917 Raises:
1918 DeclarationError: for a ``fixes`` that is not a table of option
1919 names to answers.
1920 """
1921 if table is None:
1922 return ()
1923 if not isinstance(table, dict):1923 ↛ 1924line 1923 didn't jump to line 1924 because the condition on line 1923 was never true
1924 raise reader.refuse(
1925 (*where, "fixes"),
1926 "is a table: each option of a template this one extends, to the"
1927 " answer a package born from this one takes",
1928 )
1929 found: list[tuple[str, Answer]] = []
1930 for name, answer in cast("dict[str, Any]", table).items():
1931 if not isinstance(answer, str | int | bool):1931 ↛ 1932line 1931 didn't jump to line 1932 because the condition on line 1931 was never true
1932 raise reader.refuse(
1933 (*where, "fixes", name),
1934 "is an answer: a string, an integer or a boolean",
1935 )
1936 found.append((name, answer))
1937 return tuple(found)
1938
1939
1940def template_specs_of(
1941 data: dict[str, Any], path: Path, *, extension: str
1942) -> dict[str, DeclaredTemplate]:
1943 """The templates *data*'s ``[templates.<name>]`` tables declare, judged, by name.
1944
1945 The same reader serves the base's contract file and an extension's
1946 declaration file, *extension* naming the declarer. ``doc`` and
1947 ``extensions`` are required; ``extends``, ``options`` and ``fixes``
1948 are optional, and a table takes nothing else.
1949
1950 Raises:
1951 DeclarationError: when a template is off its shape: a name that
1952 is not lower-case letters, digits and hyphens, a key it does
1953 not take, a missing ``doc`` or ``extensions``, a value of the
1954 wrong type, or an option or a fixed answer off its shape.
1955 """
1956 reader = _Reader(extension, extension, path)
1957 found: dict[str, DeclaredTemplate] = {}
1958 templates = data.get("templates")
1959 if templates is None:
1960 return found
1961 if not isinstance(templates, dict):1961 ↛ 1962line 1961 didn't jump to line 1962 because the condition on line 1961 was never true
1962 raise reader.refuse(
1963 ("templates",), "is a table of templates, each [templates.<name>]"
1964 )
1965 for name, table in cast("dict[str, Any]", templates).items():
1966 where = ("templates", name)
1967 if not _TEMPLATE_NAME.fullmatch(name):
1968 raise reader.refuse(
1969 where,
1970 "is no template name: lower-case letters, digits and hyphens,"
1971 " starting with a letter, as fm new.package.<template> spells it",
1972 )
1973 if not isinstance(table, dict):1973 ↛ 1974line 1973 didn't jump to line 1974 because the condition on line 1973 was never true
1974 raise reader.refuse(
1975 where, "is a table: doc, extensions, extends, options and fixes"
1976 )
1977 entry = cast("dict[str, Any]", table)
1978 for key in entry:
1979 if key not in _TEMPLATE_KEYS:1979 ↛ 1980line 1979 didn't jump to line 1980 because the condition on line 1979 was never true
1980 raise reader.refuse(
1981 (*where, key),
1982 "is not a key of a template: it takes doc, extensions,"
1983 " extends, options and fixes",
1984 )
1985 doc = entry.get("doc")
1986 if doc is None:
1987 raise reader.refuse(
1988 (*where, "doc"),
1989 "is missing: one line saying what a package born from the"
1990 " template is, which the template's verb shows as its help",
1991 )
1992 if not isinstance(doc, str) or not doc.strip():1992 ↛ 1993line 1992 didn't jump to line 1993 because the condition on line 1992 was never true
1993 raise reader.refuse(
1994 (*where, "doc"),
1995 "is one line of text saying what a package born from the template is",
1996 )
1997 listed = entry.get("extensions")
1998 if listed is None:
1999 raise reader.refuse(
2000 (*where, "extensions"),
2001 "is missing: the extensions a package born from the template"
2002 " lists, [] for none",
2003 )
2004 if not isinstance(listed, list) or not all(2004 ↛ 2007line 2004 didn't jump to line 2007 because the condition on line 2004 was never true
2005 isinstance(item, str) for item in cast("list[object]", listed)
2006 ):
2007 raise reader.refuse((*where, "extensions"), "is a list of extensions")
2008 extends = entry.get("extends", "")
2009 if not isinstance(extends, str):2009 ↛ 2010line 2009 didn't jump to line 2010 because the condition on line 2009 was never true
2010 raise reader.refuse((*where, "extends"), "is a template's name")
2011 found[name] = DeclaredTemplate(
2012 name,
2013 extension,
2014 doc.strip(),
2015 tuple(cast("list[str]", listed)),
2016 extends,
2017 path,
2018 _option_specs(reader, where, entry.get("options")),
2019 _fix_specs(reader, where, entry.get("fixes")),
2020 )
2021 return found
2022
2023
2024def template_declarations(extension: str, package: str) -> tuple[DeclaredTemplate, ...]:
2025 """The templates the declaration beside *package* declares, for *extension*.
2026
2027 Empty without a declaration file. Read without judging the rest of
2028 the file, and without importing anything, so an installed
2029 extension's templates are known whether a workspace lists it or not.
2030
2031 Raises:
2032 DeclarationError: when the file does not parse or a template is
2033 off its shape.
2034 """
2035 path = declaration_file(package)
2036 if path is None:2036 ↛ 2037line 2036 didn't jump to line 2037 because the condition on line 2036 was never true
2037 return ()
2038 data = _parsed(path, path.read_text("utf-8"))
2039 return tuple(template_specs_of(data, path, extension=extension).values())
2040
2041
2042def _known_queries(own: dict[str, QuerySpec], path: Path) -> dict[str, QuerySpec]:
2043 """Every declared query an answer in a file may name: the installed ones and *own*.
2044
2045 Raises:
2046 DeclarationError: when *own* declares a query another extension
2047 declares.
2048 """
2049 from livery.workshop import _queries
2050 from livery.workshop._contract_keys import shown
2051
2052 known = dict(_queries.declared_queries())
2053 for name, spec in own.items():
2054 held = known.get(name)
2055 if held is not None and held.extension != spec.extension:
2056 raise DeclarationError(
2057 f"{path}: {shown(('queries', name))} declares the {name} query, which"
2058 f" {held.extension} declares; one extension declares a query"
2059 )
2060 known[name] = spec
2061 return known
2062
2063
2064def _known_phases(own: dict[str, PhaseSpec], path: Path) -> dict[str, PhaseSpec]:
2065 """Every declared phase a file may name: the installed declarations' and *own*.
2066
2067 Raises:
2068 DeclarationError: when *own* declares a phase another extension
2069 declares.
2070 """
2071 from livery.workshop import _phases
2072
2073 known = dict(_phases.declared_phases())
2074 for name, spec in own.items():
2075 held = known.get(name)
2076 if held is not None and held.extension != spec.extension:2076 ↛ 2077line 2076 didn't jump to line 2077 because the condition on line 2076 was never true
2077 raise DeclarationError(
2078 f"{path}: phases.{name} declares the {name} phase, which"
2079 f" {held.extension} declares; one extension declares a phase"
2080 )
2081 known[name] = spec
2082 return known
2083
2084
2085def _step_tables(table: dict[str, Any]) -> dict[str, dict[str, Any]]:
2086 """The steps under a phase's table: its sub-tables beside the declaration keys."""
2087 return {
2088 key: cast("dict[str, Any]", value)
2089 for key, value in table.items()
2090 if key not in _DECLARATION_KEYS and isinstance(value, dict)
2091 }
2092
2093
2094def _step_address(text: str) -> bool:
2095 """Whether *text* is ``<owner>:<phase>.<step>``, its step one word."""
2096 owner, colon, address = text.partition(":")
2097 phase, dot, step = address.partition(".")
2098 return bool(owner and colon and phase and dot and step) and "." not in step
2099
2100
2101def installed_steps() -> dict[str, str]:
2102 """Every installed step, ``<owner>:<phase>.<step>``, to the scope it runs at.
2103
2104 The base's own steps, then each installed extension's
2105 ``[phases.<phase>.<step>]`` tables, its ``[for.<target>]`` tables'
2106 among them, read without judging the rest of the file and without
2107 importing anything. A step of a package-level phase runs once per
2108 package; a step of a workspace-level phase at the scope its table
2109 names, the workspace when it names none.
2110
2111 Raises:
2112 DeclarationError: when a declaration file does not parse.
2113 """
2114 from livery.footman import installed_entry_points
2115 from livery.workshop._phases import PACKAGE_LEVEL, declared_phases
2116 from livery.workshop._steps import PACKAGE, WORKSPACE, snapshot
2117
2118 builtin = snapshot(initial=True)
2119 found = {
2120 f"{record.extension}:{record.name}": record.scope for record in builtin.values()
2121 }
2122 phases = declared_phases()
2123 for entry in installed_entry_points("workshop.extensions"):
2124 path = declaration_file(entry.value.partition(":")[0])
2125 if path is None:2125 ↛ 2126line 2125 didn't jump to line 2126 because the condition on line 2125 was never true
2126 continue
2127 data = _parsed(path, path.read_text("utf-8"))
2128 targets = data.get("for", {})
2129 tables = [data]
2130 if isinstance(targets, dict):2130 ↛ 2136line 2130 didn't jump to line 2136 because the condition on line 2130 was always true
2131 tables += [
2132 cast("dict[str, Any]", table)
2133 for table in cast("dict[str, Any]", targets).values()
2134 if isinstance(table, dict)
2135 ]
2136 for table in tables:
2137 held = table.get("phases", {})
2138 if not isinstance(held, dict):2138 ↛ 2139line 2138 didn't jump to line 2139 because the condition on line 2138 was never true
2139 continue
2140 for phase, steps in cast("dict[str, Any]", held).items():
2141 if not isinstance(steps, dict):2141 ↛ 2142line 2141 didn't jump to line 2142 because the condition on line 2141 was never true
2142 continue
2143 spec = phases.get(phase)
2144 per_package = spec is not None and spec.level == PACKAGE_LEVEL
2145 for step, declared in _step_tables(
2146 cast("dict[str, Any]", steps)
2147 ).items():
2148 scope = (
2149 PACKAGE
2150 if per_package
2151 else str(declared.get("scope", WORKSPACE))
2152 )
2153 found[f"{entry.name}:{phase}.{step}"] = scope
2154 return found
2155
2156
2157_DEFINED: dict[tuple[Path, str], frozenset[str]] = {}
2158
2159
2160def top_level_names(path: Path) -> frozenset[str]:
2161 """The names *path*'s module defines at its top level, read from its source.
2162
2163 Its functions, classes, assignments and imports, those inside a
2164 top-level ``if`` or ``try`` among them. Parsed once per content.
2165 """
2166 text = path.read_text("utf-8")
2167 key = (path, text)
2168 found = _DEFINED.get(key)
2169 if found is None:
2170 tree = ast.parse(text, filename=str(path))
2171 found = frozenset(_defined(tree.body))
2172 _DEFINED[key] = found
2173 return found
2174
2175
2176def _defined(body: list[ast.stmt]) -> set[str]:
2177 names: set[str] = set()
2178 for node in body:
2179 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
2180 names.add(node.name)
2181 elif isinstance(node, ast.Assign):
2182 for target in node.targets:
2183 names |= {n.id for n in ast.walk(target) if isinstance(n, ast.Name)}
2184 elif isinstance(node, (ast.AnnAssign, ast.AugAssign)) and isinstance(
2185 node.target, ast.Name
2186 ):
2187 names.add(node.target.id)
2188 elif isinstance(node, (ast.Import, ast.ImportFrom)):
2189 names |= {
2190 alias.asname or alias.name.partition(".")[0] for alias in node.names
2191 }
2192 elif isinstance(node, ast.If):
2193 names |= _defined(node.body) | _defined(node.orelse)
2194 elif isinstance(node, ast.Try):2194 ↛ 2195line 2194 didn't jump to line 2195 because the condition on line 2194 was never true
2195 names |= _defined(node.body) | _defined(node.orelse)
2196 for handler in node.handlers:
2197 names |= _defined(handler.body)
2198 return names
2199
2200
2201def defined_tasks(directory: Path) -> frozenset[str]:
2202 """The tasks the modules under *directory* define, ``<group>.<task>``, read by AST.
2203
2204 The names `task_docs` reads, without their doc lines.
2205 """
2206 return frozenset(task_docs(directory))
2207
2208
2209def task_docs(directory: Path) -> dict[str, str]:
2210 """Each task the modules under *directory* define to its doc line, read by AST.
2211
2212 A task is named ``<group>.<task>``. Its doc line is the first line
2213 of the function's docstring, which footman shows as the verb's
2214 help; empty for a function without one. A module-level
2215 ``<name> = group("<group>")`` defines a group, and
2216 ``<name> = <parent>.group("<sub>")`` one beneath another. A function
2217 decorated ``@<name>.task`` defines a task in that group, named by
2218 the decorator's ``name=`` or else as footman names it: the
2219 function's name, a trailing underscore dropped, underscores as
2220 dashes. A group another module defines is followed through
2221 ``from ... import``. Nothing is imported.
2222 """
2223 package = ".".join(directory.parts[-1:])
2224 modules: dict[str, ast.Module] = {}
2225 for path in sorted(directory.rglob("*.py")):
2226 relative = path.relative_to(directory).with_suffix("")
2227 dotted = ".".join(part for part in relative.parts if part != "__init__")
2228 modules[dotted] = ast.parse(path.read_text("utf-8"), filename=str(path))
2229 groups: dict[tuple[str, str], str] = {}
2230 for _round in range(2):
2231 for dotted, tree in modules.items():
2232 for node in tree.body:
2233 found = _group_assigned(node, dotted, groups)
2234 if found is not None:
2235 groups[(dotted, found[0])] = found[1]
2236 for dotted, tree in modules.items():
2237 for node in tree.body:
2238 if isinstance(node, ast.ImportFrom) and node.module is not None:
2239 source = node.module.rpartition(f"{package}.")[2]
2240 for alias in node.names:
2241 group = groups.get((source, alias.name))
2242 if group is not None:
2243 groups.setdefault((dotted, alias.asname or alias.name), group)
2244 tasks: dict[str, str] = {}
2245 for dotted, tree in modules.items():
2246 for node in tree.body:
2247 if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
2248 continue
2249 for decorator in node.decorator_list:
2250 call = decorator if isinstance(decorator, ast.Call) else None
2251 target = call.func if call is not None else decorator
2252 if not (
2253 isinstance(target, ast.Attribute)
2254 and target.attr == "task"
2255 and isinstance(target.value, ast.Name)
2256 ):
2257 continue
2258 group = groups.get((dotted, target.value.id))
2259 if group is None:2259 ↛ 2260line 2259 didn't jump to line 2260 because the condition on line 2259 was never true
2260 continue
2261 named = next(
2262 (
2263 keyword.value.value
2264 for keyword in (call.keywords if call is not None else ())
2265 if keyword.arg == "name"
2266 and isinstance(keyword.value, ast.Constant)
2267 and isinstance(keyword.value.value, str)
2268 ),
2269 node.name.rstrip("_").replace("_", "-"),
2270 )
2271 doc = (ast.get_docstring(node) or "").strip()
2272 tasks[f"{group}.{named}"] = doc.splitlines()[0] if doc else ""
2273 return tasks
2274
2275
2276def _group_assigned(
2277 node: ast.stmt, module: str, groups: dict[tuple[str, str], str]
2278) -> tuple[str, str] | None:
2279 """The variable and the group *node* assigns: ``group("x")``, ``<g>.group("y")``."""
2280 if not (
2281 isinstance(node, ast.Assign)
2282 and len(node.targets) == 1
2283 and isinstance(node.targets[0], ast.Name)
2284 and isinstance(node.value, ast.Call)
2285 and node.value.args
2286 and isinstance(node.value.args[0], ast.Constant)
2287 and isinstance(node.value.args[0].value, str)
2288 ):
2289 return None
2290 name = node.value.args[0].value
2291 func = node.value.func
2292 if isinstance(func, ast.Name) and func.id == "group":
2293 return node.targets[0].id, name
2294 if (
2295 isinstance(func, ast.Attribute)
2296 and func.attr == "group"
2297 and isinstance(func.value, ast.Name)
2298 and (module, func.value.id) in groups
2299 ):
2300 return node.targets[0].id, f"{groups[(module, func.value.id)]}.{name}"
2301 return None
2302
2303
2304def contract_keys(package: str) -> tuple[Declared, ...]:
2305 """The contract keys the declaration beside *package* owns; empty without one.
2306
2307 Read without judging the rest of the file, and without importing
2308 anything: the contract judge asks every installed extension.
2309
2310 Raises:
2311 DeclarationError: when the file does not parse or a key's
2312 declaration is malformed.
2313 """
2314 path = declaration_file(package)
2315 if path is None:
2316 return ()
2317 return contract_keys_of(_parsed(path, path.read_text("utf-8")), path)
2318
2319
2320def contract_keys_of(
2321 data: dict[str, Any], path: Path, *, contracts: tuple[str, ...] = CONTRACTS
2322) -> tuple[Declared, ...]:
2323 """The contract keys *data*'s ``[contract]`` tables declare, judged.
2324
2325 *contracts* are the contracts the file may declare keys in: a
2326 workspace's for an extension; the base's own file declares the keys
2327 of ``extension.toml`` as well.
2328 """
2329 found: list[Declared] = []
2330 for contract, table in data.get("contract", {}).items():
2331 if contract not in contracts:
2332 raise DeclarationError(
2333 f"{path}: [contract.{contract}] names no contract; an extension"
2334 f" declares keys in {', '.join(contracts)}"
2335 )
2336 found += _keys(cast("ContractKind", contract), table, (), path)
2337 return tuple(found)
2338
2339
2340#: The keys a contract key's own declaration holds. Under one of these
2341#: names a table is a key of its own, declared beneath: a query's
2342#: ``values`` is a key of ``extension.toml``, and its declaration is a
2343#: table.
2344_OWN = ("types", "values", "doc")
2345
2346
2347def _keys(
2348 contract: ContractKind, table: dict[str, Any], parts: tuple[str, ...], path: Path
2349) -> list[Declared]:
2350 from livery.workshop._contract_keys import TYPES, Declared
2351
2352 where = f"[contract.{contract}{''.join('.' + part for part in parts)}]"
2353 found: list[Declared] = []
2354 own = {key for key in _OWN if key in table and not isinstance(table[key], dict)}
2355 if own:
2356 types = table.get("types") if "types" in own else None
2357 if not (
2358 isinstance(types, list)
2359 and types
2360 and all(kind in TYPES for kind in cast("list[object]", types))
2361 ):
2362 raise DeclarationError(
2363 f"{path}: {where} types is {types!r}; it lists one or more of"
2364 f" {', '.join(TYPES)}"
2365 )
2366 values = table.get("values", []) if "values" in own else []
2367 doc = table.get("doc", "") if "doc" in own else ""
2368 if not isinstance(values, list) or not isinstance(doc, str):2368 ↛ 2369line 2368 didn't jump to line 2369 because the condition on line 2368 was never true
2369 raise DeclarationError(
2370 f"{path}: {where}: values is a list of strings, doc a string"
2371 )
2372 found.append(
2373 Declared(
2374 contract,
2375 ".".join(parts),
2376 cast(
2377 "tuple[Type, ...]",
2378 tuple(str(kind) for kind in cast("list[object]", types)),
2379 ),
2380 tuple(str(value) for value in cast("list[object]", values)),
2381 doc,
2382 )
2383 )
2384 for key, value in table.items():
2385 if key in own:
2386 continue
2387 if not isinstance(value, dict) or "." in key:2387 ↛ 2388line 2387 didn't jump to line 2388 because the condition on line 2387 was never true
2388 raise DeclarationError(
2389 f"{path}: {where} {key} is not a key's declaration; a key is a"
2390 " table with types, and values and doc where it has them"
2391 )
2392 found += _keys(contract, cast("dict[str, Any]", value), (*parts, key), path)
2393 return found