Coverage for packages/workshop/src/livery/workshop/_steps.py: 96%

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"""The step registry: what the quality gate runs, one record per step.
2
3A step is one tool's judgment over the workspace or over one
4package: a formatter's pass, the render drift comparison, ctest
5over a native member. Each is a [livery.workshop._steps.StepRecord][]
6registered through [livery.workshop._steps.register_step][], and
7the gate is the walk over the registry: every applicable step
8green, the exit code the verdict. The workshop registers the
9builtin records at import; an extension's records register at
10mount, after them and in composition order, each extension after
11the ones it requires, ties alphabetical, and re-registering a name
12replaces the record.
13
14A step names the extensions whose packages it judges, and a package
15holding none of them skips it by name: a C++ member is formatted over
16its recipe by a python formatter and over its sources by clang-format
17because each step names an extension it holds. The phases the
18registry knows are the ones its steps name, so they are what the
19listed extensions register.
20
21A step is named by its phase and its name in the phase,
22``test.pytest``. The phase is a declared one
23([livery.workshop._phases.declared_phases][]), and a step of a phase
24nobody declares refuses naming the declared ones. A phase that
25declares a verb is a verb and every step a sub-task of it, made by
26[livery.workshop._steps.generate_verbs][] from the registry: ``fm
27test`` runs the test phase's steps and ``fm test.pytest`` the one;
28the gate runs the steps of the phases that declare themselves gated.
29
30The gate runs the registered steps through the one walk
31([livery.workshop._phases.walk_steps][]), each a footman step: the
32rewriters one at a time before any judge reads the tree
33([livery.workshop._steps.rewriters][]), then every judge in one
34block ([livery.workshop._steps.judges][]), each with its own record.
35A step that must follow another on the same package, a build after
36its configure, names it in ``after``: the walk starts it once the
37earlier one ran, and the gate brings the earlier one in
38([livery.workshop._steps.with_earlier][]).
39"""
40
41from __future__ import annotations
42
43import inspect
44import weakref
45from collections.abc import Callable, Iterable, Mapping
46from dataclasses import dataclass
47from pathlib import Path, PurePosixPath
48from typing import TYPE_CHECKING, Annotated, cast
49
50from livery import git
51from livery.footman import Group, doc, fail, prog, root_group
52from livery.workshop import _fragments
53from livery.workshop._fragments import Fragment
54
55if TYPE_CHECKING:
56 from livery.workshop._categories import CategoryRule
57 from livery.workshop._influence import Changes, InputEntry, Inputs, Selection
58 from livery.workshop._packages import Package
59 from livery.workshop._phases import PhaseContext
60 from livery.workshop._words import Words
61
62#: A step's scope: the whole workspace in one run, or one package at a time.
63WORKSPACE = "workspace"
64PACKAGE = "package"
65
66#: How a workspace step narrows under a package-scoped gate.
67PATHS = "paths"
68PACKAGES = "packages"
69NONE = "none"
70
71#: The extension the builtin records belong to.
72BASE_EXTENSION = "livery.workshop"
73
74
75@dataclass(frozen=True)
76class Option:
77 """One option a package may set on a step, in the step's own table.
78
79 The table is ``[phases.<phase>.<step>]``, the step's address; a
80 ``[phases.<phase>]`` table sets an option on every step of the
81 phase.
82
83 Attributes:
84 name: The option's key, kebab-case.
85 kind: ``bool``, ``str``, ``int`` or ``strs``, a list of
86 strings; a value of another type refuses naming the option.
87 default: What the step reads when the package says nothing.
88 doc: One line saying what the option changes.
89 """
90
91 name: str
92 kind: str
93 default: object
94 doc: str = ""
95
96
97#: Every step carries this option: a package that turns a step off
98#: is skipped by name in the gate's output.
99ENABLED = Option("enabled", "bool", True, "whether the step judges this package")
100
101
102@dataclass(frozen=True)
103class StepRecord:
104 """One step, completely.
105
106 A step's name is its phase and its name in the phase,
107 ``test.pytest``: the verb ``fm test.pytest``, the
108 ``[phases.test.pytest]`` table of its options, the gate's lines,
109 and every lookup use it. An extension declares the step in its
110 ``[phases.<phase>.<step>]`` table.
111
112 Attributes:
113 step: The step's name in its phase, as its sub-task names it
114 under the phase's verb: ``pytest`` in ``fm test.pytest``.
115 phase: The phase the step belongs to: ``format``, ``lint``,
116 ``typecheck``, ``typecomplete``, ``test``, ``build``,
117 ``drift``, ``provenance`` or ``layering``, a declared
118 phase a verb is generated from.
119 run: The judging callable, called with the run's
120 [livery.workshop.PhaseContext][]: the engine running the
121 step's words or a reference to its code; a refusal is its
122 verdict.
123 scope: ``workspace`` for a step that judges the whole in one
124 run, ``package`` for one that judges one package at a
125 time.
126 narrowing: How a workspace step narrows under a scoped gate:
127 ``paths`` (the subset's directories), ``packages`` (the
128 subset's members) or ``none`` (the whole is always
129 judged). A package step narrows by its packages. No
130 declaration names it: the reader derives it, ``paths``
131 for a template with ``{paths}``, ``packages`` for a
132 workspace step in code with no ``inputs``, ``none``
133 otherwise ([livery.workshop._declaration.read][]).
134 fix: The rewriting callable when the tool can rewrite, run
135 serially before any judge under ``--fix``; None for a
136 step that only judges.
137 extensions: The extensions whose packages the step judges: a
138 package whose set holds one of them
139 ([livery.workshop.extension_set][]). A package step
140 runs per such member; a workspace step names them so its
141 tools and claims reach those packages, or leaves them empty.
142 tests_only: Whether a package step still runs when the
143 package's change is confined to its tests. A build and
144 the tests do; a formatter does not.
145 inputs: The files a workspace step reads, so a run judges it
146 only when one of them, or what widens it, changed, and then
147 only the changed ones when it judges per file
148 ([livery.workshop._influence.Inputs][]). None for a step
149 that narrows by its packages alone.
150 after: The steps this one runs after, by name: a build
151 after its configure, a ctest after its build. The walk
152 starts this one once each of them ran for the same
153 package, and the gate's walk brings them in
154 ([livery.workshop._steps.with_earlier][]).
155 extension: The extension that registered the step, named when a
156 narrowing is printed.
157 tools: The tools the step runs, as the tool profile names
158 them, ``("clang_format",)``; each reaches the profile while a
159 package the step judges exists, naming ``step <name>`` as its
160 site, and leaves it when the step is unregistered.
161 options: The options a package may set under
162 ``[phases.<phase>.<step>]``; ``enabled`` is every step's.
163 fragments: The configuration the render manages for the
164 step, one per rendered file it has something to say in;
165 composed in step-name order, judged by the drift gate,
166 gone from the next render with the record.
167 claims: The categories the step judges, each with the rules
168 it withholds there and the suffixes it reads; a step
169 judges every file its claims reach and no other, and a
170 tool with per-file ignores renders its ignores from them.
171 flags: The command-line flags the step reads, from `FLAGS`:
172 ``point`` for a step that selects tests by CI point,
173 ``shard`` for a step that runs its share of a sharded
174 check leg, and so runs on every shard; a step without it
175 runs on the first shard alone
176 ([livery.workshop._steps.on_this_shard][]). A generated
177 verb offers the flags its steps declare, and ``--fix``
178 with ``--safe-fix`` where a step has a fix mode.
179 arguments: Whether the step hands the tool it wraps the words
180 after ``--`` on its own verb (``fm test.pytest -- -k name``),
181 which it reads from [livery.workshop.PhaseContext][]'s
182 ``arguments``. A step that wraps no tool leaves it off, and
183 its verb refuses them. No declaration names it: the reader
184 derives it, on for a template with ``{arguments}`` and for
185 a step in code that names ``tools``.
186 words: The step's words when it is declared in words, which
187 ``fm explain`` prints and the conformance kit judges; None
188 for a step whose ``main`` is code.
189 provides: The context keys the step writes inside its phase,
190 each to its type name; a step of one phase reads what
191 another provides.
192 reads: The context keys the step reads inside its phase.
193 isolated: Whether the step serves the phase's isolated side
194 (True), from a copy of the sources in a fresh environment,
195 or its tree side (False); None serves both. The walk runs
196 the step on the side the engine gives the phase
197 ([livery.workshop._phases.serves][]), and the gate gives
198 the tree side.
199 enabled: Whether the step registers while its extension is
200 listed. An extension declares False for a step a workspace
201 turns on at the step's address in the root contract,
202 ``[phases.<phase>.<step>] enabled = true``.
203 replaces: The steps of the base or of an extension this one
204 requires that it replaces, each ``<owner>:<phase>.<step>``
205 with the reason; naming the step registered at this one's
206 address is what lets a second extension take the address.
207 deletes: The steps of the base or of an extension this one
208 requires that it deletes, each ``<owner>:<phase>.<step>``
209 with the reason.
210 outputs: The paths the step writes, each relative to the root
211 or ``package/<path>`` for the path in each package. When
212 [livery.workshop.run_phase][] runs the step's phase, an
213 output no running step declares is removed first, so a step
214 that stops running leaves nothing behind wherever it wrote.
215
216 """
217
218 step: str
219 phase: str
220 run: Callable[[PhaseContext], None]
221 scope: str = WORKSPACE
222 narrowing: str = NONE
223 fix: Callable[[PhaseContext], None] | None = None
224 extensions: tuple[str, ...] = ()
225 tests_only: bool = False
226 inputs: Inputs | None = None
227 after: tuple[str, ...] = ()
228 extension: str = BASE_EXTENSION
229 tools: tuple[str, ...] = ()
230 options: tuple[Option, ...] = ()
231 fragments: tuple[Fragment, ...] = ()
232 flags: tuple[str, ...] = ()
233 arguments: bool = False
234 words: Words | None = None
235 provides: tuple[tuple[str, str], ...] = ()
236 reads: tuple[str, ...] = ()
237 isolated: bool | None = None
238 enabled: bool = True
239 replaces: tuple[tuple[str, str], ...] = ()
240 deletes: tuple[tuple[str, str], ...] = ()
241 outputs: tuple[str, ...] = ()
242
243 @property
244 def name(self) -> str:
245 """The step's name: its phase and its name in the phase, ``test.pytest``."""
246 return f"{self.phase}.{self.step}"
247
248 @property
249 def category_reads(self) -> tuple[InputEntry, ...]:
250 """The category entries of ``inputs.reads``, for package-scoped steps."""
251 if self.inputs is None:
252 return ()
253 return tuple(entry for entry in self.inputs.reads if entry.category)
254
255
256_STEPS: dict[str, StepRecord] = {}
257
258
259#: The command-line flags a step may read, beyond the fix modes:
260#: ``point``, the CI point whose tests the step selects, and ``shard``,
261#: the shard of a sharded check leg the step runs its share of.
262FLAGS = ("point", "shard")
263
264
265def register_step(record: StepRecord) -> None:
266 """Register *record*; a name already registered is replaced.
267
268 The mount registers each step a listed extension declares.
269 Replacing is how an extension swaps the step at an address, and
270 how a test injects a fake; a package step names at least one
271 extension, since a step that judges packages and applies to none
272 never runs. The step's address, ``<phase>.<step>``, is a task's
273 address, so a dot inside the phase or the step's name refuses, and
274 a step named ``default`` refuses (that address is the phase verb's
275 own).
276 """
277 from livery.workshop import _phases
278
279 for part in (record.phase, record.step):
280 if not part or "." in part:
281 fail(
282 f"step {record.name!r}: a phase and a step's name are one word"
283 f" each, not {part!r}; the step answers to <phase>.<step>"
284 )
285 declared = _phases.declared_phases()
286 if record.phase not in declared:
287 fail(
288 f"step {record.name!r}: {record.phase} is not a declared phase; the"
289 f" phases are {', '.join(declared)}"
290 )
291 if record.step == "default":
292 fail(
293 f"step {record.name!r}: {record.name} is the address of the"
294 f" {record.phase} verb itself; name the step by its tool"
295 )
296 held = _STEPS.get(record.name)
297 if held is not None and held.extension != record.extension:
298 # A second extension takes an address by saying so: the step it
299 # replaces or deletes, named with its owner, and why.
300 named = {address for address, _reason in (*record.replaces, *record.deletes)}
301 if f"{held.extension}:{held.name}" not in named:
302 fail(
303 f"step {record.name} is declared by both {held.extension} and"
304 f" {record.extension}; two extensions declare one step unless"
305 f" {record.extension} names {held.extension}:{held.name} in"
306 " replaces or deletes, with a reason"
307 )
308 if record.scope not in (WORKSPACE, PACKAGE):
309 fail(
310 f"step {record.name!r}: scope is {WORKSPACE!r} or {PACKAGE!r},"
311 f" not {record.scope!r}"
312 )
313 unknown = [flag for flag in record.flags if flag not in FLAGS]
314 if unknown:
315 fail(
316 f"step {record.name!r} reads {', '.join(unknown)}, which no verb"
317 f" offers; the flags are {', '.join(FLAGS)}"
318 )
319 if record.narrowing not in (PATHS, PACKAGES, NONE):
320 fail(
321 f"step {record.name!r}: narrowing is {PATHS!r}, {PACKAGES!r} or"
322 f" {NONE!r}, not {record.narrowing!r}"
323 )
324 if record.scope == PACKAGE and not record.extensions:
325 fail(
326 f"step {record.name!r} judges packages and names no extension: a"
327 " package step judges the packages whose set holds one it names"
328 )
329 try:
330 _fragments.verify(record.fragments, record.name)
331 except ValueError as error:
332 fail(str(error))
333 from livery.workshop._categories import known_categories, known_channels
334 from livery.workshop._influence import NAMED_SETS
335
336 if record.inputs is not None:
337 known = known_categories()
338 channels = known_channels()
339 for entry in (*record.inputs.reads, *record.inputs.widens):
340 if entry.category and entry.category not in known:
341 fail(
342 f"step {record.name!r} names category {entry.category!r}, which"
343 " no category table knows; the categories are"
344 f" {', '.join(sorted(known))}"
345 )
346 if entry.channel and entry.channel not in channels:346 ↛ 347line 346 didn't jump to line 347 because the condition on line 346 was never true
347 fail(
348 f"step {record.name!r} names channel {entry.channel!r}, which"
349 " no channel rule defines; the channels are"
350 f" {', '.join(sorted(channels))}"
351 )
352 if entry.set and entry.set not in NAMED_SETS:352 ↛ 353line 352 didn't jump to line 353 because the condition on line 352 was never true
353 fail(
354 f"step {record.name!r} names set {entry.set!r}, which is not a"
355 f" named set; the sets are {', '.join(sorted(NAMED_SETS))}"
356 )
357 _STEPS[record.name] = record
358
359
360def _typed(option: Option, value: object) -> bool:
361 if option.kind == "strs":
362 return isinstance(value, list) and all(
363 isinstance(item, str) for item in cast("list[object]", value)
364 )
365 expected = {"bool": bool, "str": str, "int": int}[option.kind]
366 if option.kind == "int" and isinstance(value, bool):366 ↛ 367line 366 didn't jump to line 367 because the condition on line 366 was never true
367 return False
368 return isinstance(value, expected)
369
370
371def option_addresses(record: StepRecord) -> tuple[str, ...]:
372 """The tables that reach *record*'s options, shallowest first.
373
374 ``phases.<phase>``, the phase's table, which reaches every step of
375 the phase, then ``phases.<phase>.<step>``, the step's own: the
376 later table wins key by key, since it names fewer steps.
377 """
378 return (f"phases.{record.phase}", f"phases.{record.phase}.{record.step}")
379
380
381def option_value(record: StepRecord, package: Package, name: str) -> object:
382 """What *package* sets for *record*'s option *name*, or the option's default.
383
384 The deepest table that sets it wins
385 ([livery.workshop._steps.option_addresses][]). Refuses an option
386 the record does not declare and a value of the wrong type, naming
387 the record's options.
388 """
389 declared = {option.name: option for option in (*record.options, ENABLED)}
390 if name not in declared:
391 fail(
392 f"step {record.name!r} declares no option {name!r}; its options are"
393 f" {', '.join(declared)}"
394 )
395 option = declared[name]
396 tables = dict(package.step_options)
397 found: object = option.default
398 for address in option_addresses(record):
399 for key, value in tables.get(address, ()):
400 if key != name:
401 continue
402 if not _typed(option, value):
403 fail(
404 f"{package.path}/workshop.toml: [{address}] {name} is"
405 f" {option.kind}, not {value!r}"
406 )
407 found = value
408 return found
409
410
411def _reached(address: str) -> tuple[StepRecord, ...]:
412 """The registered steps a table *address* reaches.
413
414 ``phases.<phase>`` reaches every step of the phase, and
415 ``phases.<phase>.<step>`` the one step.
416 """
417 _kind, _, rest = address.partition(".")
418 phase, _, step = rest.partition(".")
419 return tuple(
420 r for r in _STEPS.values() if r.phase == phase and (not step or r.step == step)
421 )
422
423
424def option_problems(packages: tuple[Package, ...]) -> list[str]:
425 """Every option table or key no registered step takes, one line each.
426
427 Read by ``layering.graph``, so a package that addresses a phase or
428 a step that does not exist, or sets an option none of the steps it
429 reaches declares, is refused with the vocabulary named.
430 """
431 problems: list[str] = []
432 known = phases()
433 for package in packages:
434 where = f"{package.path}/workshop.toml"
435 for address, options in package.step_options:
436 reached = _reached(address)
437 if not reached:
438 _kind, _, rest = address.partition(".")
439 if "." in rest:
440 problems.append(
441 f"{where}: [{address}] reaches no registered step; the"
442 f" steps are {', '.join(sorted(_STEPS))}"
443 )
444 else:
445 problems.append(
446 f"{where}: [{address}] names no phase a registered step"
447 f" has; the phases are {', '.join(known)}"
448 )
449 continue
450 declared: dict[str, Option] = {ENABLED.name: ENABLED}
451 for record in reached:
452 declared.update({option.name: option for option in record.options})
453 for key, value in options:
454 option = declared.get(key)
455 if option is None:
456 problems.append(
457 f"{where}: [{address}] sets {key!r}, which no step it"
458 f" reaches declares; their options are"
459 f" {', '.join(sorted(declared))}"
460 )
461 elif not _typed(option, value):
462 problems.append(
463 f"{where}: [{address}] {key} is {option.kind}, not {value!r}"
464 )
465 return problems
466
467
468def enabled(name: str, packages: tuple[Package, ...]) -> tuple[Package, ...]:
469 """*packages* minus those that turned the step *name* off, each skip printed."""
470 record = step_for(name)
471 kept: list[Package] = []
472 for package in packages:
473 if option_value(record, package, "enabled"):
474 kept.append(package)
475 else:
476 print(
477 f" {name}: {package.path} skips (turned off in"
478 f" {package.path}/workshop.toml)"
479 )
480 return tuple(kept)
481
482
483def tools_for(extensions: Iterable[str]) -> tuple[tuple[str, str], ...]:
484 """The tools the steps judging packages that hold *extensions* run.
485
486 Each as a ``(tool, step)`` pair. A step judges such a package
487 when it names one of *extensions*; a workspace step names the
488 extensions its bodies judge the same way.
489 """
490 held = set(extensions)
491 found: list[tuple[str, str]] = []
492 for record in _STEPS.values():
493 if held & set(record.extensions):
494 found.extend((tool, record.name) for tool in record.tools)
495 return tuple(found)
496
497
498def unregister_step(name: str) -> None:
499 """Drop the step *name*; unknown names refuse naming the registry."""
500 if name not in _STEPS:
501 fail(f"{name!r} is not a registered step; steps: {', '.join(_STEPS)}")
502 del _STEPS[name]
503
504
505def narrowings() -> tuple[str, ...]:
506 """The gate's lines naming each step an extension registered.
507
508 A step the base did not register names its extension. Empty for the
509 base alone.
510 """
511 return tuple(
512 f" {record.name}: registered by {record.extension}"
513 for record in _STEPS.values()
514 if record.extension != BASE_EXTENSION
515 )
516
517
518def step_names() -> tuple[str, ...]:
519 """Every registered step, in registration order."""
520 return tuple(_STEPS)
521
522
523def snapshot(*, initial: bool = False) -> dict[str, StepRecord]:
524 """The registry's state, for [livery.workshop._steps.restore][] to put back.
525
526 With *initial*, the state importing this module leaves instead: the
527 builtin steps alone, as a process starts with them.
528 """
529 return dict(_BUILTIN_STATE if initial else _STEPS)
530
531
532def restore(state: dict[str, StepRecord]) -> None:
533 """Put the registry back to *state*."""
534 _STEPS.clear()
535 _STEPS.update(state)
536
537
538def _uses_change_selection(record: StepRecord) -> bool:
539 """Whether *record* selects by changed files rather than by packages."""
540 return (
541 record.inputs is not None
542 and record.scope == WORKSPACE
543 and record.words is None
544 and not record.extensions
545 )
546
547
548def _reaches(entry: InputEntry, relative: str) -> bool:
549 """Whether the entry admits the file's suffix; no suffixes admits every file."""
550 return not entry.suffixes or PurePosixPath(relative).suffix in entry.suffixes
551
552
553def _admits(entry: InputEntry, pattern: str) -> bool:
554 """Whether a category pattern can name a file the entry reads.
555
556 A pattern ending in a literal suffix outside the entry's, cpp's
557 ``tests/**/*.cpp`` against a python entry, renders no ignore; a
558 directory pattern renders as it is, since the tool reads only its
559 own files under it.
560 """
561 return not PurePosixPath(pattern).suffix or _reaches(entry, pattern)
562
563
564def _package_files(package: Package) -> tuple[str, ...]:
565 """The files git holds under the package: tracked, or untracked and not ignored.
566
567 Sorted, relative to the package. A build tree or a cache under the
568 package is ignored, so no entry reaches it; a tracked file deleted
569 from the tree is left out.
570 """
571 names = git.ls_files(package.directory, others=True)
572 return tuple(name for name in names if (package.directory / name).is_file())
573
574
575def judged_files(record: StepRecord, package: Package) -> tuple[str, ...]:
576 """The files of *package* the step's category reads reach, relative to it, sorted.
577
578 Every file git holds under the package directory is categorised
579 and kept when a category read names its category and admits its suffix; a
580 record without category reads judges nothing by this measure, which is
581 what a step that runs a tool over directories looks like from
582 here.
583 """
584 from livery.workshop._categories import category_of
585
586 entries = record.category_reads
587 if not entries or not package.directory.is_dir():
588 return ()
589 found: list[str] = []
590 for relative in _package_files(package):
591 category = category_of(package, relative).name
592 if any(e.category == category and _reaches(e, relative) for e in entries):
593 found.append(relative)
594 return tuple(found)
595
596
597def claimants(package: Package, path: str) -> tuple[str, ...]:
598 """The package-scoped steps whose inputs reach *path* in *package*, sorted."""
599 from livery.workshop._categories import category_of
600
601 category = category_of(package, path).name
602 names = []
603 for record in _STEPS.values():
604 if _uses_change_selection(record):
605 continue
606 entries = record.category_reads
607 if not any(e.category == category and _reaches(e, path) for e in entries):
608 continue
609 if record.extensions and not _applies(record, package):
610 continue
611 names.append(record.name)
612 return tuple(sorted(names))
613
614
615def readers_of(root: Path, path: str) -> tuple[str, ...]:
616 """The workspace change-selected steps whose ``inputs.reads`` reach *path*."""
617 from livery.workshop._influence import reads as inputs_read
618
619 names = [
620 record.name
621 for record in _STEPS.values()
622 if _uses_change_selection(record)
623 and record.inputs is not None
624 and inputs_read(record.inputs, root, path)
625 ]
626 return tuple(sorted(names))
627
628
629def per_file_ignores(
630 held: Iterable[Iterable[str]],
631) -> list[tuple[str, tuple[str, ...]]]:
632 """The per-file ignores the inputs render, pattern to rule codes, sorted.
633
634 *held* is each set of extensions a present package holds. For
635 each set, every category read of a step that judges a package
636 holding it and withholds rules on a category maps to that
637 category's patterns in the tables that answer for such a package,
638 each under ``packages/**/``, which reaches a member in a group
639 directory too. For the workspace's own unit, every step's category
640 reads map to its table's patterns as they are. Two steps reading one
641 category under different rules land in one entry with both sets.
642 """
643 from livery.workshop._categories import category_rules, workspace_rules
644
645 table: dict[str, set[str]] = {}
646 units: list[tuple[frozenset[str] | None, tuple[CategoryRule, ...], str]] = []
647 for listed in held:
648 names = tuple(listed)
649 units.append((frozenset(names), category_rules(names), "packages/**/"))
650 units.append((None, workspace_rules(), ""))
651 for holding, rules, prefix in units:
652 for record in _STEPS.values():
653 if holding is not None and not judges_extensions(record, holding):
654 continue
655 for entry in record.category_reads:
656 if not entry.ignore:
657 continue
658 for rule in rules:
659 if rule.category != entry.category or rule.pattern == "**":
660 continue
661 if not _admits(entry, rule.pattern):
662 continue
663 table.setdefault(prefix + rule.pattern, set()).update(entry.ignore)
664 return [(pattern, tuple(sorted(codes))) for pattern, codes in sorted(table.items())]
665
666
667def steps_by_name() -> dict[str, StepRecord]:
668 """Every registered record by name, in registration order."""
669 return dict(_STEPS)
670
671
672def answering(address: str) -> str | None:
673 """The step answering to *address*, its name; None when none is registered."""
674 return address if address in _STEPS else None
675
676
677def step_for(name: str) -> StepRecord:
678 """The step named *name*, ``test.pytest``.
679
680 Refusal names the registry.
681 """
682 if name not in _STEPS:
683 fail(f"{name!r} is not a registered step; steps: {', '.join(_STEPS)}")
684 return _STEPS[name]
685
686
687def phases() -> tuple[str, ...]:
688 """The phases the registered steps belong to, sorted."""
689 return tuple(sorted({r.phase for r in _STEPS.values()}))
690
691
692def judges_extensions(record: StepRecord, extensions: Iterable[str]) -> bool:
693 """Whether *record* judges a package holding *extensions*.
694
695 A step that names no extensions judges every package; one that
696 names some judges a package holding one of them.
697 """
698 return not record.extensions or bool(set(record.extensions) & set(extensions))
699
700
701def judges_unit(record: StepRecord, unit: Package) -> bool:
702 """Whether *record* judges *unit*, by the extensions the unit holds.
703
704 A member holds its set, and the workspace's own tests hold the
705 root's set (`extension_set`). A step that names no extension judges
706 every unit; one that names some judges a unit holding one of them.
707 """
708 from livery.workshop._composition import extension_set
709
710 return judges_extensions(record, extension_set(unit))
711
712
713def judged_by(
714 record: StepRecord, packages: tuple[Package, ...], *, quiet: bool = False
715) -> tuple[Package, ...]:
716 """The *packages* *record* judges, by the extensions they hold; each other skips.
717
718 A package holding none of the step's extensions prints a skip
719 naming the step, the package and the extensions, so a narrowed gate
720 is visible in the output and never passes silently. *quiet* counts
721 without printing.
722 """
723 kept: list[Package] = []
724 for package in packages:
725 if judges_unit(record, package):
726 kept.append(package)
727 elif not quiet:
728 wanted = " or ".join(record.extensions)
729 print(f" {record.name}: {package.path} skips (not a {wanted} package)")
730 return tuple(kept)
731
732
733def _applies(record: StepRecord, package: Package) -> bool:
734 """Whether a package step judges *package*, by the extensions it holds."""
735 from livery.workshop._composition import extension_set
736
737 return bool(set(record.extensions) & set(extension_set(package)))
738
739
740def judges_package(record: StepRecord, ctx: PhaseContext, package: Package) -> bool:
741 """Whether the package step *record* runs over *package* in this run.
742
743 The package holds an extension the step names; a change confined
744 to the package's tests leaves the step out unless it is tests-only
745 ([livery.workshop._steps.StepRecord][]).
746 """
747 tests_only = ctx.scoped and package.path in ctx.tests
748 return (
749 record.scope == PACKAGE
750 and _applies(record, package)
751 and (record.tests_only or not tests_only)
752 )
753
754
755def members(ctx: PhaseContext) -> tuple[Package, ...]:
756 """The packages under judgment that are members: every one but the tests unit."""
757 from livery.workshop._packages import WORKSPACE_TESTS
758
759 return tuple(package for package in ctx.judged if package.path != WORKSPACE_TESTS)
760
761
762def _makes_verb(phase: str) -> bool:
763 """Whether *phase* gets a verb: it declares one."""
764 from livery.workshop import _phases
765
766 spec = _phases.declared_phases().get(phase)
767 return spec is None or spec.verb
768
769
770def verb_tree() -> dict[str, dict[str, StepRecord]]:
771 """Each phase's steps by name, sorted: the verbs the registry generates.
772
773 A phase that declares no verb is left out.
774 """
775 tree: dict[str, dict[str, StepRecord]] = {}
776 for record in _STEPS.values():
777 if _makes_verb(record.phase):
778 tree.setdefault(record.phase, {})[record.step] = record
779 return {phase: dict(sorted(steps.items())) for phase, steps in sorted(tree.items())}
780
781
782#: The verb functions the generator made. Footman shares a task's
783#: function when it copies a tree into a project, so the function is
784#: how a later generation knows a verb as its own: its own it remakes
785#: or removes, and any other task at an address serves that address.
786_MADE: weakref.WeakSet[Callable[..., None]] = weakref.WeakSet()
787
788
789def split_arguments(paths: tuple[str, ...]) -> tuple[tuple[str, ...], tuple[str, ...]]:
790 """A verb's positional words as its paths, then the words after ``--``.
791
792 footman hands a task's variadic parameter the words after ``--``
793 too, last, and names them through ``passthrough()``.
794 """
795 from livery.footman import passthrough
796
797 after = tuple(passthrough())
798 if after and paths[-len(after) :] == after:
799 return paths[: -len(after)], after
800 return paths, after
801
802
803def _run_named(
804 names: tuple[str, ...],
805 words: tuple[str, ...],
806 *,
807 refusal: str,
808 fix: bool = False,
809 safe_fix: bool = False,
810 point: str = "",
811 shard: str = "",
812) -> None:
813 from livery.workshop import _quality
814
815 paths, arguments = split_arguments(words)
816 if arguments and refusal:
817 fail(refusal)
818 _quality.run_steps(
819 names,
820 paths,
821 fix=fix,
822 safe_fix=safe_fix,
823 point=point,
824 shard=shard,
825 arguments=arguments,
826 )
827
828
829#: A generated verb's paths and flags, each with its help text. They live at
830#: module level because footman reads a task's annotations in its
831#: module's namespace: a name local to the function making the verb
832#: does not resolve there, and the flag's value would arrive as text.
833_Paths = Annotated[
834 str, doc("the files or directories to check; the workspace when none")
835]
836_Fix = Annotated[bool, doc("rewrite what the steps can, then judge the rest")]
837_SafeFix = Annotated[bool, doc("fix, removing no code: safe for an edit in flight")]
838_Point = Annotated[
839 str, doc("select this CI point's tests: gate, merge, nightly, release")
840]
841_Shard = Annotated[
842 str, doc("run this shard's share of a sharded check leg: <i>of<n>, such as 2of4")
843]
844
845
846def _verb(
847 select: Callable[[], tuple[str, ...]],
848 *,
849 fixes: bool,
850 flags: frozenset[str],
851 what: str,
852 refusal: str = "",
853) -> Callable[..., None]:
854 """A verb over the steps *select* names, offering exactly the flags they read.
855
856 ``--fix`` and ``--safe-fix`` where a step can fix, ``--point`` and
857 ``--shard`` where one reads them (*flags*, from `FLAGS`); the
858 paths narrow the run to those files. The words after ``--`` reach
859 the step's tool, unless *refusal* says why this verb takes none.
860 One body per set of flags, because footman reads a verb's flags
861 from its signature, and a signature is written, not computed.
862 """
863
864 def run(
865 paths: tuple[str, ...],
866 *,
867 fix: bool = False,
868 safe_fix: bool = False,
869 point: str = "",
870 shard: str = "",
871 ) -> None:
872 _run_named(
873 select(),
874 paths,
875 refusal=refusal,
876 fix=fix,
877 safe_fix=safe_fix,
878 point=point,
879 shard=shard,
880 )
881
882 def bare(*paths: _Paths) -> None:
883 run(paths)
884
885 def with_point(*paths: _Paths, point: _Point = "") -> None:
886 run(paths, point=point)
887
888 def with_shard(*paths: _Paths, shard: _Shard = "") -> None:
889 run(paths, shard=shard)
890
891 def with_point_and_shard(
892 *paths: _Paths, point: _Point = "", shard: _Shard = ""
893 ) -> None:
894 run(paths, point=point, shard=shard)
895
896 def with_fix(*paths: _Paths, fix: _Fix = False, safe_fix: _SafeFix = False) -> None:
897 run(paths, fix=fix, safe_fix=safe_fix)
898
899 def with_fix_and_point(
900 *paths: _Paths,
901 fix: _Fix = False,
902 safe_fix: _SafeFix = False,
903 point: _Point = "",
904 ) -> None:
905 run(paths, fix=fix, safe_fix=safe_fix, point=point)
906
907 def with_fix_and_shard(
908 *paths: _Paths,
909 fix: _Fix = False,
910 safe_fix: _SafeFix = False,
911 shard: _Shard = "",
912 ) -> None:
913 run(paths, fix=fix, safe_fix=safe_fix, shard=shard)
914
915 def with_fix_point_and_shard(
916 *paths: _Paths,
917 fix: _Fix = False,
918 safe_fix: _SafeFix = False,
919 point: _Point = "",
920 shard: _Shard = "",
921 ) -> None:
922 run(paths, fix=fix, safe_fix=safe_fix, point=point, shard=shard)
923
924 bodies: dict[tuple[bool, bool, bool], Callable[..., None]] = {
925 (False, False, False): bare,
926 (False, True, False): with_point,
927 (False, False, True): with_shard,
928 (False, True, True): with_point_and_shard,
929 (True, False, False): with_fix,
930 (True, True, False): with_fix_and_point,
931 (True, False, True): with_fix_and_shard,
932 (True, True, True): with_fix_point_and_shard,
933 }
934 chosen = bodies[(fixes, "point" in flags, "shard" in flags)]
935 chosen.__doc__ = what
936 _MADE.add(chosen)
937 return chosen
938
939
940def _steps_of(phase: str) -> Callable[[], tuple[str, ...]]:
941 """Every registered step of *phase*, read when the verb runs."""
942
943 def select() -> tuple[str, ...]:
944 return tuple(record.name for record in _STEPS.values() if record.phase == phase)
945
946 return select
947
948
949def _one_step(name: str) -> Callable[[], tuple[str, ...]]:
950 def select() -> tuple[str, ...]:
951 return (name,)
952
953 return select
954
955
956def _is_made(task: Callable[..., object]) -> bool:
957 """Whether the generator made *task*, through the function footman wraps."""
958 return inspect.unwrap(task) in _MADE
959
960
961def _flags_of(task: Callable[..., object]) -> frozenset[str]:
962 """The flags a verb offers: its keyword parameters."""
963 return frozenset(
964 name
965 for name, parameter in inspect.signature(task).parameters.items()
966 if parameter.kind is inspect.Parameter.KEYWORD_ONLY
967 )
968
969
970def _place(parent: Group, key: str, verb: Callable[..., None]) -> None:
971 """Put *verb* at *key* in *parent*, unless a verb that serves it is there.
972
973 A verb the generator made is remade when its flags changed, so a
974 step registered later that fixes or reads the point reaches its
975 phase's verb; any other task at the address is left alone.
976 """
977 existing = parent.tasks.get(key)
978 if existing is not None:
979 if not _is_made(existing) or _flags_of(existing) == _flags_of(verb):
980 return
981 del parent.tasks[key]
982 if key == "default":
983 parent.default(verb)
984 else:
985 parent.task(name=key)(verb)
986
987
988def _prune(target: Group, tree: Mapping[str, Mapping[str, StepRecord]]) -> None:
989 """Remove the verbs the generator made whose steps are gone.
990
991 A phase with no step left loses its verb, and its group when that
992 leaves the group empty; a task another extension put there stays.
993 """
994 for phase, parent in list(target.groups.items()):
995 steps = tree.get(phase, {})
996 removed = False
997 for key, task in list(parent.tasks.items()):
998 kept = bool(steps) if key == "default" else key in steps
999 if _is_made(task) and not kept:
1000 del parent.tasks[key]
1001 removed = True
1002 if removed and not parent.tasks and not parent.groups:
1003 del target.groups[phase]
1004
1005
1006def generate_verbs(into: Group | None = None) -> None:
1007 """Make a verb per phase and a sub-task per step, from the registry.
1008
1009 ``fm test`` runs every step of the test phase and ``fm test.pytest``
1010 the one, each offering exactly the flags its steps read. A phase
1011 or a sub-task whose address a verb already holds is served by that
1012 verb, ``fm provenance``, and nothing is
1013 made there. Run again after extensions registered or withdrew steps,
1014 it makes what is new, remakes a verb whose flags changed, and
1015 removes a verb whose step is gone.
1016 """
1017 target = into if into is not None else root_group
1018 tree = verb_tree()
1019 _prune(target, tree)
1020 for phase, steps in tree.items():
1021 if phase in target.tasks:
1022 continue
1023 parent = target.groups.get(phase)
1024 default = None if parent is None else parent.default_task
1025 # The generator owns the phase's verb in a group it made; a
1026 # group of another verb's gets no default.
1027 owned = parent is None or (default is not None and _is_made(default))
1028 if parent is None:
1029 parent = target.group(phase, help=f"The {phase} steps, one task each")
1030 if owned:
1031 _place(
1032 parent,
1033 "default",
1034 _verb(
1035 _steps_of(phase),
1036 fixes=any(r.fix is not None for r in steps.values()),
1037 flags=frozenset(f for r in steps.values() for f in r.flags),
1038 what=f"Run every {phase} step, over the named paths or the"
1039 " workspace.",
1040 refusal=arguments_refusal(f"{prog()} {phase}", steps.values()),
1041 ),
1042 )
1043 for step, record in steps.items():
1044 if step in parent.groups:1044 ↛ 1045line 1044 didn't jump to line 1045 because the condition on line 1044 was never true
1045 continue
1046 _place(
1047 parent,
1048 step,
1049 _verb(
1050 _one_step(record.name),
1051 fixes=record.fix is not None,
1052 flags=frozenset(record.flags),
1053 what=f"Run the {record.name} step alone, over the named paths"
1054 " or the workspace"
1055 + (
1056 "; the words after -- go to its tool."
1057 if record.arguments
1058 else "."
1059 ),
1060 refusal=""
1061 if record.arguments
1062 else f"{record.name} wraps no tool, so it takes no arguments"
1063 " after --",
1064 ),
1065 )
1066
1067
1068def arguments_refusal(verb: str, records: Iterable[StepRecord]) -> str:
1069 """Why *verb*, which runs several steps, takes no arguments after ``--``.
1070
1071 The words after ``--`` are one tool's, so they go to a step's own
1072 verb; the refusal names those of *records* that take them.
1073 """
1074 takers = [f"{prog()} {r.phase}.{r.step}" for r in records if r.arguments]
1075 named = f": {', '.join(takers)}" if takers else ""
1076 return (
1077 f"`{verb}` runs several steps, and the words after -- are one tool's;"
1078 f" give them to the step's own verb{named}"
1079 )
1080
1081
1082def run_step(name: str, ctx: PhaseContext, *, fix: bool = False) -> None:
1083 """Run the step *name* over *ctx* through the walk: its judge, or its fix mode.
1084
1085 One step alone ([livery.workshop._phases.walk_steps][]): a workspace
1086 step runs once, a package step once per package it judges, and
1087 a step without a fix mode runs nothing in fix mode. The steps
1088 named in ``after`` are not run first: a caller running several
1089 steps by hand orders them itself, and the gate's walk brings them
1090 in ([livery.workshop._steps.with_earlier][]).
1091 """
1092 from livery.workshop._phases import walk_steps
1093
1094 walk_steps(ctx, (step_for(name),), fixing=fix)
1095
1096
1097def with_earlier(names: tuple[str, ...]) -> tuple[StepRecord, ...]:
1098 """The records of *names*, and of every step one of them runs after.
1099
1100 Followed through ``after`` transitively, in registration order,
1101 so a build's configure joins the walk that judges the build. An
1102 ``after`` naming a step an installed extension declares and the
1103 mount did not register orders nothing: clang-tidy's lint runs after
1104 cmake's configure in a workspace whose packages hold cmake, and
1105 alone in one whose packages do not.
1106
1107 Raises:
1108 Failed: when an ``after`` names a step that neither the base nor
1109 an installed extension declares, naming the registry.
1110 """
1111 wanted = set(names)
1112 queue = list(names)
1113 while queue:
1114 for earlier in step_for(queue.pop()).after:
1115 if earlier in wanted:
1116 continue
1117 if earlier not in _STEPS and installed_step(earlier):
1118 continue
1119 # A name nothing declares joins the queue, and its lookup
1120 # refuses naming the registry.
1121 wanted.add(earlier)
1122 queue.append(earlier)
1123 return tuple(record for record in _STEPS.values() if record.name in wanted)
1124
1125
1126def installed_step(name: str) -> bool:
1127 """Whether an installed extension or the base declares the step *name*.
1128
1129 *name* is ``<phase>.<step>``. Read from the declarations, so a step
1130 the mount did not register, one of an extension the workspace does
1131 not mount, is declared all the same.
1132 """
1133 from livery.workshop._declaration import installed_steps
1134
1135 return any(address.partition(":")[2] == name for address in installed_steps())
1136
1137
1138def _applies_now(record: StepRecord, ctx: PhaseContext) -> bool:
1139 if record.scope == WORKSPACE:
1140 if record.inputs is not None:
1141 # Listed, so the walk says when no file it reads changed.
1142 return True
1143 # A step without declared inputs narrows by its packages, so a
1144 # scope that holds none leaves it nothing to judge. Running it
1145 # would read the empty scope as the whole: the test step would
1146 # start the whole suite. Named files are a scope of their own,
1147 # which the step's claims judge.
1148 return bool(ctx.files) or not (ctx.scoped and not ctx.subset)
1149 return any(judges_package(record, ctx, p) for p in members(ctx))
1150
1151
1152def workspace_selected(ctx: PhaseContext) -> tuple[str, ...]:
1153 """The workspace steps with declared inputs that this run's changes select."""
1154 return tuple(
1155 record.name
1156 for record in _STEPS.values()
1157 if record.scope == WORKSPACE
1158 and record.inputs is not None
1159 and selected(record, ctx).runs
1160 )
1161
1162
1163def selected_files(ctx: PhaseContext) -> frozenset[str] | None:
1164 """The files the running step judges in this run; None for every file it reads.
1165
1166 A workspace step that declares ``inputs`` judges, in a run that
1167 knows what changed, the changed files among its inputs, and what
1168 its ``widen`` reference adds; in a run that knows nothing of the
1169 changes, it judges every file it reads, and this is None. The
1170 context names the running step, so a step asks with the context
1171 its run was handed.
1172
1173 Raises:
1174 Failed: when *ctx* names no step: one built by hand, outside
1175 a step's run.
1176 """
1177 if not ctx.step:
1178 fail(
1179 "selected_files() answers for the running step, and this"
1180 " PhaseContext names none: call it with the context a step's"
1181 " run is handed, which sets PhaseContext.step"
1182 )
1183 return _selected_files(step_for(ctx.step), ctx)
1184
1185
1186def _selected_files(record: StepRecord, ctx: PhaseContext) -> frozenset[str] | None:
1187 """The files *record* judges in this run; None for every file it reads."""
1188 selection = selected(record, ctx)
1189 return None if selection.whole else frozenset(selection.files)
1190
1191
1192#: What never counts as a manifest or a composed file's input, though it
1193#: sits beside them: prose, and the licence.
1194NOT_INPUTS = ("**/*.md", "LICENSE", "**/LICENSE")
1195
1196
1197def package_files(root: Path) -> tuple[str, ...]:
1198 """The files directly in each package's directory, as patterns.
1199
1200 The contract and the native manifests are among them, whatever the
1201 package's kind calls its manifest, so the base names none of them.
1202 """
1203 from livery.workshop._packages import package_directories
1204
1205 return tuple(
1206 f"{directory.relative_to(root).as_posix()}/*"
1207 for directory in package_directories(root)
1208 )
1209
1210
1211def graph_files(root: Path) -> tuple[str, ...]:
1212 """What the graph is made of: the contracts, the native manifests, a root src/.
1213
1214 The layering steps over the sources widen on them: a change there
1215 moves what the rules read, so every source is judged again.
1216 """
1217 return ("workshop.toml", "src/**", *package_files(root))
1218
1219
1220def graph_changed(changes: Changes) -> bool:
1221 """Tell whether a contract, a native manifest or a root ``src/`` changed.
1222
1223 A step over a language's sources widens on it through its
1224 ``widen`` reference, a function of its own extension that calls
1225 this one: the members, their module roots and what they declare
1226 come from these files, so a change to one judges every source
1227 again, as the base's own layering steps do. Prose and the licence
1228 beside a manifest never count.
1229
1230 Args:
1231 changes: What the run changed, as a step's ``widen`` reference
1232 receives it.
1233
1234 Returns:
1235 True when a changed path is the root contract, a file directly
1236 in a member's directory, or a file under ``src/`` at the root.
1237 """
1238 from livery.workshop._categories import matches
1239
1240 patterns = graph_files(changes.root)
1241 return any(
1242 matches(pattern, path)
1243 for path in changes.paths
1244 if not any(matches(ignored, path) for ignored in NOT_INPUTS)
1245 for pattern in patterns
1246 )
1247
1248
1249#: The files the generated outputs land in, for every forge: the CI
1250#: files, the entry script and the code-owners file.
1251GENERATED = (
1252 ".github/workflows/*.yml",
1253 ".gitea/workflows/*.yml",
1254 ".gitlab-ci.yml",
1255 "setup.sh",
1256 ".github/CODEOWNERS",
1257 ".gitlab/CODEOWNERS",
1258 ".gitea/CODEOWNERS",
1259 "CODEOWNERS",
1260 "docs/CODEOWNERS",
1261)
1262
1263
1264def _drift_reads(root: Path) -> tuple[str, ...]:
1265 """The tracked outputs drift judges: the receipted composed ones and the generated.
1266
1267 Read from the render's receipts, never by rendering: listing what
1268 is composed must cost less than composing it.
1269 """
1270 from livery.workshop._fragment_engine import read_rendered
1271 from livery.workshop._packages import package_directories
1272
1273 found = list(GENERATED)
1274 found += list(read_rendered(root))
1275 for directory in package_directories(root):
1276 home = directory.relative_to(root).as_posix()
1277 found += [f"{home}/{name}" for name in read_rendered(directory)]
1278 return tuple(found)
1279
1280
1281def _drift_widens(root: Path) -> tuple[str, ...]:
1282 """What every tracked output is made from: contracts, manifests, locks, extensions.
1283
1284 A listed extension whose sources live in a member package composes
1285 from them, so a change under them may move any output.
1286 """
1287 from livery.workshop._extensions import extension_names, extension_provider
1288 from livery.workshop._packages import discover_packages
1289
1290 packages = discover_packages(root)
1291 providers = {extension_provider(name, packages) for name in extension_names(root)}
1292 return (
1293 "workshop.toml",
1294 *package_files(root),
1295 "uv.lock",
1296 "toolroom.lock",
1297 *(f"{provider}/src/**" for provider in sorted(providers) if provider),
1298 )
1299
1300
1301def selected(record: StepRecord, ctx: PhaseContext) -> Selection:
1302 """What *record* judges in this run, by its declared inputs.
1303
1304 Everything for a step that declares none. The run's changes
1305 select, or the named files of `fm check <paths>` when there are no
1306 changes; a run with neither judges everything.
1307 """
1308 from livery.workshop._extensions import extension_provider
1309 from livery.workshop._influence import WHOLE, Changes, select
1310
1311 if record.inputs is None:1311 ↛ 1312line 1311 didn't jump to line 1312 because the condition on line 1311 was never true
1312 return WHOLE
1313 changes = ctx.changes
1314 if changes is None and ctx.files:
1315 changes = Changes(ctx.root, ctx.files)
1316 return select(
1317 record.inputs,
1318 changes,
1319 provider=extension_provider(record.extension, ctx.packages),
1320 packages=ctx.packages or None,
1321 )
1322
1323
1324#: The unit of every file under no package: the root's own files,
1325#: ``tasks.py`` and the workspace's tests among them.
1326ROOT_UNIT = "."
1327
1328
1329def catalogue(ctx: PhaseContext) -> dict[str, tuple[tuple[str, str], ...]] | None:
1330 """Every file git holds under the root, by unit, each with its category.
1331
1332 Listed once per walk: tracked files and untracked ones git does not
1333 ignore, as the tools see them, or the run's named files alone. A
1334 package's files are relative to it and categorised by the tables of
1335 the extensions it holds; a file under no package belongs to
1336 [livery.workshop._steps.ROOT_UNIT], relative to the root and
1337 categorised by the workspace's table. None when the root is not a
1338 git checkout, and then every step that applies runs.
1339 """
1340 from livery.workshop._categories import category_of
1341 from livery.workshop._packages import WORKSPACE_TESTS
1342 from livery.workshop._provenance import unit_of
1343
1344 if ctx.files:
1345 names: set[str] = set(ctx.files)
1346 else:
1347 try:
1348 names = set(git.ls_files(ctx.root, others=True))
1349 except git.GitError:
1350 return None
1351 packages = tuple(p for p in ctx.packages if p.path != WORKSPACE_TESTS)
1352 found: dict[str, list[tuple[str, str]]] = {}
1353 for name in sorted(names):
1354 if not (ctx.root / name).is_file():1354 ↛ 1355line 1354 didn't jump to line 1355 because the condition on line 1354 was never true
1355 continue
1356 unit, inside = unit_of(ctx.root, packages, name)
1357 if unit is None:1357 ↛ 1358line 1357 didn't jump to line 1358 because the condition on line 1357 was never true
1358 continue
1359 key = unit.path if unit in packages else ROOT_UNIT
1360 found.setdefault(key, []).append((inside, category_of(unit, inside).name))
1361 return {key: tuple(files) for key, files in found.items()}
1362
1363
1364def _scope_units(record: StepRecord, ctx: PhaseContext) -> tuple[str, ...]:
1365 """The units *record* reads in this run.
1366
1367 A package step reads the packages it judges. A workspace step
1368 reads every unit in a whole gate; in a scoped one, the subset's
1369 packages and the root's own files, since the workspace's tests
1370 ride every scoped run.
1371 """
1372 if record.scope == PACKAGE:
1373 return tuple(
1374 package.path
1375 for package in members(ctx)
1376 if judges_package(record, ctx, package)
1377 )
1378 if ctx.subset is None or ctx.catalogue is None:
1379 return tuple(ctx.catalogue or ())
1380 return (*(package.path for package in members(ctx)), ROOT_UNIT)
1381
1382
1383def reads_files(
1384 record: StepRecord, ctx: PhaseContext, units: tuple[str, ...] | None = None
1385) -> bool:
1386 """Whether *record*'s inputs reach a file of *units*, or of its scope in this run.
1387
1388 A step without inputs reads what its own body decides, and a run
1389 without a catalogue has no listing to judge by: both answer yes,
1390 except over named files, which a step without inputs cannot say
1391 it reads.
1392 """
1393 if _uses_change_selection(record):
1394 if ctx.changes is not None or ctx.files:
1395 if ctx.files and ctx.safe and not record.category_reads:
1396 return False
1397 return selected(record, ctx).runs
1398 if record.inputs is not None and not all(
1399 e.category for e in record.inputs.reads
1400 ):
1401 return True
1402 entries = record.category_reads
1403 if not entries:
1404 return not ctx.files
1405 if ctx.catalogue is None:
1406 return True
1407 from livery.workshop._packages import WORKSPACE_TESTS
1408
1409 for unit in units if units is not None else _scope_units(record, ctx):
1410 unit_files = ctx.catalogue.get(unit, ())
1411 if not unit_files and unit == WORKSPACE_TESTS:
1412 prefix = f"{WORKSPACE_TESTS}/"
1413 unit_files = tuple(
1414 item
1415 for item in ctx.catalogue.get(ROOT_UNIT, ())
1416 if item[0].startswith(prefix)
1417 )
1418 for relative, category in unit_files:
1419 if any(e.category == category and _reaches(e, relative) for e in entries):
1420 return True
1421 return False
1422
1423
1424def claimed_files(
1425 record: StepRecord, ctx: PhaseContext, unit: str | None = None
1426) -> tuple[str, ...]:
1427 """The files of the run's catalogue *record*'s category reads reach, absolute.
1428
1429 For a run over named files: the ones a step takes. *unit* keeps
1430 one package's alone, for a package step.
1431 """
1432 entries = record.category_reads
1433 found: list[str] = []
1434 for key, files in (ctx.catalogue or {}).items():
1435 if unit is not None and key != unit:
1436 continue
1437 base = ctx.root if key == ROOT_UNIT else ctx.root / key
1438 for relative, category in files:
1439 if any(e.category == category and _reaches(e, relative) for e in entries):
1440 found.append(str(base / relative))
1441 return tuple(sorted(found))
1442
1443
1444def with_files(names: tuple[str, ...], ctx: PhaseContext) -> tuple[str, ...]:
1445 """*names* less the steps with no file to read in this run, each skip said.
1446
1447 No process starts for a step whose inputs reach nothing in scope.
1448 """
1449 kept: list[str] = []
1450 where = (
1451 "the named files"
1452 if ctx.files
1453 else "the affected packages"
1454 if ctx.scoped
1455 else "the workspace"
1456 )
1457 for name in names:
1458 record = _STEPS[name]
1459 if reads_files(record, ctx):
1460 kept.append(name)
1461 continue
1462 said = (
1463 "the changed files"
1464 if _uses_change_selection(record) and ctx.changes is not None
1465 else where
1466 )
1467 print(f" {name}: no file it reads in {said}; not run")
1468 return tuple(kept)
1469
1470
1471def on_this_shard(names: tuple[str, ...], ctx: PhaseContext) -> tuple[str, ...]:
1472 """*names* less the steps this shard leaves to the first shard, each said.
1473
1474 A step that declares ``shard`` among its flags runs on every shard
1475 of a sharded check leg and runs its share, the shard in its
1476 context's ``shard``. A step that does not runs whole, so it runs
1477 on the first shard alone: on any other shard it is left out, and a
1478 line says so. On the first shard, and on a run that is one shard
1479 of one, every step stays and nothing is said.
1480 """
1481 if ctx.shard.first:
1482 return names
1483 kept: list[str] = []
1484 for name in names:
1485 if "shard" in _STEPS[name].flags:
1486 kept.append(name)
1487 continue
1488 print(f" {name}: left to the first shard (this leg is {ctx.shard})")
1489 return tuple(kept)
1490
1491
1492def _gated(record: StepRecord) -> bool:
1493 """Whether the gate runs *record*: its phase declares itself gated."""
1494 from livery.workshop import _phases
1495
1496 spec = _phases.declared_phases().get(record.phase)
1497 return spec is None or spec.gated
1498
1499
1500def rewriters(ctx: PhaseContext) -> tuple[str, ...]:
1501 """The steps whose fix mode runs, serially and in order, under --fix.
1502
1503 Those of the gated phases; empty unless the gate runs in its fix
1504 mode. They run in registration order, the base's first and then
1505 each extension's in composition order, with each step after the
1506 ones it names in ``after`` and the providers of the keys it reads.
1507
1508 Raises:
1509 OrderCycle: when the rewriters' order has no start, naming the
1510 members of one cycle.
1511 """
1512 if not ctx.fix:
1513 return ()
1514 from livery.workshop._phases import phase_order
1515
1516 records = [
1517 record
1518 for record in _STEPS.values()
1519 if record.fix is not None and _gated(record) and _applies_now(record, ctx)
1520 ]
1521 return tuple(record.name for record in phase_order(records))
1522
1523
1524def judges(ctx: PhaseContext) -> tuple[str, ...]:
1525 """The steps the gate judges together, in registration order.
1526
1527 Those of the gated phases. A step that rewrote in this run is not
1528 judged again: re-judging the style it just wrote would only spend
1529 time agreeing.
1530 """
1531 names = []
1532 for record in _STEPS.values():
1533 if not _gated(record) or not _applies_now(record, ctx):
1534 continue
1535 if record.fix is not None and ctx.fix:
1536 continue
1537 names.append(record.name)
1538 return tuple(names)
1539
1540
1541#: The whole repository, as a step that walks it from the root reads it.
1542#: [livery.workshop._steps.scoped_paths][] answers it when a step
1543#: judges its configured whole; a tool that reads ``.`` as more than
1544#: its configuration names takes no paths then.
1545WHOLE = (".",)
1546
1547
1548def _workspace_unit(ctx: PhaseContext) -> tuple[Package, ...]:
1549 """The workspace's own tests, when this run judges them as a unit."""
1550 from livery.workshop._packages import WORKSPACE_TESTS
1551
1552 return tuple(p for p in ctx.judged if p.path == WORKSPACE_TESTS)
1553
1554
1555def _claimed(name: str, natives: tuple[Package, ...]) -> tuple[str, ...]:
1556 """The files of the native members the step *name* claims, by path.
1557
1558 A native member's directories are not a python step's to walk, so
1559 its files come by name: its ``conanfile.py``, say.
1560 """
1561 record = step_for(name)
1562 return tuple(f"{p.path}/{f}" for p in natives for f in judged_files(record, p))
1563
1564
1565def _every_unit_reached(ctx: PhaseContext, record: StepRecord, chosen: int) -> bool:
1566 """Whether a scoped run over *chosen* units reaches every unit *record* judges.
1567
1568 Every member the step judges, the workspace's tests unit among
1569 them while the step judges it, with none turned off anywhere: the
1570 whole would reach the same, so the step runs over its configured
1571 whole instead of a list naming every unit.
1572 """
1573 from livery.workshop._packages import WORKSPACE_TESTS
1574
1575 everyone = tuple(p for p in ctx.packages if p.path != WORKSPACE_TESTS)
1576 gated_all = judged_by(record, everyone, quiet=True)
1577 # The workspace's tests unit rides in the scope, not always among
1578 # the packages: counted once from either.
1579 suites = tuple(p for p in (*ctx.packages, *ctx.judged) if p.path == WORKSPACE_TESTS)
1580 tests_unit = {p.path for p in judged_by(record, suites, quiet=True)}
1581 units = len(gated_all) + len(tests_unit)
1582 on = all(option_value(record, p, "enabled") for p in gated_all)
1583 return on and 0 < units <= chosen
1584
1585
1586def scoped_paths(ctx: PhaseContext, name: str) -> tuple[str, ...]:
1587 """The paths the path-narrowing step *name* judges in this run.
1588
1589 The files the run names, when it names any. Otherwise the whole
1590 tree, ``.``, when the run reaches every member the step judges;
1591 else the ``src`` and ``tests`` directories of the reached members
1592 holding the runtime's language, the workspace's own tests when the
1593 run and the step judge them, and the files the step's claims give
1594 it in the other reached members.
1595 """
1596 from livery.workshop._packages import holds_runtime_language, package_paths
1597
1598 record = step_for(name)
1599 if ctx.files:
1600 return claimed_files(record, ctx)
1601 gated_members = judged_by(record, members(ctx))
1602 chosen_members = enabled(name, gated_members)
1603 pythons = tuple(p for p in chosen_members if holds_runtime_language(p))
1604 natives = tuple(p for p in chosen_members if not holds_runtime_language(p))
1605 unit = judged_by(record, _workspace_unit(ctx), quiet=True)
1606
1607 def holding(packages: tuple[Package, ...]) -> tuple[str, ...]:
1608 # A directory with no file the claims reach has nothing to
1609 # judge, and a tool such as mypy refuses one it is handed.
1610 return tuple(
1611 path
1612 for path in package_paths(packages)
1613 if _holds_claimed(record, ctx.root / path)
1614 )
1615
1616 if ctx.subset is None:
1617 if len(chosen_members) == len(gated_members):1617 ↛ 1619line 1617 didn't jump to line 1619 because the condition on line 1617 was always true
1618 return WHOLE
1619 chosen = holding(pythons + unit) + _claimed(name, natives)
1620 return chosen or WHOLE
1621 judged = tuple(p for p in ctx.subset if p in pythons or p in unit)
1622 present = tuple(p for p in natives if p in ctx.subset)
1623 if _every_unit_reached(ctx, record, len(judged) + len(present)):
1624 return WHOLE
1625 return holding(judged) + _claimed(name, present)
1626
1627
1628def _holds_claimed(record: StepRecord, directory: Path) -> bool:
1629 """Whether *directory* holds a file with a suffix *record*'s inputs read.
1630
1631 A step with no category read, or one that names no suffix, reads every
1632 file, so any directory holds one.
1633 """
1634 entries = record.category_reads
1635 if not entries or any(not entry.suffixes for entry in entries):1635 ↛ 1636line 1635 didn't jump to line 1636 because the condition on line 1635 was never true
1636 return True
1637 suffixes = sorted({suffix for entry in entries for suffix in entry.suffixes})
1638 return any(next(directory.rglob(f"*{suffix}"), None) for suffix in suffixes)
1639
1640
1641def scoped_files(
1642 ctx: PhaseContext, name: str, package: Package | None = None
1643) -> tuple[Path, ...]:
1644 """The files of *package* the step *name* judges in this run, absolute.
1645
1646 *package* is the run's own package unless named: a package step
1647 names none, and a step that narrows by packages names each one
1648 [livery.workshop.scoped_packages][] answers. The files the run
1649 names, when it names any; else every file the step's claims reach
1650 in the package, an untracked new one among them.
1651
1652 Raises:
1653 Failed: when neither *package* nor the run names a package.
1654 """
1655 record = step_for(name)
1656 package = package or ctx.package
1657 if package is None:1657 ↛ 1658line 1657 didn't jump to line 1658 because the condition on line 1657 was never true
1658 fail(f"{name} judges one package at a time, and this run names none")
1659 if ctx.files:
1660 return tuple(Path(path) for path in claimed_files(record, ctx, package.path))
1661 return tuple(package.directory / path for path in judged_files(record, package))
1662
1663
1664def scoped_packages(ctx: PhaseContext, name: str) -> tuple[Package, ...]:
1665 """The members the package-narrowing step *name* judges in this run.
1666
1667 The members holding an extension it names, in a scoped run those
1668 of the subset, less each one that turned the step off in its
1669 contract. Each skip is printed, so a narrowed gate names what it
1670 left out. A run over named files keeps the members holding a named
1671 file the step claims. The workspace's own tests are not a member.
1672 """
1673 record = step_for(name)
1674 chosen = enabled(name, judged_by(record, members(ctx)))
1675 if not ctx.files:
1676 return chosen
1677 return tuple(p for p in chosen if claimed_files(record, ctx, p.path))
1678
1679
1680def scoped_suite(ctx: PhaseContext, name: str) -> Package | None:
1681 """The workspace's own tests, when the step *name* judges them.
1682
1683 The unit ([livery.workshop.workspace_suite][]) holds the root's
1684 set, so the step judges it while that set holds an extension the
1685 step names. Its tests reach any package, so every run of the step
1686 runs them then. None when the workspace has no ``tests``
1687 directory. None as well when the step does not judge the unit, and
1688 then a line says why.
1689 """
1690 from livery.workshop._packages import workspace_suite
1691
1692 record = step_for(name)
1693 unit = workspace_suite(ctx.root)
1694 if unit is None or judges_unit(record, unit):
1695 return unit
1696 wanted = " or ".join(record.extensions)
1697 which = "it" if len(record.extensions) == 1 else "one"
1698 print(
1699 f" {name}: {unit.path} skips (the root's set holds no {wanted};"
1700 f" list {which} in [workspace] extensions to run them)"
1701 )
1702 return None
1703
1704
1705def declared_step(name: str) -> StepRecord:
1706 """The step *name*: its registered record, else the installed declaration's.
1707
1708 A process that mounted nothing holds the base's own steps alone,
1709 so an extension's step is read from the installed extension that
1710 declares it, the first by name (`installed_record` in the
1711 extensions module).
1712
1713 Raises:
1714 Failed: when no installed extension declares the step, naming it.
1715 """
1716 record = _STEPS.get(name)
1717 if record is not None:
1718 return record
1719 from livery.workshop._extensions import installed_record
1720
1721 found = installed_record(name)
1722 if found is None:
1723 fail(
1724 f"no installed extension declares the step {name!r}; install the"
1725 f" extension that declares it (`{prog()} sync` installs the ones the"
1726 " workspace lists), or name a step an installed extension declares"
1727 )
1728 return found
1729
1730
1731def step_option(name: str, package: Package, option: str) -> object:
1732 """What *package* sets for the step *name*'s *option*, or the option's default.
1733
1734 The deepest of the package's tables that sets it wins. A step the
1735 mount registered answers from its registration. A step it did not
1736 register, as in a process that mounted nothing, answers from the
1737 installed extension that declares it.
1738
1739 Raises:
1740 Failed: when no installed extension declares the step, naming
1741 it; when the step declares no *option*, naming its options;
1742 or when the package sets a value of the wrong type, naming
1743 the table.
1744 """
1745 return option_value(declared_step(name), package, option)
1746
1747
1748def step_extensions(name: str) -> tuple[str, ...]:
1749 """The extensions the step *name* names in its ``extensions`` list.
1750
1751 The step judges a package whose set holds one of them
1752 ([livery.workshop.extension_set][]), and every package when it
1753 names none. The step is read as [livery.workshop.step_option][]
1754 reads it: registered, else installed.
1755
1756 Raises:
1757 Failed: when no installed extension declares the step, naming it.
1758 """
1759 return declared_step(name).extensions
1760
1761
1762def step_enabled(root: Path, name: str) -> bool:
1763 """Whether the step *name* is on in the workspace at *root*.
1764
1765 A step its extension declares on is always on. A step it declares
1766 ``enabled = false`` is on while the root contract turns it on, with
1767 ``enabled = true`` in the step's ``[phases.<phase>.<step>]`` table,
1768 and registers only then. A package turns a step off for itself
1769 with the step's ``enabled`` option, which
1770 [livery.workshop.step_option][] reads.
1771
1772 Raises:
1773 Failed: when no installed extension declares the step, naming it.
1774 """
1775 if declared_step(name).enabled:
1776 return True
1777 from livery.workshop._extensions import enabled_steps
1778
1779 return name in enabled_steps(root)
1780
1781
1782def tested(units: tuple[Package, ...]) -> tuple[Package, ...]:
1783 """Keep the *units* whose suites a registered step of the test phase runs.
1784
1785 A step runs a unit's suite while the unit's set holds an extension
1786 the step names, and every unit's when it names none: a member holds
1787 its own set, and the workspace's own tests
1788 ([livery.workshop.WORKSPACE_TESTS][]) hold the root's set. A step
1789 of package scope runs over one member at a time and never over the
1790 workspace's own tests.
1791
1792 Returns:
1793 The units of *units* some test step runs, in *units* order.
1794 """
1795 from livery.workshop._packages import WORKSPACE_TESTS
1796
1797 tests = [record for record in _STEPS.values() if record.phase == "test"]
1798 return tuple(
1799 unit
1800 for unit in units
1801 if any(
1802 judges_unit(record, unit)
1803 and not (unit.path == WORKSPACE_TESTS and record.scope == PACKAGE)
1804 for record in tests
1805 )
1806 )
1807
1808
1809def _register_builtin() -> None:
1810 """Register the workshop's own steps, in the order the rewriters run.
1811
1812 Each judges the whole tree: the render's drift, the provenance of
1813 the shipped content, the graph and the base's rules over the
1814 sources. A step that judges one package at a time is an
1815 extension's, and registers at mount.
1816 """
1817 from livery.workshop._influence import InputEntry, Inputs
1818 from livery.workshop._packages import RULES
1819
1820 def render_run(ctx: PhaseContext) -> None:
1821 from livery.workshop import _quality
1822
1823 _quality.drift_check(files=_selected_files(step_for("drift.check"), ctx))
1824
1825 def render_fix(ctx: PhaseContext) -> None:
1826 # A rewriter is not judged again under --fix, so the fix judges
1827 # what it leaves, as the provenance fix does.
1828 from livery.workshop import _quality
1829 from livery.workshop._shipped_files import deliver, relocate
1830 from livery.workshop._templates import apply_generated
1831
1832 for line in relocate(ctx.root) + deliver(ctx.root):
1833 print(line)
1834 for path in apply_generated(ctx.root):
1835 print(f" generated: {path}")
1836 _quality.drift_check()
1837
1838 def provenance_run(ctx: PhaseContext) -> None:
1839 from livery.workshop import _provenance
1840
1841 _provenance.check_content(
1842 files=_selected_files(step_for("provenance.check"), ctx)
1843 )
1844
1845 def provenance_fix(ctx: PhaseContext) -> None:
1846 from livery.workshop import _provenance
1847
1848 _provenance.check_content(
1849 fix=True, files=_selected_files(step_for("provenance.check"), ctx)
1850 )
1851
1852 def graph_run(ctx: PhaseContext) -> None:
1853 from livery.workshop._packages import verify_graph
1854
1855 verify_graph(ctx.root)
1856
1857 def relocked(root: Path, written: list[str]) -> None:
1858 """Print each line a fix *written*, and lock again when one moved a manifest."""
1859 from livery.workshop._uv import run_uv
1860
1861 for line in written:
1862 print(line)
1863 if any("pyproject.toml" in line for line in written):
1864 # Each line names the files written. A requirement written
1865 # into a uv member's manifest moves the uv workspace's lock,
1866 # so the fix locks again and leaves the tree consistent, as
1867 # a person would after editing by hand.
1868 run_uv("lock", root=root)
1869
1870 def graph_fix(ctx: PhaseContext) -> None:
1871 from livery.workshop._extensions import write_extensions
1872 from livery.workshop._packages import verify_graph, write_test_requirements
1873
1874 for line in write_extensions(ctx.root):1874 ↛ 1875line 1874 didn't jump to line 1875 because the loop on line 1874 never started
1875 print(line)
1876 relocked(ctx.root, write_test_requirements(ctx.root))
1877 verify_graph(ctx.root)
1878
1879 def rule_run(step: str) -> Callable[[PhaseContext], None]:
1880 """The judge of the base's layering step *step*, over the files it reaches."""
1881
1882 def run(ctx: PhaseContext) -> None:
1883 from livery.workshop._packages import rule_problems
1884
1885 files = _selected_files(step_for(f"layering.{step}"), ctx)
1886 problems = rule_problems(step, ctx.root, ctx.packages, files)
1887 if problems:
1888 fail("the workspace breaks its layering:\n " + "\n ".join(problems))
1889
1890 return run
1891
1892 def sibling_fix(ctx: PhaseContext) -> None:
1893 from dataclasses import replace
1894
1895 from livery.workshop._packages import discover_packages, write_edges
1896
1897 written = write_edges(ctx.root)
1898 relocked(ctx.root, written)
1899 if written:
1900 # The run read the packages before the fix wrote their
1901 # contracts, and the judge reads them as the fix left them.
1902 ctx = replace(ctx, packages=discover_packages(ctx.root))
1903 # A rewriter is not judged again under --fix, so the fix judges
1904 # what it leaves.
1905 rule_run("sibling-references")(ctx)
1906
1907 for record in (
1908 StepRecord(
1909 "check",
1910 "drift",
1911 render_run,
1912 fix=render_fix,
1913 inputs=Inputs(
1914 reads=(
1915 InputEntry(channel="generated"),
1916 InputEntry(channel="composed"),
1917 InputEntry(channel="computed"),
1918 ),
1919 widens=(
1920 InputEntry(set="graph"),
1921 InputEntry(channel="toolchain"),
1922 InputEntry(set="extension-sources"),
1923 ),
1924 ),
1925 ),
1926 StepRecord(
1927 "check",
1928 "provenance",
1929 provenance_run,
1930 fix=provenance_fix,
1931 inputs=Inputs(reads=(InputEntry(channel="extension-content"),)),
1932 ),
1933 StepRecord(
1934 "graph",
1935 "layering",
1936 graph_run,
1937 fix=graph_fix,
1938 inputs=Inputs(reads=(InputEntry(set="graph"),), per_file=False),
1939 ),
1940 # The base's rules over the sources, one step each; the sibling
1941 # step's fix is the one rewrite among them.
1942 *(
1943 StepRecord(
1944 step,
1945 "layering",
1946 rule_run(step),
1947 fix=sibling_fix if step == "sibling-references" else None,
1948 inputs=Inputs(
1949 reads=(
1950 InputEntry(category="source", suffixes=(".py",)),
1951 InputEntry(category="test", suffixes=(".py",)),
1952 InputEntry(category="test-support", suffixes=(".py",)),
1953 InputEntry(set="tasks"),
1954 ),
1955 widens=(InputEntry(set="graph"),),
1956 ),
1957 )
1958 for step in RULES
1959 ),
1960 ):
1961 register_step(record)
1962
1963
1964_register_builtin()
1965
1966#: The registry as the import leaves it, for `snapshot(initial=True)`.
1967_BUILTIN_STATE = snapshot()