Coverage for packages/workshop/src/livery/workshop/_queries.py: 100%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, 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_guard.py, packages/workshop/tests/test_workshop_templates.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_shipped_files.py, packages/workshop/tests/test_workshop_shells.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_run.py, packages/workshop/tests/test_workshop_root_attribution.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_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_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_package_templates.py, packages/workshop/tests/test_workshop_package_level_fragments.py, packages/workshop/tests/test_workshop_new_project.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_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.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_cpp_kind.py, packages/workshop/tests/test_workshop_contributed_jobs.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_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_speed.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/python/tests/test_credential_traces.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.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_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"""Ask a typed question that extensions answer, combined by the query's declared rule.
2
3A query is declared, by the base in the ``[queries]`` section of its
4``contract.toml`` and by an extension under ``[queries.<name>]`` in its
5``extension.toml``, in one grammar ([livery.workshop._queries.QuerySpec][]):
6``combine``, how the answers make one, ``union``, ``nearest``, ``agreed``
7or a function ``module:name``; ``level``, ``package`` for a question
8about one package and ``workspace`` for one about the workspace;
9``default``, the answer while no extension answers; and ``values``, the
10only answers it takes. [livery.workshop._queries.declared_queries][] is
11every declared query by name, the base's and then each installed
12extension's; two extensions declaring one query refuse naming both.
13
14An extension answers a query under ``[queries]`` in its declaration
15file: ``<name> = "module:function"``, a function called with the
16package or the workspace root, or a literal, ``[queries.<name>] value``.
17It answers under ``[for.<target>.queries]`` the same way, and that
18answer is asked only while the target is listed and the extension's
19listing contributes to it, the rule
20[livery.workshop.contributions_for][] reads a target's tables by.
21[livery.workshop.answer][] asks a package's set, or the installed set,
22in composition order, and combines the answers by the query's rule. A
23handle, [livery.workshop.Query][], names a query and types its answer;
24the base's handles are the constants here, and an extension names its
25own with ``Query("docs.members")``.
26"""
27
28from __future__ import annotations
29
30import functools
31from collections.abc import Callable, Iterable, Mapping, Sequence
32from dataclasses import dataclass
33from pathlib import Path
34from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, cast
35
36if TYPE_CHECKING:
37 from livery.forge import Registry
38 from livery.git import Keyed, Series
39 from livery.workshop._composition import Lookup
40 from livery.workshop._declaration import Declaration, DeclaredValue, Reference
41 from livery.workshop._influence import Changes
42 from livery.workshop._packages import Package, SourceReferences
43
44T = TypeVar("T")
45T_co = TypeVar("T_co", covariant=True)
46
47#: The levels a query is asked at: about one package, or about the
48#: workspace.
49PACKAGE_LEVEL = "package"
50WORKSPACE_LEVEL = "workspace"
51LEVELS = (PACKAGE_LEVEL, WORKSPACE_LEVEL)
52
53#: The rules a query may combine its answers by, beside a function.
54UNION = "union"
55NEAREST = "nearest"
56AGREED = "agreed"
57
58#: The extension that declares the base's queries.
59BASE = "livery.workshop"
60
61#: How answers, by extension, make one answer; the lookup reads the
62#: declarations a rule needs, the requirements for ``nearest``.
63Combine = Callable[[Mapping[str, Any], "Lookup"], Any]
64
65
66class QueryError(RuntimeError):
67 """A query asked or answered in a way its declaration cannot take.
68
69 A name no extension declares, a question asked at the other level,
70 an answer off the query's values, or answers its rule cannot
71 combine; the message names the query and the extensions.
72 """
73
74
75@dataclass(frozen=True)
76class Query(Generic[T_co]):
77 """A handle naming a declared query, typed by its answer.
78
79 The handle is covariant in its answer: one typed by a tuple serves
80 a reader that takes any iterable.
81
82 Attributes:
83 name: The key an extension answers it under: ``public-modules``.
84 """
85
86 name: str
87
88
89@dataclass(frozen=True)
90class QuerySpec:
91 """A query as its declarer declares it: one ``[queries.<name>]`` table.
92
93 Attributes:
94 name: The key an extension answers it under: ``public-modules``.
95 combine: How the answers make one. ``union``: every item any
96 answer holds, once each, in the order first met, each
97 answer a list. ``nearest``: the answer of the one extension
98 no other answering one requires. ``agreed``: the one value
99 every answer that is not empty holds. Or a function, called
100 with the answers by extension and the declarations' lookup,
101 which raises [livery.workshop._queries.QueryError][] or
102 ``ValueError`` naming the extensions when the answers break
103 its rule.
104 level: ``package`` for a question about one package, asked with
105 the package and answered by its set in composition order;
106 ``workspace`` for one about the workspace, asked with its
107 root and answered by the installed set in composition order.
108 default: The answer while no extension answers; None takes the
109 rule's answer over no answers, an empty union, no nearest,
110 no agreement, a function's answer over nothing.
111 values: The only answers the query takes; None takes any.
112 extension: The extension that declares it; the base for its own.
113 """
114
115 name: str
116 combine: str | Reference = UNION
117 level: str = PACKAGE_LEVEL
118 default: object = None
119 values: tuple[object, ...] | None = None
120 extension: str = BASE
121
122
123def _union(answers: Mapping[str, Any], lookup: Lookup) -> tuple[Any, ...]:
124 """Every item any answer holds, once each, in the order first met."""
125 del lookup
126 found: dict[Any, None] = {}
127 for name, value in answers.items():
128 if isinstance(value, (str, bytes)) or not isinstance(value, Iterable):
129 raise QueryError(
130 f"{name} answers {value!r}, and a union combines lists; answer a list"
131 )
132 found.update(dict.fromkeys(value))
133 return tuple(found)
134
135
136def _agreed(answers: Mapping[str, Any], lookup: Lookup) -> Any:
137 """The one value every answer that is not empty holds; empty when none does."""
138 del lookup
139 named = {name: value for name, value in answers.items() if value}
140 if len({repr(value) for value in named.values()}) > 1:
141 listed = ", ".join(f"{name} {value!r}" for name, value in named.items())
142 raise QueryError(f"the answers differ, and they must agree: {listed}")
143 return next(iter(named.values()), "")
144
145
146def _nearest(answers: Mapping[str, Any], lookup: Lookup) -> Any:
147 """The answer of the one extension no other answering one requires.
148
149 Its answer is the nearest: it builds on the others. None when no
150 extension answers with a value.
151 """
152 from livery.workshop._composition import nearest_extensions
153
154 named = {name: value for name, value in answers.items() if value is not None}
155 nearest = nearest_extensions(named, lookup)
156 if len(nearest) > 1:
157 raise QueryError(
158 f"{' and '.join(nearest)} both answer, and neither requires the other;"
159 " one of them answers, or one requires the other"
160 )
161 return named[nearest[0]] if nearest else None
162
163
164def merged(answers: Mapping[str, Any], lookup: Lookup) -> Mapping[str, str]:
165 """Every name any answer holds, to its one value; a name valued twice refuses.
166
167 The rule of the ``requirements``, ``test-requirements`` and
168 ``job-built-members`` queries, which the base's contract file names.
169 """
170 del lookup
171 found: dict[str, str] = {}
172 by: dict[str, str] = {}
173 for name, value in answers.items():
174 for key, held in cast("Mapping[str, str]", value).items():
175 if key in found and found[key] != held:
176 raise QueryError(
177 f"{by[key]} answers {key} {found[key]!r} and {name} answers"
178 f" {held!r}; the answers name each entry once, or alike"
179 )
180 found[key] = held
181 by.setdefault(key, name)
182 return found
183
184
185def owned(answers: Mapping[str, Any], lookup: Lookup) -> tuple[str, ...]:
186 """Every item any answer holds; an item two extensions answer refuses.
187
188 The ``executables`` query's rule, which the base's contract file
189 names.
190 """
191 del lookup
192 owners: dict[str, str] = {}
193 for name, value in answers.items():
194 for item in cast("Iterable[str]", value):
195 if item in owners and owners[item] != name:
196 raise QueryError(
197 f"{owners[item]} and {name} both answer {item}; one extension"
198 " of a package answers each"
199 )
200 owners[item] = name
201 return tuple(owners)
202
203
204#: Each rule by its name in a declaration.
205RULES: Mapping[str, Combine] = {UNION: _union, NEAREST: _nearest, AGREED: _agreed}
206
207
208class RequirementWriter(Protocol):
209 """Write a package's requirement on a sibling into one ecosystem's manifest.
210
211 An extension answers the ``requirement-writers`` query with its
212 writers, and the ``test-requirement-writers`` query with the writers
213 of a requirement the package's tests alone have. Every writer of a
214 package's set is called for each requirement. A writer takes a
215 sibling of its own ecosystem alone: for any other sibling it writes
216 nothing and returns None, so the requirement lands in the manifest
217 of the sibling's ecosystem. A requirement no writer of the set
218 takes refuses, naming the sibling's set.
219 """
220
221 def __call__(
222 self, package: Package, dependency: Package, floor: str
223 ) -> list[str] | None:
224 """Write *dependency* at *floor* into *package*'s manifest.
225
226 Args:
227 package: The package whose manifest gains the requirement.
228 dependency: The sibling it requires.
229 floor: The lowest version of *dependency* the requirement
230 takes.
231
232 Returns:
233 The files changed, relative to the package; empty when the
234 manifest names *dependency* already. None for a sibling
235 outside the writer's ecosystem, which it leaves alone.
236 """
237 ...
238
239
240class Folder(Protocol):
241 """Fold one file a check leg's shards each left into the platform leg's one file.
242
243 An extension answers the ``ci.fold`` query with one folder per file
244 its leg entry leaves in the leg's spool, by the file's name. The
245 gate job calls it with the shards' files, in shard order, each as
246 the per-run ref holds it, and puts what it returns on the platform
247 leg's ref under the same name, where the judges read it as one
248 leg's file.
249 """
250
251 def __call__(self, shards: Sequence[Mapping[str, Any]]) -> Mapping[str, Any]:
252 """The one file of the platform leg, from *shards*' files.
253
254 Args:
255 shards: The file as each shard left it, in shard order.
256
257 Returns:
258 The folded file.
259
260 Raises:
261 ValueError: When the shards' files cannot be one leg's,
262 naming what differs; the fold is red with it.
263 """
264 ...
265
266
267#: The modules that declare the package's public API, by import path:
268#: what a type-completeness step verifies.
269PUBLIC_MODULES: Query[tuple[str, ...]] = Query("public-modules")
270
271#: Where the package's build writes its compilation database, which a
272#: tool such as clang-tidy reads.
273COMPILE_COMMANDS: Query[Path | None] = Query("compile-commands")
274
275#: The names other packages reference this one's code by.
276MODULE_ROOTS: Query[tuple[str, ...]] = Query("module-roots")
277
278#: What each of the package's sources references, one record per
279#: source, which the layering phase's rules over references read.
280REFERENCES: Query[tuple[SourceReferences, ...]] = Query("references")
281
282#: The version the package's own manifests declare.
283CURRENT_VERSION: Query[str] = Query("current-version")
284
285#: Every file the ``stamp`` phase may write a version into, so a caller
286#: can keep and restore them.
287VERSION_FILES: Query[tuple[Path, ...]] = Query("version-files")
288
289#: What the package's native manifests require, each distribution's name
290#: to its constraint.
291REQUIREMENTS: Query[Mapping[str, str]] = Query("requirements")
292
293#: The writers of a requirement on a sibling into the package's native
294#: manifests, each for a sibling of its own ecosystem; every one is called.
295REQUIREMENT_WRITERS: Query[tuple[RequirementWriter, ...]] = Query("requirement-writers")
296
297#: What the package's native manifests require for its tests alone, each
298#: distribution's name to its constraint. A package whose set answers it
299#: has a home for its test edges.
300TEST_REQUIREMENTS: Query[Mapping[str, str]] = Query("test-requirements")
301
302#: The writers of a test requirement on a sibling into the package's
303#: native manifests, each for a sibling of its own ecosystem; every one is
304#: called.
305TEST_REQUIREMENT_WRITERS: Query[tuple[RequirementWriter, ...]] = Query(
306 "test-requirement-writers"
307)
308
309#: The distributions the package releases, each as its ecosystem and its
310#: name.
311DISTRIBUTIONS: Query[tuple[tuple[str, str], ...]] = Query("distributions")
312
313#: The registry the package releases to, as a probe of the versions it
314#: serves, which the release train polls until an upload is served; an
315#: empty answer when no extension of the package's set releases it.
316REGISTRY: Query[Registry | None] = Query("registry")
317
318#: The executables ``fm run`` may start, by name.
319EXECUTABLES: Query[tuple[str, ...]] = Query("executables")
320
321#: What the host must provide for the package and no store installs,
322#: such as a C compiler, each by the name it resolves by on ``PATH``.
323HOST_TOOLS: Query[tuple[str, ...]] = Query("host-tools")
324
325#: The marketplace ids of the editor extensions the listed extensions
326#: recommend, which the rendered ``.vscode/extensions.json`` lists.
327EDITOR_EXTENSIONS: Query[tuple[str, ...]] = Query("editor-extensions")
328
329#: The state store's series the listed extensions keep beside the
330#: base's own, which the janitor bounds and ``fm store.ls`` lists.
331STORE_SERIES: Query[tuple[Series | Keyed, ...]] = Query("store.series")
332
333#: The members a job of the release point builds before the wave, each
334#: member's path (``packages/<member>``) to the job's name: the wave
335#: publishes what the run collected for them, and the entry installs
336#: those of them uv installs after the tools.
337JOB_BUILT_MEMBERS: Query[Mapping[str, str]] = Query("job-built-members")
338
339#: The inputs the listed extensions add to the checkout step of the
340#: rendered GitHub and Gitea workflows, each name to its value.
341CHECKOUT_INPUTS: Query[Mapping[str, str]] = Query("checkout-inputs")
342
343#: How the gate job folds a file a check leg's shards each left into the
344#: platform leg's one file, by the file's name: one folder per file the
345#: listed extensions' leg entries leave. A file two extensions fold
346#: refuses; a file nobody folds is red by name in the fold.
347FOLDERS: Query[Mapping[str, Folder]] = Query("ci.fold")
348
349#: What test items each package holds for a shardable test step, by step
350#: name: each callable takes a [livery.workshop.Package][] and returns
351#: sorted root-relative test item paths. Used by ``fm ci.legs`` to size
352#: shards to the selected items without naming any test runner in the base.
353TEST_ITEMS: Query[Mapping[str, Callable[[Package], tuple[str, ...]]]] = Query(
354 "ci.test-items"
355)
356
357#: What one answer to `REACHES` says of a change: each changed path it
358#: widens, to why it widens and the paths of the members it reaches.
359Reached = Mapping[str, tuple[str, tuple[str, ...]]]
360
361#: What a change reaches beyond its own packages and their dependents:
362#: the functions the listed extensions answer with, each called with the
363#: run's [livery.workshop.Changes][]. The affected engine
364#: ([livery.workshop._graph.affected_from_paths][]) runs every member
365#: they name, with its dependents.
366REACHES: Query[tuple[Callable[[Changes], Reached], ...]] = Query("reaches")
367
368
369@functools.cache
370def base_queries() -> dict[str, QuerySpec]:
371 """The base's queries, read from the ``[queries]`` section of its contract file.
372
373 In the file's order, each spec naming the base as its declarer.
374
375 Raises:
376 DeclarationError: when a section is off the shape a query's
377 declaration has.
378 """
379 from livery.workshop._contract_keys import BASE_FILE, base_contract
380 from livery.workshop._declaration import query_specs_of
381
382 return query_specs_of(base_contract(), BASE_FILE, extension=BASE, package=BASE)
383
384
385@functools.cache
386def declared_queries() -> dict[str, QuerySpec]:
387 """Every declared query by name: the base's, then each installed extension's.
388
389 An installed extension's declaration is read whether the workspace
390 lists it or not, so an answer to its query reads the same anywhere;
391 a query nobody listed declares is asked by nobody.
392
393 Raises:
394 DeclarationError: when two extensions declare one query.
395 """
396 from livery.footman import installed_entry_points
397 from livery.workshop._declaration import DeclarationError, query_declarations
398
399 found = dict(base_queries())
400 for entry in installed_entry_points("workshop.extensions"):
401 for spec in query_declarations(entry.name, entry.value.partition(":")[0]):
402 held = found.get(spec.name)
403 if held is not None and held.extension != spec.extension:
404 both = " and ".join(sorted((held.extension, spec.extension)))
405 raise DeclarationError(
406 f"the {spec.name} query is declared by both {both}; one"
407 " extension declares a query"
408 )
409 found[spec.name] = spec
410 return found
411
412
413def query_spec(name: str) -> QuerySpec:
414 """The declared query *name*; refuses naming the declared ones.
415
416 Raises:
417 QueryError: when no extension declares *name*.
418 """
419 specs = declared_queries()
420 found = specs.get(name)
421 if found is None:
422 raise QueryError(
423 f"{name} is not a declared query; the queries are {', '.join(specs)}"
424 )
425 return found
426
427
428def _walk(subject: Package | Path, spec: QuerySpec, lookup: Lookup) -> tuple[str, ...]:
429 """The extensions asked *spec* about *subject*, in the order they answer.
430
431 A package's set, or the installed set, in composition order; a set
432 whose declared order has no start is asked
433 alphabetically, and ``layering.graph`` names the cycle.
434
435 Raises:
436 QueryError: when *subject* is at the other level from the query.
437 """
438 if isinstance(subject, Path):
439 if spec.level != WORKSPACE_LEVEL:
440 raise QueryError(
441 f"{spec.name} is a question about a package, which {spec.extension}"
442 " declares at the package level; ask it with the package"
443 )
444 from livery.workshop._extensions import extension_names
445
446 return extension_names(subject)
447 if spec.level != PACKAGE_LEVEL:
448 raise QueryError(
449 f"{spec.name} is a question about the workspace, which {spec.extension}"
450 " declares at the workspace level; ask it with the workspace root"
451 )
452 from livery.workshop._composition import OrderCycle, closure, order
453
454 members = closure(subject.extensions, lookup)
455 try:
456 return order(members, lookup)
457 except OrderCycle:
458 return tuple(sorted(members))
459
460
461def _contributed(subject: Package | Path, extension: str) -> frozenset[str]:
462 """The listed targets *extension*'s listing contributes to in *subject*'s workspace.
463
464 The rule [livery.workshop.contributions_for][] reads a target's
465 tables by: every listed target the extension declares a
466 ``[for.<target>]`` table for, except those its root entry's
467 ``without`` names.
468 """
469 from livery.workshop._extensions import extension_names, resolved_targets
470
471 start = subject if isinstance(subject, Path) else subject.directory
472 listed = frozenset(extension_names(start))
473 return listed.intersection(resolved_targets(start).get(extension, ()))
474
475
476def answered_at(
477 subject: Package | Path, extension: str, declared: Declaration, query: str
478) -> list[tuple[tuple[str, ...], Reference | DeclaredValue]]:
479 """Where *extension* answers *query* about *subject* now, each place and answer.
480
481 A place is a key path in *declared*'s file: the top level,
482 ``queries.<query>``, always, and a ``[for.<target>]`` table's,
483 ``for.<target>.queries.<query>``, while *target* is listed and the
484 extension's listing contributes to it. Decided from the
485 declarations and the contracts' lists alone, asking nothing; empty
486 when no place answers now. [livery.workshop._queries.answers][]
487 asks the places it names.
488 """
489 held: list[tuple[tuple[str, ...], Reference | DeclaredValue]] = []
490 if query in declared.queries:
491 held.append((("queries", query), declared.queries[query]))
492 targets = [
493 target
494 for target, answered in declared.target_queries.items()
495 if query in answered
496 ]
497 if targets:
498 # The lists are read only when a [for] table answers the query.
499 contributed = _contributed(subject, extension)
500 held += [
501 (("for", target, "queries", query), declared.target_queries[target][query])
502 for target in targets
503 if target in contributed
504 ]
505 return held
506
507
508def _one_answer(
509 name: str,
510 held: list[tuple[tuple[str, ...], Reference | DeclaredValue]],
511 subject: Package | Path,
512 spec: QuerySpec,
513) -> object:
514 """The answer of the extension *name* from each place *held* names.
515
516 Each place is a key path in the declaration file and the answer
517 there, asked and judged against the query's values. Answers from
518 two places make one for a ``union`` query, every item once in the
519 order first met; for a query of any other rule they refuse.
520 """
521 from livery.workshop._contract_keys import shown
522 from livery.workshop._declaration import DeclaredValue
523
524 values: dict[str, object] = {}
525 for place, answered in held:
526 value = (
527 answered.value if isinstance(answered, DeclaredValue) else answered(subject)
528 )
529 if spec.values is not None and value not in spec.values:
530 listed = ", ".join(repr(known) for known in spec.values)
531 at = f" at {shown(place)}" if place[0] == "for" else ""
532 raise QueryError(
533 f"{name} answers {spec.name} with {value!r}{at}, whose values are"
534 f" {listed}"
535 )
536 values[shown(place)] = value
537 if len(values) == 1:
538 return next(iter(values.values()))
539 if spec.combine != UNION:
540 raise QueryError(
541 f"{name} answers {spec.name} at {' and at '.join(values)}; only a"
542 " union query takes two answers from one extension, so answer it in"
543 " one place"
544 )
545 items: dict[object, None] = {}
546 for where, value in values.items():
547 if isinstance(value, (str, bytes)) or not isinstance(value, Iterable):
548 raise QueryError(
549 f"{name} answers {spec.name} with {value!r} at {where}, and a union"
550 " combines lists; answer a list"
551 )
552 items.update(dict.fromkeys(cast("Iterable[object]", value)))
553 return tuple(items)
554
555
556def answers(
557 subject: Package | Path, query: Query[T], *, lookup: Lookup | None = None
558) -> dict[str, T]:
559 """Each extension that answers *query* about *subject*, to its answer.
560
561 *subject* is the package for a package-level query, and the
562 workspace root, or a directory in the workspace, for a
563 workspace-level one. Each declaration is read through *lookup*,
564 the installed ones when absent. An extension answers at the top
565 level of its declaration file, and in a ``[for.<target>]`` table
566 while *target* is listed and the extension's listing contributes to
567 it ([livery.workshop._queries.answered_at][]); answering in two of
568 those places, it answers a ``union`` query with every item of both.
569
570 Raises:
571 QueryError: when no extension declares the query, when *subject*
572 is at the other level, when an answer is off the query's
573 values, naming the extension, or when an extension answers a
574 query of another rule in two places, naming both.
575 """
576 if lookup is None:
577 from livery.workshop._extensions import installed_declaration
578
579 lookup = installed_declaration
580 spec = query_spec(query.name)
581 found: dict[str, T] = {}
582 for name in _walk(subject, spec, lookup):
583 declared = lookup(name)
584 if declared is None:
585 continue
586 held = answered_at(subject, name, declared, query.name)
587 if held:
588 found[name] = cast("T", _one_answer(name, held, subject, spec))
589 return found
590
591
592def answer(
593 subject: Package | Path, query: Query[T], *, lookup: Lookup | None = None
594) -> T:
595 """The answer to *query* about *subject*: the extensions' answers, combined.
596
597 *subject* is the package for a package-level query, answered by its
598 set in composition order, and the workspace root, or a directory in
599 the workspace, for a workspace-level one, answered by the installed
600 set in composition order. With no extension answering, the query's
601 declared default, or its rule's answer over nothing.
602
603 Raises:
604 QueryError: when no extension declares the query, when *subject*
605 is at the other level, when an answer is off the query's
606 values, or when the answers break the query's rule; the
607 message names the query and the extensions, and a package's
608 path for a package-level query.
609 """
610 if lookup is None:
611 from livery.workshop._extensions import installed_declaration
612
613 lookup = installed_declaration
614 spec = query_spec(query.name)
615 found = answers(subject, query, lookup=lookup)
616 if not found and spec.default is not None:
617 return cast("T", spec.default)
618 combine: Combine = (
619 RULES[spec.combine] if isinstance(spec.combine, str) else spec.combine
620 )
621 where = "" if isinstance(subject, Path) else f"{subject.path}: "
622 try:
623 return cast("T", combine(found, lookup))
624 except (QueryError, ValueError) as error:
625 raise QueryError(f"{where}{query.name}: {error}") from None
626
627
628def workspace_answers(root: Path, *, lookup: Lookup | None = None) -> dict[str, object]:
629 """Every workspace-level query's answer about *root*, by name.
630
631 A rendered template reads ``queries["python.dev-group"]`` through
632 it; a name no extension declares at the workspace level is absent.
633 """
634 return {
635 name: answer(root, Query(name), lookup=lookup)
636 for name, spec in declared_queries().items()
637 if spec.level == WORKSPACE_LEVEL
638 }