Coverage for packages/workshop/src/livery/workshop/_ci_generate.py: 97%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_runtime_language.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_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.py, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_fragments.py, packages/workshop/tests/test_workshop_extensions.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_declaration.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_cpp_kind.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/extensions/ty/tests/test_ty.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/pyrefly/tests/test_pyrefly.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.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/conan/tests/test_conan_kind.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 ran.

1"""The CI workflow renderers: the declared points, in each forge's words.
2
3Workflow files are mechanical forge knowledge, emitted here from the
4workspace contract (``workshop.toml``) and the derived Python matrix,
5written as managed generated artifacts, and the drift check compares
6the committed files against these same pure functions, offline.
7Change an emitter, run ``fm sync``, and every kind's files move
8together.
9
10Every job enters through the emitted ``setup.sh`` (the entry
11contract: uv at the lock's pin, the venv synced against the lock,
12the emission persisted) and then calls the runner bare: no ``uv run``
13anywhere in a rendered workflow.
14
15The release workflows are the merge-triggered train: publishing runs
16where the release PR's squash lands, and the receipt tags are cut by
17``fm workflow.release.publish`` after the index confirms each
18member, so a tag is a receipt, never a trigger.
19"""
20
21from __future__ import annotations
22
23import json
24from collections.abc import Mapping, Sequence
25from pathlib import Path
26from typing import TYPE_CHECKING, Any, cast
27
28import livery.footman as footman
29from livery.workshop._contract import load_contract
30from livery.workshop._points import (
31 EVENT_NAMES,
32 Job,
33 Point,
34 emitted_points,
35 job_installs,
36 job_runners,
37 job_seams,
38 points,
39 pull_request_listed,
40 pull_request_runners,
41 shard_counts,
42)
43from livery.workshop._pythons import gate_pythons, python_matrix
44from livery.workshop._shard import Shard
45
46if TYPE_CHECKING:
47 from livery.workshop._composition import Lookup
48
49
50def _pinned(repo: str, commit: str, version: str) -> str:
51 """One ``uses:`` value: *repo* at *commit*, with the *version* the commit is."""
52 return f"{repo}@{commit} # {version}"
53
54
55#: The actions the emitted jobs use, by forge, each pinned to a commit
56#: with its version beside it. Keyed by forge because each forge's
57#: runners prove their own majors: this repository's CI proves
58#: GitHub's, the loop proves Gitea's on the v4 line. A bump moves with
59#: its proof. The pin table and nothing else says which commit a job
60#: runs, so a rendered ``uses:`` never names a moving tag.
61ACTIONS: dict[str, dict[str, str]] = {
62 "github": {
63 "checkout": _pinned(
64 "actions/checkout", "3d3c42e5aac5ba805825da76410c181273ba90b1", "v7.0.1"
65 ),
66 "upload": _pinned(
67 "actions/upload-artifact",
68 "043fb46d1a93c77aae656e7c1c64a875d1fc6a0a",
69 "v7.0.1",
70 ),
71 "download": _pinned(
72 "actions/download-artifact",
73 "3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c",
74 "v8.0.1",
75 ),
76 "setup-uv": _pinned(
77 "astral-sh/setup-uv", "20cfd1bf945f4377ade1205e4dbc17946fc9a30d", "v10.0.1"
78 ),
79 # The cache action the jobs restore and save through: the tool
80 # store, uv's cache and conan's home, each keyed by its lock
81 # with a prefix fallback.
82 "cache": _pinned(
83 "actions/cache", "55cc8345863c7cc4c66a329aec7e433d2d1c52a9", "v6.1.0"
84 ),
85 "upload-pages": _pinned(
86 "actions/upload-pages-artifact",
87 "7b1f4a764d45c48632c6b24a0339c27f5614fb0b",
88 "v4.0.0",
89 ),
90 "deploy-pages": _pinned(
91 "actions/deploy-pages", "d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e", "v4.0.5"
92 ),
93 },
94 "gitea": {
95 "checkout": _pinned(
96 "actions/checkout", "11d5960a326750d5838078e36cf38b85af677262", "v4.4.0"
97 ),
98 "upload": _pinned(
99 "actions/upload-artifact",
100 "ea165f8d65b6e75b540449e92b4886f43607fa02",
101 "v4.6.2",
102 ),
103 "download": _pinned(
104 "actions/download-artifact",
105 "d3f86a106a0bac45b974a628896c90dbdf5c8093",
106 "v4.3.0",
107 ),
108 },
109}
110#: The tool store's home on a GitHub job: the data directory the entry
111#: places under the runner's temp, the working drive, and the store as
112#: its `toolroom`. Literal here because the step runs before any verb
113#: can: the venv it would need is what the entry step makes.
114STORE_HOME = "${{ runner.temp }}/footman/toolroom"
115#: Where a GitHub job keeps conan's home: the working drive, the job's
116#: own, the path conan's declared CONAN_HOME, ``{place}/conan``, takes
117#: on a GitHub job, where the entry and `fm env.emit --github` place it
118#: under the runner's temp, so the cache step and every conan the job
119#: runs agree on one directory.
120CONAN_HOME = "${{ runner.temp }}/conan"
121
122
123def _facts(root: Path, everything: tuple[Point, ...] | None = None) -> dict[str, Any]:
124 """What the emitters read: the contract's CI facts, matrix derived.
125
126 Runners, the shards per runner, the required context, and the
127 forge kind come from ``workshop.toml``; the Python matrix from the root
128 ``pyproject.toml``'s floor and the workshop's newest supported
129 minor; the uv pin from the lock; what a job installs, where it
130 deploys and the runners it fans out to from the functions the job
131 names, over *everything*, the points the files render, *root*'s
132 when absent; what the listed extensions add to the checkout step
133 from their answers to the ``checkout-inputs`` query. None of it is
134 the project's identity, which the project's answers hold alone.
135 """
136 from livery.workshop._entry import locked_uv_version
137 from livery.workshop._envfile import parse_env_file
138 from livery.workshop._governance import ci_environments
139 from livery.workshop._packages import discover_packages
140 from livery.workshop._points import schedule
141 from livery.workshop._queries import CHECKOUT_INPUTS, answer
142
143 contract = load_contract(root / "workshop.toml")
144 ci = contract.get("ci") or {}
145 runners = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
146 narrowed = pull_request_runners(ci)
147 shards, pull_request_shards = _shard_facts(ci, runners, narrowed)
148 try:
149 packages = discover_packages(root)
150 except ValueError:
151 packages = ()
152 selection_enabled = any(pkg.test_selection == "on" for pkg in packages)
153 return {
154 "forge_kind": str((contract.get("forge") or {}).get("kind", "github")),
155 # What the listed extensions add to the checkout step, such as
156 # fetching the objects a git filter keeps outside the repository.
157 "checkout_inputs": dict(answer(root, CHECKOUT_INPUTS)),
158 "runners": runners,
159 "pull_request_runners": narrowed,
160 # The shards per runner label, one for a runner the tables do
161 # not name: every event's over every runner, and a pull
162 # request's over its runners.
163 "shards": shards,
164 "pull_request_shards": pull_request_shards,
165 "selection_enabled": selection_enabled,
166 "required_context": str(ci.get("required-context", "gate")),
167 "environments": ci_environments(contract),
168 "python_versions": python_matrix(root),
169 "gate_pythons": gate_pythons(root),
170 # The outer uv, the one tool that runs before the lock can
171 # speak: pinned to the lock's own uv, so the bootstrap is not
172 # the one unpinned link. Empty without a lock, and the
173 # bootstrap then stays unpinned rather than inventing a
174 # version.
175 "uv_pin": locked_uv_version(root),
176 # The system packages each job installs before it enters, the
177 # seam each deploying job publishes through, and the runner
178 # labels each runners job fans out to, by point and job: the
179 # declaration of a job knows why.
180 "installs": job_installs(root, everything),
181 "seams": job_seams(root, everything),
182 "job_runners": job_runners(root, everything),
183 # The committed .repo.env's keys: the offline, deterministic
184 # list of which non-secret Actions variables the entry step may
185 # carry into a job's shared rung (never CI secrets).
186 "env_keys": sorted(parse_env_file(root / ".repo.env")),
187 # Scheduled points that carry at least one cadence or if-changed
188 # entry, so the workflow opens with a short due job that skips
189 # downstream jobs with nothing due.
190 "due_points": sorted(
191 {entry.point for entry in schedule(root) if entry.if_changed or entry.every}
192 ),
193 }
194
195
196def _var_lines(answers: dict[str, Any]) -> list[str]:
197 """The entry step's environment lines: each declared key's variable, prefixed.
198
199 Each key the committed ``.repo.env`` declares may be overridden by a
200 non-secret CI repository variable; the entry step carries it as
201 ``RUNG_<KEY>`` from ``vars.<KEY>`` (never ``secrets.<KEY>``), and
202 the emission the entry runs writes the non-empty ones into a
203 runner-local file the cascade reads as the shared slot
204 (``WORKSHOP_SHARED_ENV_FILE``). Non-empty values only, so an absent
205 variable cannot mask a committed value, and a fork PR behaves like a
206 machine without a shared file. CI secrets never ride ``.repo.env``:
207 they enter workflows strictly through explicit credential
208 declarations on trusted jobs. Empty when the workspace declares no
209 keys.
210 """
211 from livery.workshop._envfile import RUNG_PREFIX
212
213 keys = [str(key) for key in answers.get("env_keys", [])]
214 return [f"{RUNG_PREFIX}{key}: ${{{{ vars.{key} }}}}" for key in keys]
215
216
217def _setup_uv_step(answers: dict[str, Any]) -> str:
218 """The setup-uv step, uv pinned to the lock's own version, its cache off.
219
220 Nothing of uv's is cached: the only wheels the sync builds from
221 source are the workspace's own, rebuilt on every commit, and the
222 wheels it downloads arrive faster than an archive of them restores.
223 The cache is still placed on the runner's working drive by the
224 entry, so the sync links wheels into the venv instead of copying
225 across drives.
226 """
227 pin = str(answers.get("uv_pin", ""))
228 lines = [f" - uses: {ACTIONS['github']['setup-uv']}", " with:"]
229 if pin:
230 lines.append(f' version: "{pin}"')
231 lines.append(" enable-cache: false")
232 return "\n".join(lines) + "\n"
233
234
235def _store_cache_step() -> str:
236 """The tool store restored before the entry materialises it.
237
238 Keyed by the tools lock, the OS and the architecture, with the
239 prefix as the restore key, so a changed lock restores everything
240 unchanged and the store lands only the digests it lacks. A
241 restored folder is a tier the store verifies on access: an old or
242 torn archive costs a refetch, never a fault. `ci.run` sweeps the
243 store before the post-job save, so the archive carries the trees
244 the tools run from and not the artifacts they were extracted from.
245 """
246 return (
247 f" - uses: {ACTIONS['github']['cache']}\n"
248 " with:\n"
249 f" path: {STORE_HOME}\n"
250 " key: tools-${{ runner.os }}-${{ runner.arch }}"
251 "-${{ hashFiles('toolroom.lock') }}\n"
252 " restore-keys: tools-${{ runner.os }}-${{ runner.arch }}-\n"
253 )
254
255
256def _conan_cache_step() -> str:
257 """Conan's home restored around a job that builds native packages.
258
259 Keyed by the recipes, the OS and the architecture, with the
260 prefix as the restore key: a third-party package from Conan
261 Center is built from source once per key and downloaded from the
262 cache afterwards. The recipes are the key because they carry the
263 requirements; a range that resolves to a newer version inside an
264 unchanged recipe reuses the entry and builds that one package.
265 The cache is the speed extension and Conan Center the origin, so a
266 miss costs time, never a red leg.
267 """
268 # A forge's glob stops at a slash: a package in a group directory
269 # is one level deeper.
270 recipes = "packages/*/conanfile.py', 'packages/*/*/conanfile.py"
271 return (
272 f" - uses: {ACTIONS['github']['cache']}\n"
273 " with:\n"
274 f" path: {CONAN_HOME}\n"
275 " key: conan-${{ runner.os }}-${{ runner.arch }}"
276 f"-${{{{ hashFiles('{recipes}') }}}}\n"
277 " restore-keys: conan-${{ runner.os }}-${{ runner.arch }}-\n"
278 )
279
280
281def _job_cache_step(job: Job) -> str:
282 """A job's declared workspace cache restored before entry and saved after.
283
284 Keyed by the job name, runner OS and architecture, ``uv.lock`` (so a
285 toolchain upgrade starts from a clean cache) and the commit SHA, with
286 the lock-scoped prefix as restore key so each run restores the newest
287 cached state for the same toolchain and saves its updated state back.
288 """
289 prefix = f"{job.name}-${{{{ runner.os }}}}-${{{{ runner.arch }}}}-${{{{ hashFiles('uv.lock') }}}}"
290 return (
291 f" - uses: {ACTIONS['github']['cache']}\n"
292 " with:\n"
293 f" path: {job.cache_dir}\n"
294 f" key: {prefix}-${{{{ github.sha }}}}\n"
295 f" restore-keys: {prefix}-\n"
296 )
297
298
299def _installs(
300 answers: dict[str, Any],
301 point: Point,
302 job: Job,
303 joins: Sequence[tuple[Point, Job]] = (),
304) -> tuple[str, ...]:
305 """The system packages *job* of *point* installs before it enters, *joins* included."""
306 found = set(answers.get("installs", {}).get((point.name, job.name), ()))
307 for other, joined in joins:
308 found.update(answers.get("installs", {}).get((other.name, joined.name), ()))
309 return tuple(sorted(found))
310
311
312def _joins_of(
313 point: Point, job: Job, everything: tuple[Point, ...]
314) -> list[tuple[Point, Job]]:
315 """The joins of *job* of *point*: on the point itself and on the points inheriting it.
316
317 Each with the point it was contributed to, which conditions the
318 plumbing it adds: a join on the merge point of a job the gate
319 point declares renders on the gate point's job, on a push alone.
320 """
321 return [
322 (other, joined)
323 for other in everything
324 if other.name == point.name or other.inherits == point.name
325 for joined in other.jobs
326 if joined.joins and joined.name == job.name
327 ]
328
329
330def _condition(point: Point, other: Point) -> str:
331 """The event condition a step *other* adds to a job of *point* carries; none on its own point."""
332 return "" if other.name == point.name else _event_filter(other)
333
334
335def _if_line(condition: str) -> str:
336 return f" if: {condition}\n" if condition else ""
337
338
339def _artifact_root(everything: tuple[Point, ...], name: str) -> str:
340 """The directory a collected artifact *name* unpacks into: its static root."""
341 for point in everything:341 ↛ 348line 341 didn't jump to line 348 because the loop on line 341 didn't complete
342 for job in point.jobs:
343 if job.publishes == name and job.paths:
344 first = job.paths[0]
345 if not any(ch in first for ch in ("*", "?", "[")):
346 return first.rstrip("/") or "."
347 return first.split("/", 1)[0]
348 return "."
349
350
351def _seam(answers: dict[str, Any], point: Point, job: Job) -> str:
352 """The seam *job* of *point* publishes through; ``""`` when it deploys nothing."""
353 return str(answers.get("seams", {}).get((point.name, job.name), ""))
354
355
356def _installs_step(packages: tuple[str, ...]) -> str:
357 """The step installing *packages* on a GitHub- or Gitea-shaped job; empty for none."""
358 if not packages:
359 return ""
360 return (
361 " - name: System packages\n"
362 " run: sudo apt-get update -q && sudo apt-get install"
363 f" -y -q {' '.join(packages)}\n"
364 )
365
366
367DRIVER_DIST = "livery-workshop"
368"""The distribution a re-dispatched wave may pin as its driver."""
369
370
371def _enter_step(answers: dict[str, Any], *, matrix_python: bool = False) -> str:
372 """The entry step: ``setup.sh github`` persists the emission.
373
374 Every step after it calls the runner and the venv tools bare,
375 from the persisted PATH. ``UV_PYTHON`` selects the matrix leg's
376 interpreter for the entry sync where a matrix exists, and the
377 declared keys' non-secret Actions variables ride the step's
378 environment as ``RUNG_<KEY>`` for the emission to materialise into
379 the shared slot.
380 """
381 lines: list[str] = []
382 if matrix_python:
383 lines.append("UV_PYTHON: ${{ matrix.python }}")
384 lines.extend(_var_lines(answers))
385 env = " env:\n" + "".join(f" {line}\n" for line in lines)
386 return (
387 " - name: Enter the workspace\n"
388 + (env if lines else "")
389 + " run: bash setup.sh github\n"
390 )
391
392
393def _csv(values: list[Any], *, quoted: bool = False) -> str:
394 return ", ".join(f'"{v}"' if quoted else str(v) for v in values)
395
396
397def _labels(answers: dict[str, Any], point: Point, job: Job) -> list[str]:
398 """The runner labels *job* of *point* fans out to; empty when its function names none."""
399 found = answers.get("job_runners", {}).get((point.name, job.name), ())
400 return [str(label) for label in found]
401
402
403def _gitlab_image(answers: dict[str, Any], python: str) -> str:
404 """The pinned uv image for a GitLab job.
405
406 With a lock the tag carries the pin
407 (``<pin>-python<minor>-bookworm``), so the job's uv is the lock's
408 uv; without one the unversioned tag is the honest fallback.
409 """
410 pin = str(answers.get("uv_pin", ""))
411 prefix = f"{pin}-" if pin else ""
412 return f"ghcr.io/astral-sh/uv:{prefix}python{python}-bookworm"
413
414
415def _comment(text: str, indent: str = "") -> str:
416 """*text* as YAML comment lines under *indent*; empty for empty."""
417 import textwrap
418
419 if not text:
420 return ""
421 width = max(40, 72 - len(indent))
422 return "".join(f"{indent}# {line}\n" for line in textwrap.wrap(text, width=width))
423
424
425def _renders(point: Point, job: Job, answers: dict[str, Any]) -> bool:
426 """Whether *job* of *point* exists for this workspace.
427
428 A ``runners`` job exists when its function names a runner label
429 for this workspace; when it names none, the job does not render
430 and `_needs` drops a need on it. Every other job always exists.
431 """
432 return job.matrix != "runners" or bool(_labels(answers, point, job))
433
434
435def _points_of(workflow: str, everything: tuple[Point, ...]) -> tuple[Point, ...]:
436 """The points among *everything* whose shell *workflow* is, in order."""
437 return tuple(point for point in everything if point.workflow == workflow)
438
439
440def _needs(
441 point: Point, job: Job, answers: dict[str, Any], everything: tuple[Point, ...]
442) -> list[str]:
443 """The jobs *job* waits for that render for this workspace."""
444 owners = [other for other in everything if other.name == point.inherits]
445 rendered = {
446 other.name
447 for owner in (*owners, point)
448 for other in owner.jobs
449 if _renders(owner, other, answers)
450 }
451 return [need for need in job.needs if need in rendered]
452
453
454def _event_filter(point: Point) -> str:
455 """The Actions condition admitting *point*'s events alone."""
456 return " || ".join(f"github.event_name == '{event}'" for event in point.events)
457
458
459def _shard_facts(
460 ci: dict[str, Any], runners: Sequence[str], narrowed: Sequence[str]
461) -> tuple[dict[str, int], dict[str, int]]:
462 """The shards per runner label: every event's, and a pull request's.
463
464 Read as [livery.workshop.check_shards][] and
465 [livery.workshop.pull_request_shards][] read them, so the matrix
466 and the leg labels agree: ``[ci] shards`` over every runner, one
467 for a runner it does not name; ``[ci] pull-request-shards`` over
468 the pull request's runners, *narrowed*, or every event's counts for
469 those runners while that key is absent. A count outside the
470 contract refuses here, through `shard_counts`, before a line
471 renders.
472 """
473 shards = shard_counts(ci, key="shards", runners=runners, listed="[ci] runners")
474 if ci.get("pull-request-shards") is None:
475 return shards, {runner: shards[runner] for runner in narrowed}
476 pull = shard_counts(
477 ci,
478 key="pull-request-shards",
479 runners=narrowed,
480 listed=pull_request_listed(ci),
481 )
482 return shards, pull
483
484
485def _runners(answers: dict[str, Any]) -> tuple[list[str], list[str]]:
486 """Every event's runner labels, and a pull request's."""
487 runners = [str(runner) for runner in answers.get("runners", ["ubuntu-latest"])]
488 narrowed = [
489 str(runner) for runner in answers.get("pull_request_runners", runners[:1])
490 ]
491 return runners, narrowed
492
493
494def _shards(
495 answers: dict[str, Any], key: str, runners: Sequence[str]
496) -> dict[str, int]:
497 """The shards per runner the fact *key* holds, one for a runner it does not name."""
498 counts: Mapping[str, Any] = answers.get(key) or {}
499 return {runner: int(counts.get(runner, 1)) for runner in runners}
500
501
502def _split(counts: Mapping[str, int]) -> bool:
503 """Whether any runner in *counts* runs as more than one shard."""
504 return any(count > 1 for count in counts.values())
505
506
507def _carries_shards(answers: dict[str, Any]) -> bool:
508 """Whether the check matrix is ``include`` entries carrying shards.
509
510 It is when any runner runs as more than one shard on any event: the
511 entries of a split runner each name their shard, on the check job
512 or in both of the legs job's literals, and the one call passes
513 ``matrix.shard`` on every event, empty on a runner with one shard.
514 """
515 runners, narrowed = _runners(answers)
516 return _split(_shards(answers, "shards", runners)) or _split(
517 _shards(answers, "pull_request_shards", narrowed)
518 )
519
520
521def _narrows(answers: dict[str, Any]) -> bool:
522 """Whether a pull request's check legs differ from every other event's.
523
524 They do when the pull request runs on fewer runners, or when a
525 runner it runs on runs as another number of shards.
526 """
527 runners, narrowed = _runners(answers)
528 if narrowed != runners:
529 return True
530 shards = _shards(answers, "shards", runners)
531 pull = _shards(answers, "pull_request_shards", narrowed)
532 return pull != {runner: shards[runner] for runner in narrowed}
533
534
535def _shard_count_for(counts: Mapping[Any, int], runner: str, python: str) -> int:
536 """Shard count for *(runner, python)* from a per-leg or per-runner map."""
537 if (runner, python) in counts:
538 return counts[(runner, python)]
539 return counts.get(runner, 1)
540
541
542def _entries(
543 runners: Sequence[str],
544 pythons: Sequence[str],
545 counts: Mapping[Any, int],
546) -> list[tuple[str, str, str]]:
547 """One ``(os, python, shard)`` per matrix entry, in that order.
548
549 A runner with a count of one has one entry per Python with an empty
550 shard: the forge then names its job as the unsplit leg, ``check
551 (ubuntu-latest, 3.14)``, the name the runner gives it and keys its
552 rows by, and the call's shard reaches the runner empty, which it
553 reads as one shard of one.
554 """
555 entries: list[tuple[str, str, str]] = []
556 for runner in runners:
557 for python in pythons:
558 count = _shard_count_for(counts, runner, python)
559 if count == 1:
560 entries.append((runner, python, ""))
561 continue
562 for index in range(1, count + 1):
563 entries.append((runner, python, str(Shard(index, count))))
564 return entries
565
566
567def matrix_for_leg_counts(
568 runners: Sequence[str],
569 pythons: Sequence[str],
570 counts: Mapping[Any, int],
571 *,
572 sharded: bool,
573) -> dict[str, Any]:
574 """Matrix dictionary for *runners*, *pythons*, and per-leg shard *counts*."""
575 if sharded:
576 return {
577 "include": [
578 {
579 "os": os_label,
580 "python": python,
581 **({"shard": shard} if shard else {}),
582 }
583 for os_label, python, shard in _entries(runners, pythons, counts)
584 ]
585 }
586 return {"os": list(runners), "python": list(pythons)}
587
588
589def _literal(
590 runners: Sequence[str],
591 pythons: Sequence[str],
592 counts: Mapping[str, int],
593 *,
594 sharded: bool,
595) -> str:
596 """One matrix as the JSON literal the legs job holds.
597
598 The ``include`` shape when *sharded*, each entry of a split runner
599 with its shard and an entry of a runner with one shard without the
600 key; the ``os`` and ``python`` lists otherwise.
601 """
602 matrix = matrix_for_leg_counts(runners, pythons, counts, sharded=sharded)
603 return json.dumps(matrix, separators=(",", ":"))
604
605
606def _legs_job(answers: dict[str, Any]) -> str:
607 """The job that picks the check legs' matrix by the event, as its output.
608
609 GitHub starts no run for a workflow whose matrix axis is an
610 expression, so the two literal matrices sit in this job's
611 environment, the event picks one, and the check job reads it with
612 ``fromJSON`` from the output: the one documented shape for a matrix
613 decided when the run starts. The decision is still the contract's;
614 the file carries two literals and which event takes which: a pull
615 request takes the narrowed one unless it carries
616 [livery.workshop.EVERY_RUNNER_LABEL][], and every other event takes
617 the full one. Both literals are ``include`` entries, each naming
618 its shard, when any runner runs as more than one shard on either
619 event, and the ``os`` and ``python`` lists otherwise. The job checks
620 nothing out and enters nothing, so it costs seconds.
621 """
622 from livery.workshop._points import EVERY_RUNNER_LABEL
623
624 runners, narrowed = _runners(answers)
625 pythons = [str(version) for version in answers.get("gate_pythons", ["3.11"])]
626 sharded = _carries_shards(answers)
627 full = _literal(
628 runners, pythons, _shards(answers, "shards", runners), sharded=sharded
629 )
630 pull = _literal(
631 narrowed,
632 pythons,
633 _shards(answers, "pull_request_shards", narrowed),
634 sharded=sharded,
635 )
636 narrowed_event = (
637 "github.event_name == 'pull_request' && !contains("
638 f"github.event.pull_request.labels.*.name, '{EVERY_RUNNER_LABEL}')"
639 )
640 return (
641 _comment(
642 "The check legs' matrix, two literals: a pull request's runners"
643 f" and every runner. A pull request without the {EVERY_RUNNER_LABEL}"
644 " label takes the first, every other run the second, and the"
645 " check job reads the pick from this job's output.",
646 " ",
647 )
648 + " legs:\n"
649 f" runs-on: {runners[0]}\n"
650 " outputs:\n"
651 " matrix: ${{ steps.legs.outputs.matrix }}\n"
652 " steps:\n"
653 " - id: legs\n"
654 " env:\n"
655 f" LEGS: ${{{{ {narrowed_event} && '{pull}' || '{full}' }}}}\n"
656 ' run: echo "matrix=$LEGS" >> "$GITHUB_OUTPUT"\n'
657 )
658
659
660def _needs_due(point: Point, answers: dict[str, Any]) -> bool:
661 """Whether *point* opens with a short ``due`` job before its work jobs."""
662 return "schedule" in point.events and point.name in answers.get("due_points", ())
663
664
665def _narrows_point(point: Point, answers: dict[str, Any]) -> bool:
666 """Whether *point*'s ``legs`` matrix narrows on pull requests."""
667 return "pull_request" in point.events and _narrows(answers)
668
669
670def _dynamic_shards(point: Point, answers: dict[str, Any]) -> bool:
671 """Whether *point*'s ``legs`` job dynamically sizes shards from selected items."""
672 return (
673 "pull_request" in point.events
674 and _carries_shards(answers)
675 and bool(answers.get("selection_enabled"))
676 )
677
678
679def _uses_legs_job(point: Point, answers: dict[str, Any]) -> bool:
680 """Whether *point*'s check job reads its matrix from a preceding ``legs`` job."""
681 return _narrows_point(point, answers) or _dynamic_shards(point, answers)
682
683
684def _dynamic_legs_job(
685 answers: dict[str, Any], prog: str, point: Point, *, forge: str
686) -> str:
687 """The planning ``legs`` job that sizes each sharded platform to its selection."""
688 runners = [str(runner) for runner in answers.get("runners", ["ubuntu-latest"])]
689 first = runners[0]
690 lines = [
691 _comment(
692 "Decide each check leg's shard count from its selected test items."
693 " A leg whose selected items fit in fewer shards than [ci] shards"
694 " starts only the shards it needs; the planned counts are written"
695 " on the run's plan ref for the gate job's fold.",
696 " ",
697 ),
698 " legs:\n",
699 ]
700 if forge == "github":
701 lines.append(" permissions:\n contents: write\n")
702 lines.extend(
703 [
704 f" runs-on: {first}\n",
705 " outputs:\n",
706 " matrix: ${{ steps.legs.outputs.matrix }}\n",
707 " skip_check: ${{ steps.legs.outputs.skip_check }}\n",
708 " steps:\n",
709 _checkout_step(
710 point,
711 Job("legs", fetch="full"),
712 forge=forge,
713 inputs=answers.get("checkout_inputs"),
714 ),
715 ]
716 )
717 if forge == "github":
718 lines.append(_setup_uv_step(answers))
719 lines.append(_store_cache_step())
720 lines.append(_enter_step(answers, matrix_python=False))
721 lines.extend(
722 [
723 " - id: legs\n",
724 " name: Plan check legs\n",
725 f' run: {prog} ci.legs --point={point.name} --output="$GITHUB_OUTPUT"\n',
726 ]
727 )
728 return "".join(lines)
729
730
731def _due_job(answers: dict[str, Any], prog: str, point: Point, *, forge: str) -> str:
732 """The short first job of a scheduled point: decides which jobs are due."""
733 runners = [str(runner) for runner in answers.get("runners", ["ubuntu-latest"])]
734 first = runners[0]
735 targets = [
736 job.name
737 for job in point.jobs
738 if not job.joins and _renders(point, job, answers)
739 ]
740 lines = [
741 _comment(
742 "Decide which scheduled jobs are due on this run. A job whose"
743 " tasks are off cadence or whose if-changed head has not moved"
744 " since the last verdict does not start; a dispatch by hand runs"
745 " regardless.",
746 " ",
747 ),
748 " due:\n",
749 f" runs-on: {first}\n",
750 " outputs:\n",
751 *(f" {name}: ${{{{ steps.due.outputs.{name} }}}}\n" for name in targets),
752 " steps:\n",
753 _checkout_step(
754 point, Job("due"), forge=forge, inputs=answers.get("checkout_inputs")
755 ),
756 ]
757 if forge == "github":
758 lines.append(_setup_uv_step(answers))
759 lines.append(_store_cache_step())
760 lines.append(_enter_step(answers, matrix_python=False))
761 lines.extend(
762 [
763 " - id: due\n",
764 " name: Check due tasks\n",
765 f' run: {prog} ci.due --point={point.name} --output="$GITHUB_OUTPUT"\n',
766 ]
767 )
768 return "".join(lines)
769
770
771def _call_step(prog: str, point: Point, job: Job, *, shard: bool = False) -> str:
772 """The one call: ``ci.run`` for the point and job, the matrix facts passed.
773
774 *shard* passes the entry's shard too, on a ``legs`` matrix whose
775 entries carry one.
776 """
777 call = f"{prog} ci.run --point={point.name} --job={job.name}"
778 if job.matrix in ("legs", "declared"):
779 passed = ' --shard="${{ matrix.shard }}"\n' if shard else ""
780 return (
781 " run: >-\n"
782 f" {call}\n"
783 ' --os="${{ matrix.os }}" --python="${{ matrix.python }}"\n'
784 + passed
785 )
786 if job.matrix == "pythons":
787 return (
788 f" run: >-\n {call}\n"
789 ' --python="${{ matrix.python }}"\n'
790 )
791 return f" run: {call}\n"
792
793
794def _isolated_env(point: Point, job: Job, *, forge: str) -> str:
795 """Environment block for an isolated Tier 1 job (never loads .repo.env)."""
796 lines: list[str] = []
797 if job.token == "job":797 ↛ 798line 797 didn't jump to line 798 because the condition on line 797 was never true
798 lines.append("FORGE_TOKEN: ${{ secrets.GITHUB_TOKEN }}")
799 elif job.token == "repository":
800 lines.append("FORGE_TOKEN: ${{ secrets.FORGE_TOKEN || secrets.GITHUB_TOKEN }}")
801 elif job.token == "secret":801 ↛ 802line 801 didn't jump to line 802 because the condition on line 801 was never true
802 lines.append("FORGE_TOKEN: ${{ secrets.FORGE_TOKEN }}")
803 elif job.token == "admin":803 ↛ 805line 803 didn't jump to line 805 because the condition on line 803 was always true
804 lines.append("FORGE_ADMIN_TOKEN: ${{ secrets.FORGE_ADMIN_TOKEN }}")
805 if job.publishes_index:
806 secret = "PYPI_TOKEN" if forge == "github" else "UV_PUBLISH_TOKEN"
807 lines.append(f"UV_PUBLISH_TOKEN: ${{{{ secrets.{secret} }}}}")
808 if point.ref_input:
809 lines.append(f"TARGET_REF: ${{{{ inputs.{point.ref_input} }}}}")
810 if any(item.name == "workshop" for item in point.inputs):
811 lines.append("WORKSHOP_DRIVER: ${{ inputs.workshop }}")
812 if not lines:812 ↛ 813line 812 didn't jump to line 813 because the condition on line 812 was never true
813 return ""
814 return " env:\n" + "".join(f" {line}\n" for line in lines)
815
816
817def _isolated_args(job: Job) -> tuple[str, ...]:
818 """CLI flags passed to an isolated Tier 1 entry module."""
819 if job.name == "govern":
820 return ("--if-changed",)
821 return ()
822
823
824def _isolated_run_block(
825 point: Point, job: Job, *, indent: str, workshop_env: str
826) -> str:
827 """Herdoc ``python3 -I`` bootstrapper launching *job.isolated* cleanly."""
828 from livery.workshop._isolated import isolated_shell_launcher
829
830 script = isolated_shell_launcher(
831 job.isolated,
832 _isolated_args(job),
833 workshop_env=workshop_env,
834 )
835 body = "".join(f"{indent}{line}\n" for line in script.splitlines())
836 return f"{indent}python3 -I - <<'EOF'\n{body}{indent}EOF\n"
837
838
839def _call_env(job: Job, *, forge: str) -> str:
840 """What the call sees: the credential, the index token, the deploy key's ssh."""
841 lines: list[str] = []
842 if job.token == "job":
843 lines.append("FORGE_TOKEN: ${{ secrets.GITHUB_TOKEN }}")
844 elif job.token == "repository":
845 lines.append("FORGE_TOKEN: ${{ secrets.FORGE_TOKEN || secrets.GITHUB_TOKEN }}")
846 elif job.token == "secret":846 ↛ 847line 846 didn't jump to line 847 because the condition on line 846 was never true
847 lines.append("FORGE_TOKEN: ${{ secrets.FORGE_TOKEN }}")
848 elif job.token == "admin":848 ↛ 849line 848 didn't jump to line 849 because the condition on line 848 was never true
849 lines.append("FORGE_ADMIN_TOKEN: ${{ secrets.FORGE_ADMIN_TOKEN }}")
850 if job.publishes_index:850 ↛ 854line 850 didn't jump to line 854 because the condition on line 850 was never true
851 # A token publishes where the repository has one; on GitHub an
852 # absent secret arrives empty, which the publish verb drops
853 # before it spawns uv, so uv stays on trusted publishing.
854 secret = "PYPI_TOKEN" if forge == "github" else "UV_PUBLISH_TOKEN"
855 lines.append(f"UV_PUBLISH_TOKEN: ${{{{ secrets.{secret} }}}}")
856 if not lines:
857 return ""
858 return " env:\n" + "".join(f" {line}\n" for line in lines)
859
860
861#: The inputs the checkout step sets from the job's own declaration,
862#: which no answer to the ``checkout-inputs`` query may name.
863CHECKOUT_OWN = ("ref", "fetch-depth", "fetch-tags", "token")
864
865
866def checkout_inputs(answers: Mapping[str, Any], lookup: Lookup) -> dict[str, str]:
867 """Every input the answers add to the checkout step, each name to its value.
868
869 The rule of the ``checkout-inputs`` query, which the base's
870 contract file names. Each answer maps an input of the checkout
871 action to its value, written into the workflow as it stands.
872
873 Raises:
874 QueryError: when an answer names an input the step sets from the
875 job's declaration (``CHECKOUT_OWN``) or gives a value that is
876 not a string, naming the extension, or when two answers give
877 one input different values, naming both.
878 """
879 from livery.workshop._queries import QueryError, merged
880
881 for name, value in answers.items():
882 for key, held in cast("Mapping[str, object]", value).items():
883 if key in CHECKOUT_OWN:
884 raise QueryError(
885 f"{name} answers {key}, which the checkout step sets from"
886 " the job's declaration; answer another input"
887 )
888 if not isinstance(held, str):
889 raise QueryError(
890 f"{name} answers {key} with {held!r}, and an input's value"
891 " is a string, as the workflow writes it; quote it"
892 )
893 return dict(merged(answers, lookup))
894
895
896def _checkout_step(
897 point: Point, job: Job, *, forge: str, inputs: Mapping[str, str] | None = None
898) -> str:
899 """The checkout: as deep as the verbs need, at the dispatched ref, able to push.
900
901 *inputs* are what the listed extensions add to it, each written
902 before the inputs the job's declaration sets.
903 """
904 action = ACTIONS[forge]["checkout"]
905 with_lines = [
906 f" {name}: {value}" for name, value in (inputs or {}).items()
907 ]
908 if point.ref_input:
909 with_lines.append(f" ref: ${{{{ inputs.{point.ref_input} }}}}")
910 if job.fetch == "full":
911 with_lines.append(" fetch-depth: 0")
912 elif job.fetch == "tags":
913 with_lines.append(" fetch-tags: true")
914 elif job.fetch:
915 with_lines.append(f" fetch-depth: {job.fetch}")
916 if job.pushes:
917 # The push rides this checkout's credential: the job token may
918 # not push a ref whose commit carries a workflow file that
919 # differs from the tip's, and receipt tags are protected.
920 token = (
921 "${{ secrets.FORGE_TOKEN || github.token }}"
922 if forge == "github"
923 else "${{ secrets.FORGE_TOKEN }}"
924 )
925 with_lines.append(f" token: {token}")
926 lines = [f" - uses: {action}\n"]
927 if with_lines:
928 lines.append(" with:\n")
929 lines.extend(line + "\n" for line in with_lines)
930 return "".join(lines)
931
932
933def _collect_step(
934 job: Job, *, forge: str, everything: tuple[Point, ...], condition: str = ""
935) -> str:
936 """The artifact *job* collects, every leg's merged into its publisher's root.
937
938 *condition* is the event condition of the point that added the
939 collect to a job of another point, empty on the job's own. A
940 collect on an ``always`` job or under a condition never stops the
941 job: the artifact may be missing when every publisher was skipped
942 or died before uploading, and the job's own entries, the verdict
943 among them, still judge the run and say so.
944 """
945 if not job.collects:
946 return ""
947 action = ACTIONS[forge]["download"]
948 tolerant = " continue-on-error: true\n" if (condition or job.always) else ""
949 return (
950 f" - uses: {action}\n" + _if_line(condition) + tolerant + " with:\n"
951 f" pattern: {job.collects}*\n"
952 f" path: {_artifact_root(everything, job.collects)}\n"
953 " merge-multiple: true\n"
954 )
955
956
957def _artifact_name(job: Job, *, matrix: str, sharded: bool) -> str:
958 """Unique artifact name for *job* under its *matrix* axes."""
959 if matrix == "legs":
960 suffix = "-${{ matrix.os }}-${{ matrix.python }}"
961 if sharded:
962 suffix += "-${{ matrix.shard }}"
963 return job.publishes + suffix
964 if matrix == "pythons":964 ↛ 965line 964 didn't jump to line 965 because the condition on line 964 was never true
965 return job.publishes + "-${{ matrix.python }}"
966 if matrix == "declared":966 ↛ 967line 966 didn't jump to line 967 because the condition on line 966 was never true
967 return job.publishes + "-${{ matrix.os }}-${{ matrix.python }}"
968 if matrix:
969 return job.publishes + "-${{ matrix.os }}"
970 return job.publishes
971
972
973def _has_hidden_path(paths: Sequence[str]) -> bool:
974 """Whether any segment of *paths* starts with a dot (hidden file or dir)."""
975 return any(
976 part.startswith(".") and part not in (".", "..")
977 for path in paths
978 for part in path.split("/")
979 )
980
981
982def _publish_step(
983 job: Job,
984 *,
985 forge: str,
986 matrix: str = "",
987 sharded: bool = False,
988 condition: str = "",
989) -> str:
990 """The artifact *job* publishes, its paths as declared, leg-named on a *matrix*.
991
992 *condition* is the event condition of the point that added the
993 publish to a job of another point, empty on the job's own.
994 """
995 if not job.publishes:
996 return ""
997 action = ACTIONS[forge]["upload"]
998 name = _artifact_name(job, matrix=matrix, sharded=sharded)
999 effective_if = condition
1000 if job.upload_always:
1001 effective_if = f"always() && ({condition})" if condition else "always()"
1002 hidden = (
1003 " include-hidden-files: true\n" if _has_hidden_path(job.paths) else ""
1004 )
1005 retention = (
1006 f" retention-days: {job.retention_days}\n"
1007 if job.retention_days
1008 else ""
1009 )
1010 return (
1011 f" - uses: {action}\n" + _if_line(effective_if) + " with:\n"
1012 f" name: {name}\n"
1013 " path: |\n"
1014 + "".join(f" {path}\n" for path in job.paths)
1015 + " if-no-files-found: ignore\n"
1016 + hidden
1017 + retention
1018 )
1019
1020
1021def _driver_step(prog: str, point: Point, *, forge: str) -> str:
1022 """The driver pin, through its verb: the released workshop the input names.
1023
1024 Every job of a point that takes a ``workshop`` input pins it before
1025 its one call, so one workshop drives the whole run; a job of any
1026 other point pins nothing. The verb decides for itself on an empty
1027 input, so the shell carries no condition.
1028 """
1029 if not any(item.name == "workshop" for item in point.inputs):
1030 return ""
1031 value = "${{ inputs.workshop }}" if forge != "gitlab" else "$workshop"
1032 return (
1033 " - name: Pin the driver\n"
1034 f' run: {prog} release.driver --workshop="{value}"\n'
1035 )
1036
1037
1038_PAGES_GRANT = """ permissions:
1039 contents: read
1040 pages: write
1041 id-token: write
1042 environment:
1043 name: github-pages
1044 url: ${{ steps.deployment.outputs.page_url }}
1045 concurrency:
1046 group: pages
1047 cancel-in-progress: false
1048"""
1049
1050_PAGES_UPLOAD = f" - uses: {ACTIONS['github']['upload-pages']}\n"
1051
1052_PAGES_DEPLOY = f""" - id: deployment
1053 uses: {ACTIONS["github"]["deploy-pages"]}
1054"""
1055
1056
1057def _pages_upload_step(condition: str = "") -> str:
1058 """The upload of the built site as the pages artifact, under *condition*."""
1059 return _PAGES_UPLOAD + _if_line(condition) + " with:\n path: site\n"
1060
1061
1062def _pages_job(answers: dict[str, Any], point: Point, job: Job, other: Point) -> str:
1063 """The forge's own pages deploy of the site *job* of *point* uploaded, for *other*.
1064
1065 No checkout and no entry: the one step deploys the artifact the
1066 joined job uploaded, in the pages environment, on *other*'s events.
1067 """
1068 first = str(next(iter(answers.get("runners", ["ubuntu-latest"]))))
1069 condition = _condition(point, other)
1070 return (
1071 _comment(
1072 f"The forge's pages deploy of the site the {job.name} job uploaded:"
1073 " no checkout and no entry, the pages environment alone.",
1074 " ",
1075 )
1076 + " pages:\n"
1077 + (f" if: {condition}\n" if condition else "")
1078 + f" needs: [{job.name}]\n"
1079 + _PAGES_GRANT
1080 + f" runs-on: {first}\n steps:\n"
1081 + _PAGES_DEPLOY
1082 )
1083
1084
1085def _verify_ref_step(point: Point) -> str:
1086 """Refuse a dispatched ref that is not an ancestor of the default branch.
1087
1088 Runs immediately after checkout and before any tool, setup script,
1089 or workspace code executes from the checked-out commit. The input
1090 rides an environment variable rather than shell interpolation to
1091 prevent command injection.
1092 """
1093 if not point.ref_input:
1094 return ""
1095 return (
1096 " - name: Verify ref is on default branch\n"
1097 " env:\n"
1098 f" TARGET_REF: ${{{{ inputs.{point.ref_input} }}}}\n"
1099 " run: >-\n"
1100 ' git fetch --no-tags origin "${GITHUB_REF_NAME:-main}" &&\n'
1101 " git merge-base --is-ancestor HEAD FETCH_HEAD ||\n"
1102 ' (echo "refused: $TARGET_REF is not an ancestor of'
1103 ' ${GITHUB_REF_NAME:-main}" >&2; exit 1)\n'
1104 )
1105
1106
1107def _grants(job: Job, *, pages: bool) -> str:
1108 """GitHub's grants for *job*: organisation defaults are read-only."""
1109 if pages:1109 ↛ 1110line 1109 didn't jump to line 1110 because the condition on line 1109 was never true
1110 return _PAGES_GRANT
1111 lines: list[str] = []
1112 if job.publishes_index:
1113 # Trusted publishing: the id token is minted for the publishing
1114 # environment alone, never for govern or bot environments.
1115 lines.append(" id-token: write")
1116 if job.writes:
1117 lines.append(" contents: write")
1118 if job.dispatches:
1119 # Starting a workflow through the API: the workflow token
1120 # answers 403 ("Resource not accessible by integration")
1121 # without it, and the wave never starts.
1122 lines.append(" actions: write")
1123 if not lines:
1124 return ""
1125 return " permissions:\n" + "".join(line + "\n" for line in lines)
1126
1127
1128def _actions_job(
1129 answers: dict[str, Any],
1130 prog: str,
1131 point: Point,
1132 job: Job,
1133 *,
1134 forge: str,
1135 everything: tuple[Point, ...],
1136) -> str:
1137 """One job of *point* for GitHub or Gitea, from its declaration.
1138
1139 A job of a point that shares its file with a point nobody
1140 inherits from runs on its own point's events alone; the gate's
1141 jobs carry no filter, since the merge point inherits them.
1142 """
1143 runners = [str(runner) for runner in answers.get("runners", ["ubuntu-latest"])]
1144 first = runners[0]
1145 pages = forge == "github" and _seam(answers, point, job) == "pages"
1146 joins = _joins_of(point, job, everything)
1147 lines = [_comment(job.note, " "), f" {job.name}:\n"]
1148 conditions = []
1149 if job.always:
1150 conditions.append("always()")
1151 shared = [
1152 other
1153 for other in _points_of(point.workflow, everything)
1154 if other.name != point.name
1155 ]
1156 if shared and not any(other.inherits == point.name for other in shared):
1157 conditions.append(_event_filter(point))
1158 if _needs_due(point, answers):
1159 conditions.append(f"needs.due.outputs.{job.name} == 'true'")
1160 if job.matrix == "legs" and _dynamic_shards(point, answers):
1161 conditions.append("needs.legs.outputs.skip_check != 'true'")
1162 if conditions:
1163 lines.append(f" if: {' && '.join(conditions)}\n")
1164 needs = _needs(point, job, answers, everything)
1165 if _needs_due(point, answers):
1166 needs = ["due", *needs]
1167 if job.matrix == "legs" and _uses_legs_job(point, answers):
1168 needs = ["legs", *needs]
1169 if (
1170 job.always
1171 and _dynamic_shards(point, answers)
1172 and "check" in needs
1173 and "legs" not in needs
1174 ):
1175 needs = ["legs", *needs]
1176 if needs:
1177 lines.append(f" needs: [{', '.join(needs)}]\n")
1178 if forge == "github":
1179 lines.append(_grants(job, pages=pages))
1180 if job.environment:
1181 env_map = answers.get("environments") or {}
1182 env_name = str(env_map.get(job.environment, job.environment))
1183 lines.append(f" environment: {env_name}\n")
1184 if job.matrix == "legs":
1185 gate = [str(version) for version in answers.get("gate_pythons", ["3.11"])]
1186 if _uses_legs_job(point, answers):
1187 lines.append(
1188 " strategy:\n fail-fast: false\n"
1189 " matrix: ${{ fromJSON(needs.legs.outputs.matrix) }}\n"
1190 " runs-on: ${{ matrix.os }}\n"
1191 )
1192 elif _carries_shards(answers):
1193 # One entry per os, python and shard: the forge names each
1194 # job by the entry's values in order, ``check (windows-latest,
1195 # 3.14, 2of4)``, so the job carries no name of its own, and
1196 # a runner with one shard has no shard key, so its job is
1197 # named as the unsplit leg the runner keys its rows by.
1198 lines.append(" strategy:\n fail-fast: false\n matrix:\n")
1199 lines.append(" include:\n")
1200 counts = _shards(answers, "shards", runners)
1201 for os_label, python, shard in _entries(runners, gate, counts):
1202 tail = f", shard: {shard}" if shard else ""
1203 lines.append(
1204 f' - {{os: {os_label}, python: "{python}"{tail}}}\n'
1205 )
1206 lines.append(" runs-on: ${{ matrix.os }}\n")
1207 else:
1208 lines.append(
1209 " strategy:\n fail-fast: false\n matrix:\n"
1210 f" os: [{_csv(runners)}]\n"
1211 f" python: [{_csv(gate, quoted=True)}]\n"
1212 " runs-on: ${{ matrix.os }}\n"
1213 )
1214 elif job.matrix == "pythons":
1215 pythons = _csv(list(answers.get("python_versions", ["3.11"])), quoted=True)
1216 lines.append(
1217 " strategy:\n fail-fast: false\n matrix:\n"
1218 f" python: [{pythons}]\n runs-on: {first}\n"
1219 )
1220 elif job.matrix == "runners":
1221 lines.append(
1222 " strategy:\n fail-fast: false\n matrix:\n"
1223 f" os: [{_csv(_labels(answers, point, job))}]\n"
1224 " runs-on: ${{ matrix.os }}\n"
1225 )
1226 elif job.matrix == "declared":
1227 lines.append(
1228 " strategy:\n fail-fast: false\n matrix:\n"
1229 f" os: [{_csv(list(job.runners))}]\n"
1230 f" python: [{_csv(list(job.pythons), quoted=True)}]\n"
1231 " runs-on: ${{ matrix.os }}\n"
1232 )
1233 else:
1234 lines.append(f" runs-on: {first}\n")
1235 lines.append(" steps:\n")
1236 lines.append(
1237 _checkout_step(point, job, forge=forge, inputs=answers.get("checkout_inputs"))
1238 )
1239 lines.append(_verify_ref_step(point))
1240 if forge == "github":
1241 lines.append(_setup_uv_step(answers))
1242 lines.append(_collect_step(job, forge=forge, everything=everything))
1243 for other, joined in joins:
1244 lines.append(
1245 _collect_step(
1246 joined,
1247 forge=forge,
1248 everything=everything,
1249 condition=_condition(point, other),
1250 )
1251 )
1252 if job.isolated:
1253 workshop_env = (
1254 "WORKSHOP_DRIVER"
1255 if any(item.name == "workshop" for item in point.inputs)
1256 else ""
1257 )
1258 lines.append(f" - name: {job.step or job.name.capitalize()}\n")
1259 lines.append(_isolated_env(point, job, forge=forge))
1260 lines.append(" run: |\n")
1261 lines.append(
1262 _isolated_run_block(
1263 point, job, indent=" ", workshop_env=workshop_env
1264 )
1265 )
1266 return "".join(lines)
1267 lines.append(_installs_step(_installs(answers, point, job, joins)))
1268 if forge == "github":
1269 lines.append(_store_cache_step())
1270 if job.conan_cache:
1271 lines.append(_conan_cache_step())
1272 if job.cache_dir:
1273 lines.append(_job_cache_step(job))
1274 lines.append(
1275 _enter_step(
1276 answers, matrix_python=job.matrix in ("legs", "pythons", "declared")
1277 )
1278 )
1279 lines.append(_driver_step(prog, point, forge=forge))
1280 lines.append(f" - name: {job.step or job.name.capitalize()}\n")
1281 lines.append(_call_env(job, forge=forge))
1282 sharded = job.matrix == "legs" and _carries_shards(answers)
1283 lines.append(
1284 _call_step(
1285 prog,
1286 point,
1287 job,
1288 shard=sharded,
1289 )
1290 )
1291 lines.append(_publish_step(job, forge=forge, matrix=job.matrix, sharded=sharded))
1292 for other, joined in joins:
1293 condition = _condition(point, other)
1294 lines.append(
1295 _publish_step(
1296 joined,
1297 forge=forge,
1298 matrix=job.matrix,
1299 sharded=sharded,
1300 condition=condition,
1301 )
1302 )
1303 if forge == "github" and _seam(answers, other, joined) == "pages":
1304 lines.append(_pages_upload_step(condition))
1305 if pages:1305 ↛ 1306line 1305 didn't jump to line 1306 because the condition on line 1305 was never true
1306 lines.append(_pages_upload_step() + _PAGES_DEPLOY)
1307 return "".join(lines)
1308
1309
1310def _actions_workflow(
1311 answers: dict[str, Any],
1312 prog: str,
1313 workflow: str,
1314 *,
1315 forge: str,
1316 everything: tuple[Point, ...] | None = None,
1317) -> str:
1318 """The workflow file *workflow* for GitHub or Gitea, from the points that share it.
1319
1320 *everything* is the workspace's points, the builtin four when
1321 absent.
1322 """
1323 everything = everything if everything is not None else points(None)
1324 owners_all = _points_of(workflow, everything)
1325 lines = [f"name: {workflow.removesuffix('.yml')}\n\n"]
1326 for point in owners_all:
1327 lines.append(_comment(point.note))
1328 lines.append("on:\n")
1329 for event in EVENT_NAMES:
1330 owners = [point for point in owners_all if event in point.events]
1331 if not owners:
1332 continue
1333 if event == "pull_request":
1334 # The default types plus labeled: a label a verb or a person
1335 # sets starts a run, whose legs job reads it.
1336 lines.append(
1337 " pull_request:\n types: [opened, synchronize, reopened, labeled]\n"
1338 )
1339 elif event == "push":
1340 lines.append(" push:\n branches: [main]\n")
1341 elif event == "schedule":
1342 lines.append(f' schedule:\n - cron: "{owners[0].cron}"\n')
1343 else:
1344 inputs = owners[0].inputs
1345 if not inputs:
1346 lines.append(" workflow_dispatch:\n")
1347 continue
1348 lines.append(" workflow_dispatch:\n inputs:\n")
1349 for item in inputs:
1350 lines.append(f" {item.name}:\n")
1351 lines.append(f" description: {item.description}\n")
1352 lines.append(
1353 f" required: {'true' if item.required else 'false'}\n"
1354 )
1355 if not item.required:
1356 lines.append(f' default: "{item.default}"\n')
1357 lines.append("\njobs:\n")
1358 for point in owners_all:
1359 if _needs_due(point, answers):
1360 lines.append(_due_job(answers, prog, point, forge=forge))
1361 for job in point.jobs:
1362 if job.joins:
1363 continue
1364 if job.matrix == "legs" and _uses_legs_job(point, answers):
1365 if _dynamic_shards(point, answers):
1366 lines.append(_dynamic_legs_job(answers, prog, point, forge=forge))
1367 else:
1368 lines.append(_legs_job(answers))
1369 if _renders(point, job, answers):
1370 lines.append(
1371 _actions_job(
1372 answers, prog, point, job, forge=forge, everything=everything
1373 )
1374 )
1375 if forge == "github":
1376 for point in owners_all:
1377 for job in point.jobs:
1378 for other, joined in _joins_of(point, job, everything):
1379 if not job.joins and _seam(answers, other, joined) == "pages":
1380 lines.append(_pages_job(answers, point, job, other))
1381 return "".join(lines)
1382
1383
1384def _gitlab_rules(point: Point, everything: tuple[Point, ...]) -> str:
1385 """The rules admitting *point*'s runs, and those of the points inheriting it."""
1386 events: list[str] = list(point.events)
1387 for other in everything:
1388 if other.inherits == point.name:
1389 events.extend(event for event in other.events if event not in events)
1390 lines = [" rules:\n", " - if: $CI_COMMIT_TAG\n when: never\n"]
1391 for event in events:
1392 if event == "pull_request":
1393 condition = '$CI_PIPELINE_SOURCE == "merge_request_event"'
1394 elif event == "push":
1395 condition = '$CI_COMMIT_BRANCH == "main" && $CI_PIPELINE_SOURCE == "push"'
1396 elif event == "schedule":
1397 condition = (
1398 '$CI_PIPELINE_SOURCE == "schedule"'
1399 f' && $FORGE_WORKFLOW == "{point.workflow}"'
1400 )
1401 else:
1402 condition = f'$FORGE_WORKFLOW == "{point.workflow}"'
1403 lines.append(f" - if: '{condition}'\n")
1404 return "".join(lines)
1405
1406
1407def _gitlab_job(
1408 answers: dict[str, Any],
1409 prog: str,
1410 point: Point,
1411 job: Job,
1412 *,
1413 image: str,
1414 everything: tuple[Point, ...],
1415) -> str:
1416 """One job of *point* in the GitLab document, from its declaration.
1417
1418 One executor, one image: a ``legs`` matrix is one leg on the first
1419 runner's label and the first gate Python, so its rows key the same
1420 leg the union expects, and it runs as the shards ``[ci] shards``
1421 gives the first runner through ``parallel: matrix``, each passing
1422 its ``SHARD``; the one document serves every event, so a pull
1423 request's counts are not read. A ``pythons`` or ``runners`` matrix
1424 is one job. A job deploying through the ``pages`` seam is GitLab
1425 Pages' own: a job named ``pages`` publishing ``public/``. A job
1426 that pushes, or writes the store, rewrites origin with the push
1427 token first, since the job token cannot push.
1428 """
1429 joins = _joins_of(point, job, everything)
1430 packages = " ".join(_installs(answers, point, job, joins))
1431 first = str(next(iter(answers.get("runners", ["ubuntu-latest"]))))
1432 stage = "release" if point.name in ("merge", "release") else "check"
1433 pages = _seam(answers, point, job) == "pages"
1434 name = "pages" if pages else job.name
1435 lines = [
1436 _comment(job.note),
1437 f"{name}:\n",
1438 f" stage: {stage}\n",
1439 f" image: {image}\n",
1440 ]
1441 count = _shards(answers, "shards", [first])[first] if job.matrix == "legs" else 1
1442 if count > 1:
1443 spelled = ", ".join(f'"{Shard(index, count)}"' for index in range(1, count + 1))
1444 lines.append(f" parallel:\n matrix:\n - SHARD: [{spelled}]\n")
1445 needs = _needs(point, job, answers, everything)
1446 if needs:
1447 lines.append(f" needs: [{', '.join(needs)}]\n")
1448 variables: list[str] = []
1449 if job.fetch in ("full", "tags"):
1450 variables.append(' GIT_DEPTH: "0"')
1451 elif job.fetch:
1452 variables.append(f' GIT_DEPTH: "{job.fetch}"')
1453 if job.token == "admin":
1454 variables.append(" FORGE_ADMIN_TOKEN: $FORGE_ADMIN_TOKEN")
1455 if variables:
1456 lines.append(" variables:\n" + "".join(v + "\n" for v in variables))
1457 rules = _gitlab_rules(point, everything)
1458 if job.always:
1459 rules = rules.replace(" - if: '", " - when: always\n if: '")
1460 lines.append(rules)
1461 lines.append(" script:\n")
1462 if point.ref_input:
1463 # The pipeline runs on the base branch; verify the dispatched
1464 # commit is an ancestor of HEAD before checking it out so no
1465 # unreviewed branch can run in a privileged pipeline.
1466 lines.append(
1467 f' - \'git merge-base --is-ancestor "${point.ref_input}" HEAD ||'
1468 f' (echo "refused: ${point.ref_input} is not an ancestor of'
1469 " $CI_COMMIT_REF_NAME\" >&2; exit 1)'\n"
1470 )
1471 lines.append(f' - git checkout --quiet "${point.ref_input}"\n')
1472 if job.pushes:
1473 lines.append(" - git fetch --tags\n")
1474 if job.pushes or job.writes:
1475 # The job token cannot push: a store write and a receipt tag
1476 # ride the push token. The address
1477 # is the server's own protocol, host and port: an instance
1478 # off 443 (the local one) is unreachable at a bare https host.
1479 lines.append(
1480 ' - git remote set-url origin "${CI_SERVER_PROTOCOL}://oauth2:'
1481 "${GITLAB_PUSH_TOKEN}@${CI_SERVER_HOST}:${CI_SERVER_PORT}/"
1482 '${CI_PROJECT_PATH}.git"\n'
1483 )
1484 if job.isolated:
1485 workshop_env = (
1486 "workshop" if any(item.name == "workshop" for item in point.inputs) else ""
1487 )
1488 lines.append(" - |\n")
1489 lines.append(
1490 _isolated_run_block(point, job, indent=" ", workshop_env=workshop_env)
1491 )
1492 return "".join(lines) + "\n"
1493 if packages:
1494 # Root in the container image: no sudo.
1495 lines.append(f" - apt-get update -q && apt-get install -y -q {packages}\n")
1496 lines.append(" - source setup.sh gitlab\n")
1497 driver = _driver_step(prog, point, forge="gitlab")
1498 if driver:
1499 lines.append(f" - {driver.split('run: ', 1)[1]}")
1500 call = f"{prog} ci.run --point={point.name} --job={job.name}"
1501 if job.matrix == "legs":
1502 python = str(next(iter(answers.get("gate_pythons", ["3.11"]))))
1503 call += f' --os="{first}" --python="{python}"'
1504 if count > 1:
1505 call += ' --shard="$SHARD"'
1506 elif job.matrix == "declared":
1507 call += f' --os="{job.runners[0]}" --python="{job.pythons[0]}"'
1508 elif job.matrix == "pythons":
1509 python = str(next(iter(answers.get("python_versions", ["3.11"]))))
1510 call += f' --python="{python}"'
1511 lines.append(f" - {call}\n")
1512 if pages:1512 ↛ 1513line 1512 didn't jump to line 1513 because the condition on line 1512 was never true
1513 lines.append(" - mv site public\n artifacts:\n paths: [public]\n")
1514 return "".join(lines) + "\n"
1515 # The job's own artifact, then what the joins publish and the site
1516 # a joined pages seam hands to the pages job; a join's artifact
1517 # expires, since the deploy that reads it follows at once.
1518 kept = list(job.paths) if job.publishes else []
1519 joined_paths: list[str] = []
1520 for other, joined in joins:
1521 joined_paths += list(joined.paths) if joined.publishes else []
1522 if _seam(answers, other, joined) == "pages":
1523 joined_paths.append("site")
1524 paths = kept + [path for path in joined_paths if path not in kept]
1525 if paths:
1526 spelled = ", ".join(f'"{path}"' for path in paths)
1527 lines.append(f" artifacts:\n paths: [{spelled}]\n")
1528 if job.upload_always:
1529 lines.append(" when: always\n")
1530 retention = job.retention_days or (1 if joined_paths else 0)
1531 if retention:
1532 unit = "day" if retention == 1 else "days"
1533 lines.append(f" expire_in: {retention} {unit}\n")
1534 return "".join(lines) + "\n"
1535
1536
1537def _gitlab_document(
1538 answers: dict[str, Any], prog: str, *, everything: tuple[Point, ...] | None = None
1539) -> str:
1540 """The one GitLab document: every point's jobs, the builtin four by default.
1541
1542 The merge point's dispatch job starts the wave through the API at
1543 the base branch with the squash in the ``ref`` variable, which the
1544 document routes on ``FORGE_WORKFLOW`` like a hand dispatch.
1545 """
1546 python = str(next(iter(answers.get("python_versions", ["3.11"]))))
1547 image = _gitlab_image(answers, python)
1548 lines = [
1549 """# The gate, the merge point, the nightly and the train, GitLab-shaped,
1550# generated by the workshop. One pipeline definition: workflow rules
1551# admit FORGE_WORKFLOW-routed pipelines (a dispatch, the clock), merge
1552# requests and main, and every pipeline is named after its workflow
1553# file, so a run reads on every forge the same way and a dispatched
1554# gate is told from a dispatched wave. Every job sources the entry
1555# script in its own shell, then calls the runner bare. The clock
1556# itself is a pipeline schedule, a project setting the governance
1557# reconcile creates, never a line here. GitLab CI variables arrive as
1558# process environment, the cascade's highest rung already: declare
1559# PYTHON_PUBLISH_INDEX, PYTHON_REGISTRY_URL, FORGE_TOKEN,
1560# UV_PUBLISH_TOKEN and GITLAB_PUSH_TOKEN (a project access token with
1561# write_repository: the job token cannot push, and the state store
1562# and the receipt tags are pushes) as CI
1563# variables, masked where their values allow it.
1564workflow:
1565 name: $FORGE_WORKFLOW
1566 rules:
1567 - if: $FORGE_WORKFLOW
1568 - if: $CI_PIPELINE_SOURCE == "merge_request_event"
1569 variables:
1570 FORGE_WORKFLOW: ci.yml
1571 - if: $CI_COMMIT_BRANCH == "main"
1572 variables:
1573 FORGE_WORKFLOW: ci.yml
1574
1575stages: [check, release]
1576
1577"""
1578 ]
1579 everything = everything if everything is not None else points(None)
1580 for point in everything:
1581 for job in point.jobs:
1582 if job.joins or not _renders(point, job, answers):
1583 continue
1584 lines.append(
1585 _gitlab_job(
1586 answers, prog, point, job, image=image, everything=everything
1587 )
1588 )
1589 for other, joined in _joins_of(point, job, everything):
1590 if _seam(answers, other, joined) == "pages":
1591 lines.append(
1592 _gitlab_pages_job(
1593 job, other, image=image, everything=everything
1594 )
1595 )
1596 return "".join(lines)
1597
1598
1599def _gitlab_pages_job(
1600 job: Job, other: Point, *, image: str, everything: tuple[Point, ...]
1601) -> str:
1602 """GitLab Pages' own job, publishing the site *job* kept, on *other*'s events."""
1603 return (
1604 _comment(
1605 f"GitLab Pages' deploy of the site the {job.name} job kept: no"
1606 " entry, the artifact moved to public/."
1607 )
1608 + f"pages:\n stage: release\n image: {image}\n needs: [{job.name}]\n"
1609 + _gitlab_rules(other, everything)
1610 + " script:\n - mv site public\n artifacts:\n paths: [public]\n\n"
1611 )
1612
1613
1614def generate(root: Path) -> dict[str, str]:
1615 """Every generated CI file for *root*'s forge kind, by path.
1616
1617 The workflows call the CLI by the name this process runs under,
1618 so a branded runner emits workflows that call itself and needs
1619 no configuration. The emitted ``setup.sh`` at the root is the
1620 entry every workflow's jobs share. The template-artifact job is
1621 emitted only for a home: the contract declares where to publish
1622 and a member extension ships the tree; an ordinary instance's
1623 release has no templates to publish.
1624 """
1625 from livery.workshop._entry import entry_script
1626 from livery.workshop._provenance import generated_header
1627
1628 prog = footman.prog()
1629 everything = emitted_points(root)
1630 facts = _facts(root, everything)
1631 kind = str(facts["forge_kind"])
1632 header = generated_header("#")
1633 if kind in ("github", "gitea"):
1634 # One file per workflow: the gate and the merge point share
1635 # ci.yml, the nightly, the release and every contributed point
1636 # have their own.
1637 workflows = sorted({point.workflow for point in everything})
1638 files = {
1639 f".{kind}/workflows/{workflow}": _actions_workflow(
1640 facts, prog, workflow, forge=kind, everything=everything
1641 )
1642 for workflow in workflows
1643 }
1644 else:
1645 files = {".gitlab-ci.yml": _gitlab_document(facts, prog, everything=everything)}
1646 files["setup.sh"] = entry_script(root)
1647 return {path: header + content for path, content in files.items()}
1648
1649
1650def generated_files(root: Path) -> dict[Path, str]:
1651 """The generated artifacts as absolute paths under *root*."""
1652 return {root / relative: content for relative, content in generate(root).items()}
1653
1654
1655#: What every generated file opens with, whatever runner wrote it.
1656GENERATED_MARK = "# Generated by the workshop from workshop.toml"
1657
1658
1659def retired_files(root: Path) -> tuple[Path, ...]:
1660 """The generated workflow files under *root* this emission does not own, to delete.
1661
1662 Every file in the forge's workflow directory that opens with
1663 `GENERATED_MARK` and is not in this emission is retired: the
1664 workflow of a point a package contributed and that went with the
1665 package. A file without the mark is a person's and is never
1666 touched.
1667 """
1668 found: list[Path] = []
1669 owned = set(generate(root))
1670 for directory in (".github/workflows", ".gitea/workflows"):
1671 folder = root / directory
1672 if not folder.is_dir():
1673 continue
1674 for path in sorted(folder.glob("*.yml")):
1675 relative = path.relative_to(root).as_posix()
1676 if relative in owned:
1677 continue
1678 try:
1679 head = path.read_text("utf-8", errors="replace")[: len(GENERATED_MARK)]
1680 except OSError:
1681 continue
1682 if head == GENERATED_MARK:
1683 found.append(path)
1684 return tuple(found)