Coverage for packages/workshop/src/livery/workshop/_phases.py: 95%

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 declared phases, the context a step receives, and the walk that runs steps.
2
3A phase is declared, by the base in the ``[phases]`` section of its
4``contract.toml`` and by an extension under ``[phases.<phase>]`` in its
5``extension.toml``, in one grammar ([livery.workshop._phases.PhaseSpec][]):
6the keys the engine running it gives its steps, typed; its level,
7``package`` for a phase whose steps run once per package and
8``workspace`` for one whose steps run once; whether ``fm check`` runs
9it; the phases it follows in the train's order; and whether a verb is
10generated for it. [livery.workshop._phases.declared_phases][] is every
11declared phase by name, the base's and then each installed
12extension's; a phase nobody declares refuses naming the declared ones,
13and two extensions declaring one phase refuse naming both.
14
15Every phase's steps run through the one walk,
16[livery.workshop._phases.walk_steps][]: each step a footman step inside
17one ``parallel()`` block, a workspace step once and a package step
18once per package in scope, independent steps concurrently, a step
19after the steps it names in ``after`` and after the providers of the
20keys it ``reads``. The gate runs its phases through it with its own
21engine around it ([livery.workshop._quality.walk][]); the release
22train and ``fm run`` run a package's lifecycle phases through it
23([livery.workshop._lifecycle][]), the steps those of the package's set
24([livery.workshop._phases.phase_steps][]); ``fm sync`` runs the sync
25phase's registered steps through it over the workspace, and
26[livery.workshop.run_phase][] those of any phase the gate never runs,
27first removing what a step that stopped running declared it writes.
28Each step receives the one context, [livery.workshop.PhaseContext][].
29
30A step table's ``deletes`` names steps of other extensions, each
31``<owner>:<phase>.<step>`` with its reason, that never run for a
32package whose set holds the deleting extension: the set's steps leave
33them out, and the walk skips such a package for a registered step it
34deletes, saying why. A package whose set does not hold the deleting
35extension runs them.
36
37The engine running a walk gives each phase its keys, by phase. The
38train builds on the isolated side in the ``release`` configuration and
39tests on the isolated side once per resolution it proves; the gate
40builds on the tree side in the ``instrumented`` configuration, and
41``fm run`` on the tree side in ``debug``. A phase whose declaration
42holds ``isolated`` has two sides: the tree, and the isolated one, from
43a copy of the sources in a fresh environment. A step that declares
44``isolated`` serves the side it names alone, and one that declares
45nothing serves both ([livery.workshop._phases.serves][]).
46
47Two steps providing one key, a key nobody provides, a step declaring a
48side of a phase that has one side, and an order with no start refuse
49before any step runs ([livery.workshop._phases.phase_problems][]);
50``layering.graph`` names them for each package.
51"""
52
53from __future__ import annotations
54
55import functools
56import threading
57from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
58from dataclasses import dataclass, field, replace
59from pathlib import Path
60from typing import TYPE_CHECKING, Any, cast
61
62from livery.footman import fail, parallel, step
63from livery.workshop._shard import ONE, Shard
64
65if TYPE_CHECKING:
66 from livery.workshop._composition import Lookup
67 from livery.workshop._influence import Changes
68 from livery.workshop._packages import Package
69 from livery.workshop._steps import StepRecord
70
71#: The levels a phase runs at: over one package at a time, or over the
72#: workspace once.
73PACKAGE_LEVEL = "package"
74WORKSPACE_LEVEL = "workspace"
75LEVELS = (PACKAGE_LEVEL, WORKSPACE_LEVEL)
76
77#: The types an engine key or a context key may take.
78TYPES = ("str", "int", "bool", "path", "strs", "paths", "table")
79
80#: The extension that declares the base's phases.
81BASE = "livery.workshop"
82
83
84@dataclass(frozen=True)
85class PhaseSpec:
86 """A phase as its declarer declares it: one ``[phases.<phase>]`` table.
87
88 Attributes:
89 name: The phase's name, ``build``.
90 keys: The keys the engine running the phase gives its steps,
91 each to its type; a step reads one like any key, and no
92 step provides one.
93 level: ``package`` for a phase whose steps run once per
94 package in scope; ``workspace`` for one whose steps run
95 once over the workspace.
96 gated: Whether ``fm check`` runs the phase.
97 after: The phases this one follows in the train's order.
98 verb: Whether a verb is generated for the phase, ``fm <phase>``
99 with a sub-task per step.
100 extension: The extension that declares the phase; the base for
101 its own.
102 """
103
104 name: str
105 keys: Mapping[str, str] = field(default_factory=dict[str, str])
106 level: str = PACKAGE_LEVEL
107 gated: bool = False
108 after: tuple[str, ...] = ()
109 verb: bool = False
110 extension: str = BASE
111
112
113class PhaseError(RuntimeError):
114 """A phase whose steps cannot run as declared, or a step's misuse of the context.
115
116 Raised before any step runs for the phase's own problems, and from
117 [livery.workshop.PhaseContext.provide][] or
118 [livery.workshop.PhaseContext.read][] for a key the running step's
119 table does not declare, or a value of another type.
120 """
121
122
123@functools.cache
124def base_phases() -> dict[str, PhaseSpec]:
125 """The base's phases, read from the ``[phases]`` section of its contract file.
126
127 In the file's order, each spec naming the base as its declarer.
128
129 Raises:
130 DeclarationError: when a section is off the shape a phase's
131 declaration has.
132 """
133 from livery.workshop._contract_keys import BASE_FILE, base_contract
134 from livery.workshop._declaration import phase_specs_of
135
136 return phase_specs_of(base_contract(), BASE_FILE, extension=BASE)
137
138
139@functools.cache
140def declared_phases() -> dict[str, PhaseSpec]:
141 """Every declared phase by name: the base's, then each installed extension's.
142
143 An installed extension's declaration is read whether the workspace
144 lists it or not, so a step into its phase reads the same anywhere;
145 the mount refuses the step while the declarer is not listed. Each
146 phase's ``after`` names declared phases, and the order they give
147 has a start.
148
149 Raises:
150 DeclarationError: when two extensions declare one phase, a
151 phase follows one nobody declares, or the order has no
152 start.
153 """
154 from livery.footman import installed_entry_points
155 from livery.workshop._declaration import DeclarationError, phase_declarations
156
157 found = dict(base_phases())
158 for entry in installed_entry_points("workshop.extensions"):
159 for spec in phase_declarations(entry.name, entry.value.partition(":")[0]):
160 held = found.get(spec.name)
161 if held is not None and held.extension != spec.extension:
162 both = " and ".join(sorted((held.extension, spec.extension)))
163 raise DeclarationError(
164 f"the {spec.name} phase is declared by both {both}; one extension"
165 " declares a phase"
166 )
167 found[spec.name] = spec
168 _judge_after(found)
169 return found
170
171
172def _judge_after(specs: Mapping[str, PhaseSpec]) -> None:
173 """Refuse an ``after`` naming no declared phase, and an order with no start."""
174 from livery.workshop._declaration import DeclarationError
175
176 for spec in specs.values():
177 for name in spec.after:
178 if name not in specs:
179 raise DeclarationError(
180 f"{spec.extension} declares the {spec.name} phase after {name},"
181 f" which no extension declares; the phases are"
182 f" {', '.join(specs)}"
183 )
184 done: set[str] = set()
185 path: list[str] = []
186
187 def visit(name: str) -> None:
188 if name in done:
189 return
190 if name in path:
191 cycle = path[path.index(name) :]
192 raise DeclarationError(
193 "the phases' order has no start: "
194 + " after ".join((name, *reversed(cycle)))
195 + "; remove an after among them"
196 )
197 path.append(name)
198 for earlier in specs[name].after:
199 visit(earlier)
200 path.pop()
201 done.add(name)
202
203 for name in specs:
204 visit(name)
205
206
207def phase_spec(name: str) -> PhaseSpec:
208 """The declared phase *name*; refuses naming the declared ones.
209
210 Raises:
211 PhaseError: when no extension declares *name*.
212 """
213 specs = declared_phases()
214 found = specs.get(name)
215 if found is None:
216 raise PhaseError(
217 f"{name} is not a declared phase; the phases are {', '.join(specs)}"
218 )
219 return found
220
221
222def lifecycle_phases() -> tuple[str, ...]:
223 """The package-level phases, in declaration order: a package's lifecycle."""
224 return tuple(
225 name for name, spec in declared_phases().items() if spec.level == PACKAGE_LEVEL
226 )
227
228
229def _holds(kind: str, value: object) -> bool:
230 """Whether *value* is of the context type *kind*."""
231 if kind == "str":
232 return isinstance(value, str)
233 if kind == "int":
234 return isinstance(value, int) and not isinstance(value, bool)
235 if kind == "bool":
236 return isinstance(value, bool)
237 if kind == "path":
238 return isinstance(value, Path)
239 if kind in ("strs", "paths"):
240 member = str if kind == "strs" else Path
241 return isinstance(value, (list, tuple)) and all(
242 isinstance(item, member) for item in value
243 )
244 return isinstance(value, dict)
245
246
247@dataclass
248class _Shared:
249 """What every view of one walk's context writes and reads.
250
251 Attributes:
252 values: The keys the steps provided, by the package they ran
253 over (an empty path for a workspace step), each to its
254 value.
255 exit_code: The exit code the ``run`` phase's step recorded.
256 lock: Held around a write, since the steps run concurrently.
257 """
258
259 values: dict[str, dict[str, object]] = field(
260 default_factory=dict[str, dict[str, object]]
261 )
262 exit_code: int = 0
263 lock: threading.Lock = field(default_factory=threading.Lock)
264
265
266@dataclass(frozen=True)
267class PhaseContext:
268 """What a run hands a step: the workspace, the run's scope, and the phase's keys.
269
270 One context serves one walk, and every step receives its own view
271 of it, with the step named in ``step`` and, for a package step,
272 the package it runs over in ``package``. A step writes the keys its
273 table ``provides`` with [livery.workshop.PhaseContext.provide][]
274 and reads the ones it ``reads`` with
275 [livery.workshop.PhaseContext.read][]; the views share what is
276 written, so the engine reads a provided key back from the context
277 the walk returns ([livery.workshop.PhaseContext.result][]). The
278 ``run`` phase's step that starts the executable records its exit
279 code with [livery.workshop.PhaseContext.exit][]. A view is frozen:
280 a step that assigns an attribute changes a copy nobody reads, so
281 the keys and the exit code go through the methods.
282
283 Attributes:
284 root: The workspace root.
285 packages: Every package the workspace carries.
286 subset: The packages a scoped gate judges, or None for the
287 whole gate.
288 tests: Per package path, the test files that stand for the
289 package's suite in this run.
290 examples: The package paths whose changed files are examples
291 and nothing else: their examples run and no suite.
292 fix: Whether the rewriters run in their fix mode.
293 files: The files the run is limited to, root-relative, from
294 `fm check <paths>`; empty when the scope decides.
295 safe: Whether the fixers run in their in-flight mode, which
296 removes no code: ``--safe-fix``.
297 point: The CI point whose tests the test phase selects; empty
298 for the gate's own.
299 shard: The shard of a sharded check leg this run is, as
300 ``fm check --shard`` or the leg's label names it
301 ([livery.workshop.Shard][]); one shard of one for a run
302 that is not split. A step that declares ``shard`` among
303 its flags runs its share of it, and the walk runs every
304 other step on the first shard alone
305 ([livery.workshop._steps.on_this_shard][]).
306 catalogue: Every file the run may read, by unit, each with its
307 category, listed once per walk by
308 [livery.workshop._steps.catalogue][]; None when there is
309 no listing, and then every step that applies runs.
310 package: The package a package step runs over, else None.
311 selection: The test files selected for that package, relative
312 to it, else empty.
313 changes: What changed since the tree the run measures from,
314 which selects what each workspace step with declared
315 inputs judges ([livery.workshop._influence.select][]); None
316 when the run knows nothing of it, and then each judges
317 everything.
318 arguments: The words after ``--``, the same for every step of
319 the run: on a step's own verb, which a step that takes
320 them hands its tool (``StepRecord.arguments``, a
321 template's ``{arguments}``), and on ``fm run``, which the
322 step starting the executable passes it; empty in every
323 other run.
324 step: The running step's name, ``<phase>.<step>``, which the
325 walk sets as it hands the context to the step; empty
326 outside a step's run.
327 phase: The phase the engine runs, ``build``, whose given keys
328 [livery.workshop.PhaseContext.result][] reads back; on a
329 step's view, the step's own phase, whose given keys the
330 step reads. Empty for a walk over several phases, the
331 gate's.
332 """
333
334 root: Path
335 packages: tuple[Package, ...] = ()
336 subset: tuple[Package, ...] | None = None
337 tests: Mapping[str, tuple[str, ...]] = field(
338 default_factory=dict[str, tuple[str, ...]]
339 )
340 examples: tuple[str, ...] = ()
341 fix: bool = False
342 files: tuple[str, ...] = ()
343 safe: bool = False
344 point: str = ""
345 shard: Shard = ONE
346 catalogue: Mapping[str, tuple[tuple[str, str], ...]] | None = None
347 package: Package | None = None
348 selection: tuple[str, ...] = ()
349 changes: Changes | None = None
350 arguments: tuple[str, ...] = ()
351 step: str = ""
352 phase: str = ""
353 _steps: Mapping[str, StepRecord] = field(
354 default_factory=dict[str, "StepRecord"], repr=False
355 )
356 _given: Mapping[str, Mapping[str, object]] = field(
357 default_factory=dict[str, Mapping[str, object]], repr=False
358 )
359 _shared: _Shared = field(default_factory=_Shared, repr=False)
360
361 @property
362 def scoped(self) -> bool:
363 """Whether this is a package-scoped gate."""
364 return self.subset is not None
365
366 @property
367 def judged(self) -> tuple[Package, ...]:
368 """The packages under judgment: the subset, or every package."""
369 return self.packages if self.subset is None else self.subset
370
371 @property
372 def member(self) -> Package:
373 """The package the step runs over, for a step that runs once per package.
374
375 Raises:
376 Failed: when the run names none: a workspace step, or a
377 context built outside a package step's run.
378 """
379 if self.package is None:
380 fail(
381 f"{self.step or 'this step'} runs over one package at a time, and"
382 " this run names none"
383 )
384 return self.package
385
386 @property
387 def exit_code(self) -> int:
388 """The exit code the ``run`` phase's step recorded; 0 until one does."""
389 return self._shared.exit_code
390
391 def exit(self, code: int) -> None:
392 """Record *code* as the exit code ``fm run`` exits with.
393
394 The ``run`` phase's step that starts the executable calls it
395 with the executable's; the walk hands the code to the verb
396 through the context it returns.
397 """
398 self._shared.exit_code = code
399
400 def for_package(self, package: Package) -> PhaseContext:
401 """This context narrowed to one package and its selected tests."""
402 files = self.tests.get(package.path, ())
403 relative = tuple(path[len(package.path) + 1 :] for path in files)
404 return replace(self, package=package, selection=relative)
405
406 def provide(self, key: str, value: object) -> None:
407 """Write *value* under *key*, a key the running step's table provides.
408
409 Raises:
410 PhaseError: when the step's table does not provide *key*,
411 or *value* is not of the type it declares.
412 """
413 record = self._running()
414 provided = dict(record.provides)
415 if key not in provided:
416 raise PhaseError(
417 f"{self.step} provides {key}, and its {self._table()} table does"
418 " not name it in provides"
419 )
420 if not _holds(provided[key], value):
421 raise PhaseError(
422 f"{self.step} provides {key} as {type(value).__name__}, and its"
423 f" {self._table()} table declares it {provided[key]}"
424 )
425 with self._shared.lock:
426 self._shared.values.setdefault(self._unit(), {})[key] = value
427
428 def read(self, key: str) -> object:
429 """The value under *key*, a key the running step's table reads.
430
431 Its type is the one its provider declares, or the one the
432 phase's declaration gives an engine key.
433
434 Raises:
435 PhaseError: when the step's table does not read *key*, the
436 engine did not give it, or its provider wrote nothing
437 under it.
438 """
439 record = self._running()
440 if key not in record.reads:
441 raise PhaseError(
442 f"{self.step} reads {key}, and its {self._table()} table does not"
443 " name it in reads"
444 )
445 if key in self._engine():
446 given = self._given.get(self.phase, {})
447 if key not in given:
448 raise PhaseError(
449 f"{self.step} reads {key}, which the engine running the"
450 f" {self.phase} phase did not give it"
451 )
452 return given[key]
453 values = self._shared.values.get(self._unit(), {})
454 if key not in values:
455 provider = next(
456 (
457 name
458 for name, held in self._steps.items()
459 if key in dict(held.provides)
460 ),
461 "its provider",
462 )
463 raise PhaseError(
464 f"{self.step} reads {key}, which {provider} has not provided in"
465 f" the {self.phase} phase"
466 )
467 return values[key]
468
469 def result(self, key: str) -> object | None:
470 """The value under *key* once the phase ran, for the engine that ran it.
471
472 A key a step provided for the context's package, else one the
473 engine gave the context's phase; None when neither wrote one.
474 """
475 values = self._shared.values.get(self._unit(), {})
476 return values.get(key, self._given.get(self.phase, {}).get(key))
477
478 def _running(self) -> StepRecord:
479 """The running step's record; refuses outside a walk's step."""
480 record = self._steps.get(self.step)
481 if record is None:
482 raise PhaseError(
483 f"{self.step or 'this step'} is not a step of the walk that built"
484 " this context, so the context has no table to judge its keys by"
485 )
486 return record
487
488 def _table(self) -> str:
489 """The running step's table, as the declaration spells it."""
490 phase, _dot, name = self.step.partition(".")
491 return f"[phases.{phase}.{name}]"
492
493 def _engine(self) -> Mapping[str, str]:
494 """The keys the engine gives the phase, when the context names one."""
495 return phase_spec(self.phase).keys if self.phase else {}
496
497 def _unit(self) -> str:
498 """Where the keys this view writes and reads live: its package, or the root."""
499 return self.package.path if self.package is not None else ""
500
501
502def phase_steps(
503 phase: str, members: tuple[str, ...], lookup: Lookup
504) -> tuple[StepRecord, ...]:
505 """The steps the extensions *members* add to *phase*, in their order.
506
507 Each member's steps in declaration order, the members in the order
508 given, which for a package's set is its composition order. A step
509 one of *members* deletes is left out, so it never runs for the set
510 (`deletions`).
511 """
512 deleted = deletions(members, lookup)
513 found: list[StepRecord] = []
514 for name in members:
515 declared = lookup(name)
516 if declared is not None:
517 found += [
518 record
519 for record in declared.phases.get(phase, ())
520 if step_address(record) not in deleted
521 ]
522 return tuple(found)
523
524
525def step_address(record: StepRecord) -> str:
526 """*record*'s address among every extension's steps: ``<owner>:<phase>.<step>``."""
527 return f"{record.extension}:{record.name}"
528
529
530def deletions(members: Iterable[str], lookup: Lookup) -> dict[str, tuple[str, str]]:
531 """The steps the extensions *members* delete, by address, to the deleter and why.
532
533 An address is ``<owner>:<phase>.<step>``, as a step table's
534 ``deletes`` names it; the first of *members* to delete a step is
535 its deleter.
536 """
537 found: dict[str, tuple[str, str]] = {}
538 for name in members:
539 declared = lookup(name)
540 if declared is None:
541 continue
542 for records in declared.phases.values():
543 for record in records:
544 for address, reason in record.deletes:
545 found.setdefault(address, (name, reason))
546 return found
547
548
549def set_deletions(package: Package) -> dict[str, tuple[str, str]]:
550 """The steps *package*'s set deletes, by address, to the deleter and why."""
551 from livery.workshop._composition import extension_set
552 from livery.workshop._extensions import installed_declaration
553
554 return deletions(extension_set(package), installed_declaration)
555
556
557#: The engine key that names a phase's side: true for the isolated one.
558ISOLATED = "isolated"
559
560
561def serves(record: StepRecord, given: Mapping[str, object]) -> bool:
562 """Whether *record* runs on the side of its phase the engine's *given* keys name.
563
564 *given* are the keys the engine gives the step's phase. A step
565 declaring ``isolated = true`` runs when the engine gives
566 ``isolated`` true; one declaring false runs when the engine gives
567 false or nothing; one declaring neither runs on both sides.
568 """
569 if record.isolated is None:
570 return True
571 return record.isolated == (given.get(ISOLATED) is True)
572
573
574def _providers(steps: Iterable[StepRecord]) -> dict[str, list[str]]:
575 """Each key the steps provide, to the steps that provide it."""
576 found: dict[str, list[str]] = {}
577 for record in steps:
578 for key, _kind in record.provides:
579 found.setdefault(key, []).append(record.name)
580 return found
581
582
583def _earlier(
584 record: StepRecord,
585 by_name: Mapping[str, StepRecord],
586 providers: Mapping[str, list[str]],
587 *,
588 after: bool,
589) -> set[str]:
590 """The steps among *by_name* that *record* runs after.
591
592 The providers of the keys it reads, in its own phase, and, with
593 *after*, the steps it names in ``after``; a name outside
594 *by_name* orders nothing.
595 """
596 found = {
597 provider
598 for key in record.reads
599 for provider in providers.get(key, ())
600 if by_name[provider].phase == record.phase
601 }
602 if after:
603 found.update(other for other in record.after if other in by_name)
604 found.discard(record.name)
605 return found
606
607
608def phase_order(
609 steps: Iterable[StepRecord], *, after: bool = True
610) -> tuple[StepRecord, ...]:
611 """*steps* in the order the walk starts them.
612
613 Each step after the providers of the keys it reads, in its own
614 phase, and, with *after*, after the steps it names in ``after``;
615 otherwise in the given order. An ``after`` naming a step outside
616 *steps* orders nothing.
617
618 Raises:
619 OrderCycle: when the order has no start, naming the members
620 of one cycle.
621 """
622 from livery.workshop._composition import OrderCycle, cycle_of
623
624 by_name = {record.name: record for record in steps}
625 providers = _providers(by_name.values())
626 waiting = {
627 name: _earlier(record, by_name, providers, after=after)
628 for name, record in by_name.items()
629 }
630 done: list[str] = []
631 while len(done) < len(by_name):
632 ready = next(
633 (
634 name
635 for name in by_name
636 if name not in done and not waiting[name].difference(done)
637 ),
638 None,
639 )
640 if ready is None:
641 left = {name: waiting[name] for name in by_name if name not in done}
642 raise OrderCycle(cycle_of(left))
643 done.append(ready)
644 return tuple(by_name[name] for name in done)
645
646
647def phase_problems(phase: str, steps: Iterable[StepRecord]) -> list[str]:
648 """Why *steps* cannot run as *phase*; empty when they can.
649
650 Two extensions declaring one step, two steps providing one key, a
651 step providing a key the phase's engine gives, a step declaring a
652 side of a phase whose declaration gives no ``isolated``, a key a
653 step reads and no step provides, and an order with no start.
654
655 Raises:
656 PhaseError: when no extension declares *phase*.
657 """
658 from livery.workshop._composition import OrderCycle
659
660 records = tuple(steps)
661 problems: list[str] = []
662 engine = phase_spec(phase).keys
663 owners: dict[str, list[str]] = {}
664 for record in records:
665 owners.setdefault(record.name, []).append(record.extension)
666 for name, extensions in owners.items():
667 if len(extensions) > 1:
668 problems.append(
669 f"the {phase} phase: {' and '.join(sorted(extensions))} both declare"
670 f" {name}; one extension of a package declares a step"
671 )
672 providers = _providers(records)
673 for key, names in sorted(providers.items()):
674 if key in engine:
675 verb = "provides" if len(names) == 1 else "provide"
676 problems.append(
677 f"the {phase} phase: {' and '.join(sorted(names))} {verb} {key},"
678 " which the engine running the phase provides; a step reads it"
679 )
680 elif len(names) > 1:
681 problems.append(
682 f"the {phase} phase: {' and '.join(sorted(names))} both provide"
683 f" {key}; one step of a package provides a key"
684 )
685 if ISOLATED not in engine:
686 problems += [
687 f"the {phase} phase: {record.name} declares isolated, and the phase"
688 " has one side: its declaration gives no isolated key"
689 for record in records
690 if record.isolated is not None
691 ]
692 for record in records:
693 for key in record.reads:
694 if key not in providers and key not in engine:
695 problems.append(
696 f"the {phase} phase: {record.name} reads {key}, which no step of"
697 " the package provides"
698 )
699 try:
700 phase_order(records)
701 except OrderCycle as error:
702 cycle = " before ".join((*error.members, error.members[0]))
703 problems.append(
704 f"the {phase} phase: its steps' order has no start: {cycle}; remove a"
705 " key read or an after among them"
706 )
707 return problems
708
709
710@dataclass(frozen=True)
711class StepOutcome:
712 """Outcome of one step unit during a walk, for the proved record.
713
714 Attributes:
715 record: The step that ran or was skipped.
716 target: Package path (``packages/workshop``) or ``"."`` for workspace.
717 verdict: One of ``green``, ``red``, ``skipped``, ``unfinished``.
718 """
719
720 record: StepRecord
721 target: str
722 verdict: str
723
724
725class _Unit:
726 """One footman step of a walk: a step record over one package, or over the whole.
727
728 Attributes:
729 record: The step.
730 package: The package it runs over; None for a workspace step.
731 title: What footman shows for it: the step's name, then the
732 package's path.
733 done: Set once the unit ran, whatever happened.
734 failed: Whether it failed; a unit that waits on it refuses.
735 verdict: Recorded outcome (``green``, ``red``, ``skipped``, ``unfinished``).
736 needs: The units that run before it.
737 """
738
739 __slots__ = (
740 "done",
741 "failed",
742 "needs",
743 "package",
744 "record",
745 "subset",
746 "title",
747 "verdict",
748 )
749
750 def __init__(
751 self,
752 record: StepRecord,
753 package: Package | None,
754 *,
755 subset: tuple[Package, ...] | None = None,
756 ) -> None:
757 self.record = record
758 self.package = package
759 self.subset = subset
760 self.title = record.name if package is None else f"{record.name} {package.path}"
761 self.done = threading.Event()
762 self.failed = False
763 self.verdict = "unfinished"
764 self.needs: list[_Unit] = []
765
766
767#: How long a waiting step looks at the unit it waits on before it
768#: yields to footman again.
769_POLL_SECONDS = 0.05
770
771
772def walk_steps(
773 ctx: PhaseContext,
774 steps: Iterable[StepRecord],
775 *,
776 inputs: Mapping[str, Mapping[str, object]] | None = None,
777 fixing: bool = False,
778 outcomes: list[StepOutcome] | None = None,
779 skip_units: frozenset[str] = frozenset(),
780) -> PhaseContext:
781 """Run *steps* as footman steps inside one ``parallel()`` block.
782
783 A step runs on the side of its phase the engine gives
784 ([livery.workshop._phases.serves][]), and a step serving the other
785 side is not run. A workspace step runs once. A package step runs
786 once per package in scope (the context's ``judged``) it judges:
787 one whose set holds an extension the step names and none that
788 deletes the step, that has not turned the step off, that has a
789 file the step's claims reach, and whose change is not confined to
790 its tests unless the step is tests-only; each other package is
791 said and not run. Independent
792 steps run concurrently, and a step starts once the steps it names
793 in ``after`` and the providers of the keys it reads have run, for
794 the same package. A step whose earlier step failed is not run and
795 says so; the earlier failure is the verdict, and the steps that
796 depend on nothing failed still run, as footman runs a block.
797 *inputs* are the keys the engine gives each phase, by phase, each
798 phase's judged against its declaration before any step runs.
799 *fixing* runs each step's fix body instead of its main, a step
800 without one running nothing, in the given order: a fix rewrites
801 what its own tool reads, and the gate runs its fixers one at a
802 time, so ``after`` orders nothing there.
803
804 Returns:
805 The context the steps shared, which the engine reads a provided
806 key or the exit code back from.
807
808 Raises:
809 PhaseError: before any step runs, when the context or *inputs*
810 names a phase nobody declares, when *inputs* gives a phase
811 a key it does not take or a value of another type, or when
812 the steps cannot run as declared
813 ([livery.workshop._phases.phase_problems][]).
814 Exception: the first failing step's, raised again once every
815 step ran.
816 """
817 from livery.workshop._packages import workspace_suite
818 from livery.workshop._steps import (
819 PACKAGE,
820 judges_package,
821 judges_unit,
822 members,
823 option_value,
824 reads_files,
825 )
826
827 records = tuple(steps)
828 where = f"{ctx.package.path}: " if ctx.package is not None else ""
829 given = {phase: dict(keys) for phase, keys in (inputs or {}).items()}
830 if ctx.phase:
831 # A context naming a phase nobody declares refuses here, before
832 # any step runs, as an input to such a phase does.
833 phase_spec(ctx.phase)
834 _judge_inputs(given, where)
835 problems: list[str] = []
836 for phase in dict.fromkeys(record.phase for record in records):
837 problems += phase_problems(
838 phase, (record for record in records if record.phase == phase)
839 )
840 if problems:
841 raise PhaseError(where + "; ".join(problems))
842 ordered = phase_order(records, after=not fixing)
843 held = replace(
844 ctx, _steps={record.name: record for record in records}, _given=given
845 )
846 units: list[_Unit] = []
847 removed: dict[str, dict[str, tuple[str, str]]] = {}
848 for record in ordered:
849 if (record.fix if fixing else record.run) is None:849 ↛ 850line 849 didn't jump to line 850 because the condition on line 849 was never true
850 continue
851 if not serves(record, given.get(record.phase, {})):
852 continue
853 if record.scope != PACKAGE:
854 if skip_units:
855 if record.extensions:
856 judged_pkgs = tuple(
857 p for p in held.judged if judges_unit(record, p)
858 )
859 suite = workspace_suite(held.root) if held.subset is None else None
860 suite_judged = suite is not None and judges_unit(record, suite)
861 if judged_pkgs or suite_judged:861 ↛ 884line 861 didn't jump to line 884 because the condition on line 861 was always true
862 unproved_pkgs = tuple(
863 p
864 for p in judged_pkgs
865 if f"{record.name}@{p.path}" not in skip_units
866 )
867 suite_needs_run = (
868 suite_judged
869 and suite is not None
870 and f"{record.name}@{suite.path}" not in skip_units
871 )
872 if not unproved_pkgs and not suite_needs_run:872 ↛ 873line 872 didn't jump to line 873 because the condition on line 872 was never true
873 continue
874 if len(unproved_pkgs) < len(judged_pkgs) or (
875 suite_judged and not suite_needs_run
876 ):
877 unit_subset = (
878 (*unproved_pkgs, suite)
879 if suite is not None and suite_needs_run
880 else unproved_pkgs
881 )
882 units.append(_Unit(record, None, subset=unit_subset))
883 continue
884 elif f"{record.name}@." in skip_units:
885 continue
886 elif f"{record.name}@." in skip_units:
887 continue
888 units.append(_Unit(record, None))
889 continue
890 for package in members(held):
891 if not judges_package(record, held, package):
892 continue
893 if skip_units and f"{record.name}@{package.path}" in skip_units:
894 continue
895 if package.path not in removed:
896 removed[package.path] = set_deletions(package)
897 deleted = removed[package.path].get(step_address(record))
898 if deleted is not None:
899 deleter, reason = deleted
900 print(
901 f" {record.name}: {package.path} skips ({deleter} deletes it:"
902 f" {reason})"
903 )
904 if outcomes is not None:904 ↛ 905line 904 didn't jump to line 905 because the condition on line 904 was never true
905 outcomes.append(StepOutcome(record, package.path, "skipped"))
906 continue
907 if not reads_files(record, held, (package.path,)):
908 print(f" {record.name}: {package.path} has no file it reads; not run")
909 if outcomes is not None:909 ↛ 910line 909 didn't jump to line 910 because the condition on line 909 was never true
910 outcomes.append(StepOutcome(record, package.path, "skipped"))
911 continue
912 if not option_value(record, package, "enabled"):
913 print(
914 f" {record.name}: {package.path} skips (turned off in"
915 f" {package.path}/workshop.toml)"
916 )
917 if outcomes is not None:
918 outcomes.append(StepOutcome(record, package.path, "skipped"))
919 continue
920 units.append(_Unit(record, package))
921 _link(units, ordered, after=not fixing)
922 bodies = [_resolved(unit, fixing) for unit in units]
923 try:
924 with parallel() as block:
925 for unit, body in zip(units, bodies, strict=True):
926 built = step(_body(held, unit, body), title=unit.title)
927 block(built.opts(capture=False)())
928 finally:
929 if outcomes is not None:
930 _collect_unit_outcomes(held, units, outcomes)
931 return held
932
933
934def _collect_unit_outcomes(
935 ctx: PhaseContext, units: Sequence[_Unit], outcomes: list[StepOutcome]
936) -> None:
937 """Append package-grain or workspace-grain `StepOutcome` rows for *units*."""
938 from livery.workshop._packages import workspace_suite
939 from livery.workshop._steps import (
940 judges_unit,
941 option_value,
942 reads_files,
943 )
944
945 for unit in units:
946 if unit.package is not None:
947 outcomes.append(StepOutcome(unit.record, unit.package.path, unit.verdict))
948 continue
949 record = unit.record
950 if record.extensions:
951 target_pkgs = unit.subset if unit.subset is not None else ctx.judged
952 seen_targets: set[str] = set()
953 matched_any = False
954 for package in target_pkgs:
955 if not judges_unit(record, package):955 ↛ 956line 955 didn't jump to line 956 because the condition on line 955 was never true
956 continue
957 matched_any = True
958 seen_targets.add(package.path)
959 if not option_value(record, package, "enabled") or not reads_files(959 ↛ 962line 959 didn't jump to line 962 because the condition on line 959 was never true
960 record, ctx, (package.path,)
961 ):
962 outcomes.append(StepOutcome(record, package.path, "skipped"))
963 else:
964 outcomes.append(StepOutcome(record, package.path, unit.verdict))
965 suite = workspace_suite(ctx.root)
966 if (966 ↛ 972line 966 didn't jump to line 972 because the condition on line 966 was never true
967 suite is not None
968 and suite.path not in seen_targets
969 and judges_unit(record, suite)
970 and (unit.subset is None or record.phase == "test")
971 ):
972 matched_any = True
973 if not option_value(record, suite, "enabled") or not reads_files(
974 record, ctx, (suite.path,)
975 ):
976 outcomes.append(StepOutcome(record, suite.path, "skipped"))
977 else:
978 outcomes.append(StepOutcome(record, suite.path, unit.verdict))
979 if not matched_any:979 ↛ 980line 979 didn't jump to line 980 because the condition on line 979 was never true
980 outcomes.append(StepOutcome(record, ".", unit.verdict))
981 else:
982 outcomes.append(StepOutcome(record, ".", unit.verdict))
983
984
985def run_registered(ctx: PhaseContext) -> PhaseContext:
986 """Run the steps registered for the phase *ctx* names, through the walk.
987
988 The steps the mount registered for ``ctx.phase``, in registration
989 order: each listed extension's own, and those of the
990 ``[for.<target>]`` tables that apply. They run as `walk_steps` runs
991 any steps, so a phase the gate never runs, one declared with
992 ``gated = false``, runs this way over the workspace its context
993 names. A workspace step that names extensions runs once while a
994 package the context judges holds one of them; while none does, a
995 line says so and the step does not run. A phase with no registered
996 step runs nothing.
997
998 Returns:
999 The context the steps shared.
1000
1001 Raises:
1002 PhaseError: when *ctx* names no phase, or one nobody declares.
1003 Exception: the first failing step's, raised again once every
1004 step ran.
1005 """
1006 running, _idle = _registered(ctx)
1007 return walk_steps(ctx, running)
1008
1009
1010def _registered(
1011 ctx: PhaseContext,
1012) -> tuple[tuple[StepRecord, ...], tuple[StepRecord, ...]]:
1013 """The steps registered for ``ctx.phase``: those that run, and those that do not.
1014
1015 A workspace step that names extensions runs while a package the
1016 context judges holds one of them, and a line says so for each one
1017 that does not.
1018
1019 Raises:
1020 PhaseError: when *ctx* names no phase.
1021 """
1022 from livery.workshop._steps import PACKAGE, judges_unit, steps_by_name
1023
1024 if not ctx.phase:
1025 raise PhaseError(
1026 "a run of the registered steps names its phase, and this context names none"
1027 )
1028 running: list[StepRecord] = []
1029 idle: list[StepRecord] = []
1030 for record in steps_by_name().values():
1031 if record.phase != ctx.phase:
1032 continue
1033 named = record.scope != PACKAGE and bool(record.extensions)
1034 if named and not any(judges_unit(record, unit) for unit in ctx.judged):
1035 wanted = " or ".join(record.extensions)
1036 print(f" {record.name}: no package holds {wanted}; not run")
1037 idle.append(record)
1038 continue
1039 running.append(record)
1040 return tuple(running), tuple(idle)
1041
1042
1043#: The record of what each phase's last run through `run_phase` declared
1044#: it writes: the checkout's own state, never committed.
1045OUTPUTS_RECORD = ".workshop/state/outputs.json"
1046
1047#: The prefix of an output that names a path in each package.
1048IN_EACH_PACKAGE = "package/"
1049
1050
1051def output_refusal(output: str) -> str:
1052 """Why *output* cannot name what a step writes, or ``""`` when it can.
1053
1054 An output is a path relative to the workspace root, or
1055 ``package/<path>`` for that path in each package; a directory ends
1056 in ``/``. It lies below the root, or below the package, and it is
1057 never ``docs/`` itself, the root's or a package's, which holds the
1058 authored pages. The text completes a sentence about the output.
1059 """
1060 import re
1061
1062 inner = output.removeprefix(IN_EACH_PACKAGE)
1063 where = "each package" if inner != output else "the root"
1064 parts = tuple(part for part in inner.split("/") if part not in ("", "."))
1065 if (
1066 "\\" in output
1067 or inner.startswith("/")
1068 or re.match(r"[A-Za-z]:", inner)
1069 or ".." in parts
1070 ):
1071 return (
1072 f"names {output!r}, which leaves the root; an output is a path below"
1073 " the root, or package/<path> for the path in each package"
1074 )
1075 if not parts:
1076 return f"names {output!r}, {where} itself; an output is a path below it"
1077 if parts == ("docs",):
1078 tree = "each package's" if inner != output else "the root's"
1079 return (
1080 f"names {output!r}, {tree} docs/ itself, which holds the authored"
1081 " pages; an output is a path below it"
1082 )
1083 return ""
1084
1085
1086def _outputs_held(root: Path) -> dict[str, tuple[str, ...]]:
1087 """Each phase's outputs, as its last run through `run_phase` recorded them.
1088
1089 A record that cannot be read, or holds another shape, records
1090 nothing: the next run writes it again.
1091 """
1092 import json
1093
1094 try:
1095 held = json.loads((root / OUTPUTS_RECORD).read_text(encoding="utf-8"))
1096 except (OSError, ValueError):
1097 return {}
1098 if not isinstance(held, dict) or held.get("schema") != 1:
1099 return {}
1100 phases = held.get("phases")
1101 if not isinstance(phases, dict):1101 ↛ 1102line 1101 didn't jump to line 1102 because the condition on line 1101 was never true
1102 return {}
1103 return {
1104 phase: tuple(output for output in listed if isinstance(output, str))
1105 for phase, listed in cast("dict[str, object]", phases).items()
1106 if isinstance(listed, list)
1107 }
1108
1109
1110def _remove_outputs(
1111 root: Path,
1112 phase: str,
1113 running: tuple[str, ...],
1114 idle: tuple[str, ...],
1115 packages: tuple[Package, ...],
1116) -> None:
1117 """Remove what no running step of *phase* writes, and record what they do.
1118
1119 Each output the phase's last run recorded, or a registered step
1120 that does not run declares, goes unless a running step declares
1121 it; one line names each path removed. The record then holds the
1122 running steps' outputs.
1123 """
1124 import json
1125 import shutil
1126
1127 held = _outputs_held(root)
1128 kept = set(running)
1129 stale = [
1130 output
1131 for output in dict.fromkeys((*held.get(phase, ()), *idle))
1132 if output not in kept and not output_refusal(output)
1133 ]
1134 for output in stale:
1135 inner = output.removeprefix(IN_EACH_PACKAGE)
1136 homes = [p.directory for p in packages] if inner != output else [root]
1137 for home in homes:
1138 path = home / inner
1139 if path.is_symlink() or path.is_file():
1140 path.unlink()
1141 elif path.is_dir():1141 ↛ 1144line 1141 didn't jump to line 1144 because the condition on line 1141 was always true
1142 shutil.rmtree(path)
1143 else:
1144 continue
1145 shown = path.relative_to(root).as_posix() + (
1146 "/" if output.endswith("/") else ""
1147 )
1148 print(f" removed {shown}: no running step of the {phase} phase writes it")
1149 recorded = tuple(sorted(kept))
1150 if held.get(phase, ()) == recorded:
1151 return
1152 held[phase] = recorded
1153 path = root / OUTPUTS_RECORD
1154 path.parent.mkdir(parents=True, exist_ok=True)
1155 document = {
1156 "schema": 1,
1157 "phases": {name: list(held[name]) for name in sorted(held) if held[name]},
1158 }
1159 path.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8")
1160
1161
1162def run_phase(root: Path, phase: str, *, outputs: Iterable[str] = ()) -> PhaseContext:
1163 """Run a phase the gate never runs over the workspace at *root*; the shared context.
1164
1165 The steps the listed extensions register for *phase*, their own and
1166 those of the ``[for.<target>]`` tables that apply, run side by side
1167 through the walk every phase runs through, each workspace step once
1168 and each package step once per package whose set holds an
1169 extension it names. A workspace step that names extensions runs
1170 while a package holds one of them; while none does, a line says so
1171 and the step does not run. A phase with no registered step runs
1172 nothing.
1173
1174 Before the steps run, the paths a step declares under ``outputs``
1175 are settled: each one the phase's last run recorded, or a step that
1176 does not run now declares, is removed unless a step that runs now
1177 declares it, and a line names each path removed. So a step that
1178 stops running, its extension unlisted or no longer installed or the
1179 step turned off, leaves nothing behind wherever it wrote, and a
1180 running step finds its own output as it left it. The record lives
1181 in the checkout's ``.workshop/state/``.
1182
1183 Args:
1184 root: The workspace root.
1185 phase: The phase, one declared with ``gated = false``.
1186 outputs: Paths this run writes that no step declares, such as
1187 those of the verbs a step runs: each in the shape a step
1188 declares one, and removed and recorded as a running step's
1189 are.
1190
1191 Returns:
1192 The context the steps shared.
1193
1194 Raises:
1195 PhaseError: when nobody declares *phase*, naming the declared
1196 phases; when the gate runs it; or when an output in
1197 *outputs* is not a path below the root, or names ``docs/``
1198 itself.
1199 Exception: the first failing step's, raised again once every
1200 step ran.
1201 """
1202 from livery.workshop._packages import discover_packages
1203
1204 spec = phase_spec(phase)
1205 if spec.gated:
1206 raise PhaseError(
1207 f"the gate runs the {phase} phase; run_phase runs a phase declared"
1208 " with gated = false, and run_phase_over runs a gated phase's steps"
1209 " over named packages"
1210 )
1211 given = tuple(outputs)
1212 for output in given:
1213 refusal = output_refusal(output)
1214 if refusal:
1215 raise PhaseError(f"an output of the {phase} phase {refusal}")
1216 ctx = PhaseContext(root=root, packages=discover_packages(root), phase=phase)
1217 running, idle = _registered(ctx)
1218 _remove_outputs(
1219 root,
1220 phase,
1221 (*(o for record in running for o in record.outputs), *given),
1222 tuple(o for record in idle for o in record.outputs),
1223 ctx.packages,
1224 )
1225 return walk_steps(ctx, running)
1226
1227
1228def _judge_inputs(given: Mapping[str, Mapping[str, object]], where: str) -> None:
1229 """Refuse an undeclared phase, a key it does not take, or a mistyped value."""
1230 for phase, keys in given.items():
1231 engine = phase_spec(phase).keys
1232 for key, value in keys.items():
1233 if key not in engine:
1234 known = ", ".join(sorted(engine)) or "nothing"
1235 raise PhaseError(
1236 f"{where}the engine gives {key} to the {phase} phase, which takes"
1237 f" {known} from it"
1238 )
1239 if not _holds(engine[key], value):
1240 raise PhaseError(
1241 f"{where}the engine gives {key} to the {phase} phase as"
1242 f" {type(value).__name__}, which the phase takes as {engine[key]}"
1243 )
1244
1245
1246def _link(units: list[_Unit], ordered: tuple[StepRecord, ...], *, after: bool) -> None:
1247 """Give each of *units* the units it waits on: its earlier steps, same package.
1248
1249 A package unit waits on an earlier step's unit of its own package,
1250 and on a workspace unit; a workspace unit waits on every unit of
1251 an earlier step.
1252 """
1253 by_name = {record.name: record for record in ordered}
1254 providers = _providers(ordered)
1255 by_record: dict[str, list[_Unit]] = {}
1256 for unit in units:
1257 by_record.setdefault(unit.record.name, []).append(unit)
1258 for unit in units:
1259 for name in sorted(_earlier(unit.record, by_name, providers, after=after)):
1260 for other in by_record.get(name, ()):
1261 same = (
1262 unit.package is None
1263 or other.package is None
1264 or unit.package.path == other.package.path
1265 )
1266 if same:1266 ↛ 1260line 1266 didn't jump to line 1260 because the condition on line 1266 was always true
1267 unit.needs.append(other)
1268
1269
1270def _resolved(unit: _Unit, fixing: bool) -> Callable[[PhaseContext], None]:
1271 """The body *unit* runs, its module imported now, on the calling thread.
1272
1273 A declared step names its function, imported when it is first
1274 called; the walk imports every step's module before the block
1275 starts, so no two steps import at once, and a module that fails to
1276 import names its step before any step runs.
1277 """
1278 from livery.workshop._declaration import Reference
1279
1280 body = unit.record.fix if fixing else unit.record.run
1281 assert body is not None # a unit is built for a step with a body alone
1282 if isinstance(body, Reference):
1283 return cast("Callable[[PhaseContext], None]", body.resolve())
1284 return body
1285
1286
1287def _body(
1288 ctx: PhaseContext, unit: _Unit, body: Callable[[PhaseContext], None]
1289) -> Callable[[], Generator[None, Any, None]]:
1290 """The footman step's body for *unit*: wait for what it needs, then run *body*.
1291
1292 A generator, so each wait is a checkpoint where footman cancels
1293 the step; the unit is marked done however the body ends, so a unit
1294 waiting on it never waits past its end.
1295 """
1296 from livery.workshop._composition import extension_set
1297
1298 record = unit.record
1299
1300 def run() -> Generator[None, Any, None]:
1301 try:
1302 for need in unit.needs:
1303 while not need.done.wait(_POLL_SECONDS):1303 ↛ 1304line 1303 didn't jump to line 1304 because the condition on line 1303 was never true
1304 yield
1305 failed = [need for need in unit.needs if need.failed]
1306 if failed:
1307 # Said here as well as refused: the block raises the
1308 # earlier failure, and this reason rides the record.
1309 unit.verdict = "skipped"
1310 reason = f"{unit.title}: not run, since {failed[0].title} failed"
1311 print(f" {reason}")
1312 fail(reason)
1313 if unit.package is not None:
1314 view = ctx.for_package(unit.package)
1315 elif unit.subset is not None:
1316 view = replace(ctx, subset=unit.subset)
1317 else:
1318 view = ctx
1319 view = replace(view, step=record.name, phase=record.phase)
1320 if unit.package is not None:
1321 held = extension_set(unit.package)
1322 matched = " and ".join(n for n in record.extensions if n in held)
1323 print(
1324 f" {record.name}: {unit.package.path} runs (a {matched} package)"
1325 )
1326 body(view)
1327 unit.verdict = "green"
1328 except (KeyboardInterrupt, GeneratorExit):
1329 unit.failed = True
1330 unit.verdict = "unfinished"
1331 raise
1332 except BaseException:
1333 unit.failed = True
1334 if unit.verdict != "skipped":
1335 unit.verdict = "red"
1336 raise
1337 finally:
1338 unit.done.set()
1339
1340 return run