Coverage for packages/workshop/src/livery/workshop/_lifecycle.py: 98%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, 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_verify.py, packages/workshop/tests/test_workshop_sync_locked.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_scale.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_quality.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_lifecycle.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_influence.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/workshop/tests/test_workshop_currency.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/python/tests/test_python_layering.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/python/tests/test_declared_imports.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/cpp/tests/test_extensions_cpp.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 ran.

1"""What the engine asks of a package: build, versions, tests, publish, requirements.
2
3The release train, the layering phase and the docs reach a package's
4artifacts and manifests through these functions alone: its build, the
5version its manifest declares, the files a version is written into,
6writing a version, testing the built artifact in isolation, publishing
7what it built and the registry it goes to, verifying a released
8version, its declared requirements, writing one, the names other
9packages reference its code by, and what its sources reference. A
10question is a query ([livery.workshop._queries.Query][]) the package's
11set answers, the extensions it lists and those they require; a build,
12a stamp, an isolated test, a publish or a verification runs as the
13package's phase ([livery.workshop._phases.walk_steps][]), the steps its
14set adds to it. So a caller never names an extension.
15
16A question nothing in the set answers gets the query's empty answer:
17no module roots, no requirements. The version is the one question an
18empty answer cannot serve, and it refuses naming the query. A phase
19the set adds no step to refuses the release, naming the phase. A
20package that lists no extension holds none: every question gets its
21empty answer, and every phase refuses.
22"""
23
24from __future__ import annotations
25
26from typing import TYPE_CHECKING, cast
27
28if TYPE_CHECKING:
29 from collections.abc import Iterable, Mapping
30 from pathlib import Path
31
32 from livery.forge import Registry
33 from livery.workshop._packages import Package, SourceReferences
34 from livery.workshop._phases import PhaseContext
35 from livery.workshop._registries import RegistryTarget
36 from livery.workshop._steps import StepRecord
37
38
39def sync(packages: Iterable[Package], root: Path) -> None:
40 """Run the sync phase over the workspace at *root* holding *packages*.
41
42 The phase is what the workspace and its members need before
43 ``uv sync`` installs them: the steps the listed extensions
44 registered at mount, each once over the workspace, and a step that
45 judges one package at a time once for each of *packages* whose set
46 holds an extension it names. A workspace step that names
47 extensions runs while one of *packages* holds one of them, and not
48 at all while none does. conan's profile step is one: it runs once
49 while a package holds conan, a package that lists nanobind among
50 them, since its set holds conan. With no step registered, the phase
51 runs nothing.
52 """
53 from livery.workshop._phases import PhaseContext, run_registered
54
55 run_registered(PhaseContext(root=root, packages=tuple(packages), phase="sync"))
56
57
58#: What the release train's build gives the build phase beside the
59#: epoch: the isolated side, in the release configuration.
60RELEASE_BUILD: Mapping[str, object] = {"isolated": True, "configuration": "release"}
61
62
63def build_release(package: Package, root: Path, *, epoch: int = 0) -> Path:
64 """Build *package*'s release artifacts into its ``dist/``; that directory.
65
66 The release train's build: the steps *package*'s set adds to the
67 build phase, run on the phase's isolated side in the ``release``
68 configuration. One of them provides the ``dist`` directory it
69 wrote.
70
71 Args:
72 package: The member to build.
73 root: The workspace root *package* is a member of.
74 epoch: The build's source date in seconds, so two builds of one
75 tree are the same bytes; 0 takes the build tool's own.
76
77 Returns:
78 The directory the build phase's steps wrote the artifacts into.
79
80 Raises:
81 Failed: naming the package, its set and the phase, when no
82 extension of the set adds a step to the build phase; and
83 naming the package, when the steps that ran provide no
84 ``dist`` directory.
85 """
86 from pathlib import Path
87
88 ctx = _served(package, "build", root, {**RELEASE_BUILD, "epoch": epoch})
89 return cast("Path", _provided(ctx, "dist", Path))
90
91
92def current_version(package: Package) -> str:
93 """The version *package*'s own manifest declares.
94
95 Raises:
96 Failed: naming the package, its set and the query, when nothing
97 in the set answers the version, since a release reads and
98 stamps it.
99 """
100 from livery.footman import fail
101 from livery.workshop._queries import CURRENT_VERSION, answer
102
103 answered = answer(package, CURRENT_VERSION)
104 if not answered:
105 held = ", ".join(_set_of(package)) or "none"
106 fail(
107 f"{package.path}: its extensions ({held}) answer no"
108 f" {CURRENT_VERSION.name}: none of them reads a version from the"
109 " package's manifests, so the release train has no version to read"
110 " or stamp. List the extension whose manifest carries the version"
111 )
112 return answered
113
114
115def version_files(package: Package) -> tuple[Path, ...]:
116 """Every file the stamp phase's steps write: the version, and the floors.
117
118 A file holding only floors is among them, as a recipe that names no
119 version is. A caller that stamps for one build keeps these files
120 first, then restores them. Empty for a package whose set names none.
121 The floors the base raises are in the package's own contract, which
122 is not among them.
123 """
124 from livery.workshop._queries import VERSION_FILES, answer
125
126 return tuple(answer(package, VERSION_FILES))
127
128
129def stamp(
130 package: Package,
131 root: Path,
132 version: str,
133 *,
134 floors: Mapping[str, str] | None = None,
135) -> list[str]:
136 """Write *version* and raise *package*'s floors in its manifests; the files changed.
137
138 The stamp phase's steps write the version into their own manifests,
139 and raise there each floor a manifest declares on one of *floors*:
140 the members released with *package*, each by its path, to the
141 version it releases at. The base raises the floor of each
142 ``[[depends]]`` edge of the package's contract on one of them.
143 Without *floors* no floor moves, as for a member released alone.
144 Each file is named relative to the package's directory.
145
146 Raises:
147 Failed: naming the package, its set and the phase, when no
148 extension of the set adds a step to the stamp phase.
149 """
150 given = dict(floors or {})
151 ctx = _served(package, "stamp", root, {"version": version, "floors": given})
152 changed = list(cast("list[str]", _provided(ctx, "changed", (list, tuple))))
153 if _raise_depends_floors(package, given):
154 from livery.workshop._contract import CONTRACT
155
156 changed.append(CONTRACT)
157 return changed
158
159
160def _raise_depends_floors(package: Package, floors: Mapping[str, str]) -> bool:
161 """Raise each ``[[depends]]`` floor of *package*'s contract on one of *floors*.
162
163 A text edit, so the contract keeps its comments and layout: the
164 ``floor`` of the edge whose ``path`` names the member takes its
165 version. Whether the contract changed.
166 """
167 import re
168
169 from livery.workshop._contract import CONTRACT
170
171 contract = package.directory / CONTRACT
172 if not floors or not contract.is_file():
173 return False
174 text = original = contract.read_text("utf-8")
175 for path, version in floors.items():
176 if path == package.path:176 ↛ 177line 176 didn't jump to line 177 because the condition on line 176 was never true
177 continue
178 text = re.sub(
179 rf'(path = "{re.escape(path)}"[^[]*?floor = ")[^"]+(")',
180 rf"\g<1>{version}\g<2>",
181 text,
182 flags=re.S,
183 )
184 if text == original:
185 return False
186 contract.write_text(text, encoding="utf-8")
187 return True
188
189
190def publish(
191 package: Package,
192 root: Path,
193 *,
194 version: str,
195 target: RegistryTarget,
196 prebuilt: bool = False,
197) -> bool:
198 """Upload *package*'s built artifacts to *target*; False when all were there.
199
200 A re-run walks past what an earlier attempt uploaded, so False is
201 a success that uploaded nothing. *prebuilt* says a job of the run
202 built the package and the run collected what it built into the
203 package's ``dist/``, so this runner built nothing. The publish
204 phase gets it as ``prebuilt``, and a step whose upload reads
205 something other than ``dist/``, as conan's reads its cache, puts
206 the collected files there first.
207
208 Raises:
209 Failed: naming the package, its set and the phase, when no
210 extension of the set adds a step to the publish phase.
211 """
212 inputs: dict[str, object] = {
213 "version": version,
214 "registry-target": target.to_table(),
215 "prebuilt": prebuilt,
216 }
217 ctx = _served(package, "publish", root, inputs)
218 return cast("bool", _provided(ctx, "published", bool))
219
220
221def distributions(package: Package) -> tuple[tuple[str, str], ...]:
222 """The distributions *package* releases, each as its ecosystem and its name.
223
224 Its set's answers to the ``distributions`` query, combined.
225 """
226 from livery.workshop._queries import DISTRIBUTIONS, answer
227
228 return answer(package, DISTRIBUTIONS)
229
230
231def ecosystem(package: Package) -> str:
232 """The one ecosystem *package* releases to, which its registry resolves by.
233
234 The ecosystem its distributions name (``distributions``): the release
235 train publishes the package to that ecosystem's registry and probes
236 it there.
237
238 Raises:
239 Failed: naming the package and its set when no extension of the
240 set releases a distribution of it, and naming the ecosystems
241 when its distributions name more than one, since a package
242 releases to one registry.
243 """
244 from livery.footman import fail
245
246 # A list, not a tuple: basedpyright narrows a tuple by the length
247 # checks below and then reads the last line's index as out of range.
248 named = list(dict.fromkeys(found for found, _name in distributions(package)))
249 if not named:
250 held = ", ".join(_set_of(package)) or "none"
251 fail(
252 f"{package.path}: its extensions ({held}) answer no registry: none of"
253 " them releases a distribution of it, so the release train has nowhere"
254 " to publish it. List the extension that releases it, or set [release]"
255 " publish = false to version and tag it without an upload"
256 )
257 if len(named) > 1:
258 fail(
259 f"{package.path}: its extensions answer more than one registry,"
260 f" {', '.join(named[:-1])} and {named[-1]}: each releases a"
261 " distribution of it, and a package releases to one registry. List"
262 " the extensions that release it to one of them"
263 )
264 return named[0]
265
266
267def registry(package: Package) -> Registry:
268 """The registry *package* releases to, as a probe of the versions it serves.
269
270 Its set's answer to the ``registry`` query, from the extension that
271 releases its distribution. The release train polls the probe until
272 a version it uploaded is served.
273
274 Raises:
275 Failed: naming the package when its extensions answer no
276 registry or more than one (``ecosystem``), before any probe is
277 built, and naming the ecosystem when the extensions that
278 release it answer no probe of its registry.
279 """
280 from livery.footman import fail
281 from livery.workshop._queries import REGISTRY, answer
282
283 released = ecosystem(package)
284 probe = answer(package, REGISTRY)
285 if not probe:
286 fail(
287 f"{package.path}: its extensions release it to {released} and answer"
288 " no probe of that registry, so the release train cannot see what it"
289 " serves"
290 )
291 return probe
292
293
294def has_isolated_test(package: Package) -> bool:
295 """Whether *package*'s release tests its built artifact on the isolated side.
296
297 Whether its set adds a step serving the test phase's isolated side,
298 as python does for the wheel it builds.
299 """
300 return bool(_isolated_tests(package))
301
302
303def isolated_test(
304 package: Package, root: Path, *, resolution: str, release_dirs: tuple[Path, ...]
305) -> dict[str, str]:
306 """Run *package*'s test phase on its isolated side at *resolution*; what it got.
307
308 Each distribution the run installed, to its version. *resolution*
309 is ``floor``, ``latest`` or ``head``; *release_dirs* are the
310 co-released set's ``dist/`` directories, the only place the run
311 finds a sibling's unpublished wheel. Ask
312 [livery.workshop._lifecycle.has_isolated_test][] first: a package
313 with no isolated test refuses here.
314
315 Raises:
316 Failed: naming the package when its set adds no step on the test
317 phase's isolated side.
318 """
319 from livery.footman import fail
320
321 if not _isolated_tests(package):
322 fail(
323 f"{package.path}: nothing tests its release isolated: its extensions"
324 " add no step on the test phase's isolated side"
325 )
326 inputs: dict[str, object] = {
327 "isolated": True,
328 "resolution": resolution,
329 "release-dirs": list(release_dirs),
330 }
331 ctx = _served(package, "test", root, inputs)
332 resolved = cast("dict[object, object]", _provided(ctx, "resolved", dict))
333 return {str(name): str(version) for name, version in resolved.items()}
334
335
336def verify(
337 package: Package,
338 root: Path,
339 *,
340 tree: Path,
341 version: str,
342 python: str,
343 index: str,
344 extras: str,
345) -> int:
346 """Install *package*'s released *version* alone and run its tests; the exit code.
347
348 *tree* is checked out at the release's receipt tag, *python* is the
349 interpreter, *index* where the version installs from and *extras*
350 the extras installed with it, comma-joined.
351
352 Raises:
353 Failed: naming the package, its set and the phase, when no
354 extension of the set adds a step to the verify phase.
355 """
356 inputs: dict[str, object] = {
357 "version": version,
358 "tree": tree,
359 "interpreter": python,
360 "index": index,
361 "extras": extras,
362 }
363 ctx = _served(package, "verify", root, inputs)
364 return cast("int", _provided(ctx, "exit-code", int))
365
366
367def declared_requirements(package: Package) -> dict[str, str]:
368 """What *package*'s native manifests require, each name to its constraint.
369
370 Empty for a package whose set reads no manifest, which declares no
371 requirement: ``layering.graph`` names each of its edges on a
372 sibling as missing from its manifests.
373 """
374 from livery.workshop._queries import REQUIREMENTS, answer
375
376 return dict(answer(package, REQUIREMENTS))
377
378
379def declared_test_requirements(package: Package) -> dict[str, str] | None:
380 """What *package*'s manifests require for its tests, each name to its constraint.
381
382 None for a package whose set answers no ``test-requirements``: the
383 package has no home for its test edges, and ``layering.graph``
384 judges none of them.
385 """
386 from livery.workshop._queries import TEST_REQUIREMENTS, answer, answers
387
388 if not answers(package, TEST_REQUIREMENTS):
389 return None
390 return dict(answer(package, TEST_REQUIREMENTS))
391
392
393def declare_requirement(
394 package: Package, dependency: Package, floor: str, *, kind: str = "runtime"
395) -> list[str]:
396 """Write *dependency* at *floor* into *package*'s manifests; the files changed.
397
398 *kind* is the edge's: a build or runtime requirement is written by
399 the writers the package's set answers ``requirement-writers`` with,
400 and a test requirement by those it answers
401 ``test-requirement-writers`` with. Every writer is called. Each
402 takes a sibling of its own ecosystem alone, so the requirement
403 lands in the manifest of the dependency's ecosystem: python's
404 ``pyproject.toml`` for a sibling that holds python, conan's recipe
405 for a sibling that is a conan package. The files are relative to
406 the package; empty when the manifests name the dependency already,
407 and for a test requirement in a set with no writer of one, which
408 has no home for it.
409
410 Raises:
411 Failed: when no writer of the set takes *dependency*, naming
412 both sets; nothing is written then.
413 """
414 from livery.footman import fail
415 from livery.workshop._composition import extension_set
416 from livery.workshop._queries import (
417 REQUIREMENT_WRITERS,
418 TEST_REQUIREMENT_WRITERS,
419 answer,
420 )
421
422 writers = answer(
423 package, TEST_REQUIREMENT_WRITERS if kind == "test" else REQUIREMENT_WRITERS
424 )
425 if kind == "test" and not writers:425 ↛ 426line 425 didn't jump to line 426 because the condition on line 425 was never true
426 return []
427 taken = [
428 written
429 for writer in writers
430 if (written := writer(package, dependency, floor)) is not None
431 ]
432 if not taken:
433 own = ", ".join(extension_set(package)) or "no extension"
434 theirs = ", ".join(extension_set(dependency)) or "no extension"
435 what = "test requirement" if kind == "test" else "requirement"
436 fail(
437 f"{package.path} holds {own}, and no writer of its set takes a"
438 f" {what} on {dependency.path}, which holds {theirs}: a writer"
439 " takes a sibling of its own ecosystem alone. List an extension"
440 f" whose manifest takes {dependency.path}, or drop the dependency"
441 )
442 return list(dict.fromkeys(name for written in taken for name in written))
443
444
445def module_roots(package: Package) -> tuple[str, ...]:
446 """The names other packages reference *package*'s code by; empty for none."""
447 from livery.workshop._queries import MODULE_ROOTS, answer
448
449 return tuple(answer(package, MODULE_ROOTS))
450
451
452def references(package: Package) -> tuple[SourceReferences, ...]:
453 """What each of *package*'s sources references, one record per source.
454
455 The ``references`` answers of the package's set, combined as their
456 union. Empty for a package nothing answers for, such as one whose
457 language no extension reads sources of. Each record names a file
458 inside the package, and one extension answers for each file.
459
460 Raises:
461 QueryError: when an answer names a file outside the package,
462 naming the extension and the file, or when two extensions
463 answer for one file, naming both.
464 """
465 from livery.workshop._queries import REFERENCES, QueryError, answers
466
467 found: Mapping[str, Iterable[SourceReferences]] = answers(package, REFERENCES)
468 owners: dict[str, str] = {}
469 union: dict[SourceReferences, None] = {}
470 for name, answered in found.items():
471 for source in answered:
472 if not _inside(package, source.path):
473 raise QueryError(
474 f"{package.path}: {REFERENCES.name}: {name} answers for"
475 f" {source.path}, a file outside the package; an answer"
476 " names the package's own sources"
477 )
478 held = owners.setdefault(source.path, name)
479 if held != name:
480 raise QueryError(
481 f"{package.path}: {REFERENCES.name}: {held} and {name} both"
482 f" answer for {source.path}; one extension of a package"
483 " answers for each source"
484 )
485 union[source] = None
486 return tuple(union)
487
488
489def _inside(package: Package, path: str) -> bool:
490 """Whether *path*, relative to the workspace root, is a file inside *package*."""
491 from pathlib import PurePosixPath
492
493 return path.startswith(f"{package.path}/") and ".." not in PurePosixPath(path).parts
494
495
496def _run_steps(
497 package: Package, phase: str, root: Path, inputs: Mapping[str, object]
498) -> PhaseContext | None:
499 """Run *phase* over *package* with the engine's *inputs*; None without steps.
500
501 None when no extension of the package's set adds steps to the
502 phase. A step an extension of the set deletes is none of them. The
503 steps run through the one walk
504 ([livery.workshop._phases.walk_steps][]), the context naming the
505 package and the phase.
506 """
507 steps = _phase_steps(package, phase)
508 if not steps:
509 return None
510 from livery.workshop._phases import PhaseContext, walk_steps
511
512 ctx = PhaseContext(root=root, packages=(package,), package=package, phase=phase)
513 return walk_steps(ctx, steps, inputs={phase: inputs})
514
515
516def _served(
517 package: Package, phase: str, root: Path, inputs: Mapping[str, object]
518) -> PhaseContext:
519 """Run *phase* over *package* as `_run_steps` does; refuse a phase with no step.
520
521 Raises:
522 Failed: naming the package, its set and the phase, when no
523 extension of the set adds a step to the phase, so nothing
524 does what the release asks of it.
525 """
526 ctx = _run_steps(package, phase, root, inputs)
527 if ctx is None:
528 from livery.footman import fail
529
530 held = ", ".join(_set_of(package)) or "none"
531 fail(
532 f"{package.path}: its extensions ({held}) add no step to the {phase}"
533 " phase, so the release has nothing to run there. List the extension"
534 f" whose steps serve the {phase} phase"
535 )
536 return ctx
537
538
539def _isolated_tests(package: Package) -> tuple[StepRecord, ...]:
540 """The steps *package*'s set adds to the test phase that serve its isolated side."""
541 from livery.workshop._phases import ISOLATED, serves
542
543 return tuple(
544 record
545 for record in _phase_steps(package, "test")
546 if serves(record, {ISOLATED: True})
547 )
548
549
550def _phase_steps(package: Package, phase: str) -> tuple[StepRecord, ...]:
551 """The steps *package*'s set adds to *phase*, less those the set deletes.
552
553 Empty for a package listing none.
554 """
555 if not package.extensions:
556 return ()
557 from livery.workshop._composition import extension_set
558 from livery.workshop._extensions import installed_declaration
559 from livery.workshop._phases import phase_steps
560
561 return phase_steps(phase, extension_set(package), installed_declaration)
562
563
564def _provided(ctx: PhaseContext, key: str, kind: type | tuple[type, ...]) -> object:
565 """What *ctx*'s steps provided under *key*; refuses when none of them did."""
566 from livery.footman import fail
567
568 value = ctx.result(key)
569 if not isinstance(value, kind):
570 fail(
571 f"{ctx.member.path}: the {ctx.phase} phase's steps provide no {key},"
572 " which the release train reads from the phase"
573 )
574 return value
575
576
577def _set_of(package: Package) -> tuple[str, ...]:
578 """The extensions *package*'s set holds, as its queries ask them."""
579 from livery.workshop._composition import extension_set
580
581 return extension_set(package)