Coverage for packages/workshop/src/livery/workshop/_entry.py: 99%

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_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.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.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_env.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/workshop/tests/test_tools_restub.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_docs.py ran.

1"""The workspace entry contract: the emitted ``setup.sh`` at the root.
2
3One choke point owns machine readiness. The script ensures uv at the
4lock's pinned version, syncs the venv against the lock, records the
5sync receipt, and emits the environment: sourced by a shell it enters
6that shell, and ``setup.sh github`` persists the emission into
7``GITHUB_ENV``/``GITHUB_PATH`` so every later CI step calls the
8runner bare. A GitLab job sources ``setup.sh gitlab``, and its shell
9keeps the emission for the job's later lines. The script sets the
10variables the workspace's extensions declare before its sync, and on a
11CI job of either kind places each one that names ``{place}`` in the
12job's own directory. Between entries the per-command reconcile
13(``livery.workshop._reconcile``) keeps the venv following the lock.
14
15The script is a generated artifact like the CI workflows: emitted by
16``livery.workshop._ci_generate.generate``, written by
17``fm sync``, judged by the drift check. POSIX only; a
18Windows CI leg runs it under the runner's bash, and a pwsh spelling
19is deferred to the tool-store port.
20"""
21
22from __future__ import annotations
23
24import json
25import shlex
26import tomllib
27from pathlib import Path
28from typing import TYPE_CHECKING
29
30import livery.footman as footman
31
32if TYPE_CHECKING:
33 from livery.workshop._declaration import DeclaredVariable
34
35
36def locked_uv_version(root: Path) -> str:
37 """The uv version the workspace pins, or "".
38
39 ``toolroom.lock`` is the single source of truth for the pinned uv
40 version; ``uv.lock`` is consulted only as a fallback when no tool
41 lock names uv (for example a workspace before its first tool lock).
42 A workspace without either pin answers "": the emitters then leave
43 the bootstrap unpinned rather than inventing a version.
44 """
45 tool_lock = root / "toolroom.lock"
46 if tool_lock.is_file():
47 try:
48 data = json.loads(tool_lock.read_text("utf-8"))
49 except (OSError, ValueError):
50 data = None
51 if isinstance(data, dict):
52 tools = data.get("tools")
53 if isinstance(tools, dict):53 ↛ 57line 53 didn't jump to line 57 because the condition on line 53 was always true
54 entry = tools.get("uv")
55 if isinstance(entry, dict) and entry.get("version"):
56 return str(entry["version"])
57 lock = root / "uv.lock"
58 if not lock.is_file():
59 return ""
60 try:
61 parsed = tomllib.loads(lock.read_text("utf-8"))
62 except (tomllib.TOMLDecodeError, UnicodeDecodeError):
63 return ""
64 for package in parsed.get("package", []):
65 if isinstance(package, dict) and package.get("name") == "uv":
66 return str(package.get("version", ""))
67 return ""
68
69
70def installer_url(pin: str) -> str:
71 """The uv installer URL, versioned when a *pin* exists."""
72 if pin:
73 return f"https://astral.sh/uv/{pin}/install.sh"
74 return "https://astral.sh/uv/install.sh"
75
76
77# __PROG__ and __INSTALLER__ are substituted at emission; a template
78# with markers instead of an f-string, because the script itself is
79# full of shell braces.
80_SCRIPT = """\
81# The entry contract: uv at the lock's pin -> the venv synced against
82# the lock, its native members left for later -> `__PROG__ sync --locked`,
83# the one a person runs, changing nothing a commit holds: the tools
84# installed, the stubs and the checkout's own files written -> the
85# environment entered here -> the native members built against it.
86# Source it to enter this shell; `setup.sh github` persists the
87# emission (GITHUB_ENV/GITHUB_PATH) for the CI steps after it, which
88# then call __PROG__ bare, and a GitLab job sources `setup.sh gitlab`,
89# whose shell runs the job's later lines.
90_root="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
91# The variables the workspace's extensions declare, set before the sync
92# below, whose builds may read them. A value naming a directory of its
93# own is placed in a CI job's own directory and is not set off a CI job:
94# a GitHub job's is its temp, RUNNER_TEMP, and a GitLab job's is
95# .workshop under its checkout, CI_PROJECT_DIR, a path no two jobs
96# running at once share, which git ignores. A job whose runner names no
97# such directory stops here. A value the environment already carries
98# wins, unless the declaration says always: here the job's environment
99# is formed, so such a value beats one the runner sets for every job.
100_place=""
101# Called with the variable naming the job's directory, its value, the
102# declared variable, and the extension that declares it.
103_job_place() {
104 if [ -z "$2" ]; then
105 echo "setup: this job's runner sets no $1; $4 declares $3 in a" \\
106 "directory of the job's own, so run it on a runner that sets one" >&2
107 return 1
108 fi
109 if [ ! -d "$2" ]; then
110 echo "setup: $1 names $2, which is not a directory; $4 declares $3" \\
111 "in it, so its runner must create it first" >&2
112 return 1
113 fi
114}
115# Called with the variable's name, its value, always or nothing, the
116# extension that declares it, and what the variable is for.
117_declared() {
118 eval "_held=\\"\\${$1:-}\\""
119 if [ -n "$_held" ] && [ "$_held" != "$2" ]; then
120 [ "$3" = always ] || return 0
121 echo "setup: $1 is $2, as $4 declares it; the environment's $1," \\
122 "$_held, is not used: $5" >&2
123 fi
124 eval "$1=\\"\\$2\\""
125 export "$1"
126}
127# On a GitHub job uv's cache and the runner's data directory, the tool
128# store under it, live under the runner's temp, the working drive. On
129# a Windows runner the working drive is not the home directory's: a
130# store on the home drive cannot hardlink its entry points into the
131# checkout and copies instead, and so would uv's cache into the venv.
132# The workflow restores the store before this script runs and saves
133# it after the job; uv's cache is placed for the drive alone. Exported
134# before the sync and the materialise, and persisted by the emission
135# below for every later step. A placement the job already carries
136# stands: a runner that keeps its caches across jobs sets them in its
137# own environment, and the temp is only where nothing is set.
138if [ "${1:-}" = github ]; then
139__GITHUB_PLACE__ UV_CACHE_DIR="${UV_CACHE_DIR:-$RUNNER_TEMP/uv-cache}"
140 __DATA_DIR_VAR__="${__DATA_DIR_VAR__:-$RUNNER_TEMP/footman}"
141 export UV_CACHE_DIR __DATA_DIR_VAR__
142elif [ "${1:-}" = gitlab ]; then
143__GITLAB_PLACE__fi
144__DECLARED__# Any uv on PATH bootstraps the venv and the first sync; when none is
145# present, install the lock's pin once under the runner's data
146# directory. Once `__PROG__ sync --locked` and the emission below run,
147# PATH leads with the tool store's pinned uv, so the project always
148# runs the pinned version.
149_pin="__UV_PIN__"
150if ! command -v uv >/dev/null 2>&1; then
151 _uv_dir="${__DATA_DIR_VAR__:-$HOME/.local/share/footman}/uv/${_pin:-any}"
152 if [ ! -x "$_uv_dir/uv" ]; then
153 curl -LsSf __INSTALLER__ | env UV_UNMANAGED_INSTALL="$_uv_dir" sh >&2
154 fi
155 PATH="$_uv_dir:$PATH"
156 export PATH
157 # Name the install that failed here. Left to fall through, uv's
158 # absence surfaces below as "uv sync failed", which sends the
159 # reader after the venv instead of after the network.
160 if ! command -v uv >/dev/null 2>&1; then
161 echo "setup: could not install uv${_pin:+ $_pin}:" \\
162 "check network access to astral.sh" >&2
163 return 1 2>/dev/null || exit 1
164 fi
165fi
166# An ARRAY, not a string: CI may invoke this with zsh, which does not
167# word-split unquoted expansions, so a two-word string would arrive
168# as one argument. Arrays expand the same under bash and zsh.
169_sync_args=()
170[ -f "$_root/uv.lock" ] && _sync_args+=(--locked)
171# A native member builds its extension at install against the tools
172# the store supplies below (the compiler's helpers, the provider that
173# resolves its native dependencies), so this sync leaves it out; the
174# workshop's sync below enters the environment itself and its own uv
175# sync builds it.
176_native=(__NATIVE_SKIP__)
177_sync() { uv sync --project "$_root" "${_sync_args[@]}" "$@" >&2; }
178_sync "${_native[@]}" \\
179 || { sleep 10; _sync "${_native[@]}"; } \\
180 || { echo "setup: uv sync failed" >&2; return 1 2>/dev/null || exit 1; }
181# The sync receipt: the lock as this venv last saw it. The runner's
182# per-command reconcile compares the two and re-syncs on drift.
183[ -f "$_root/uv.lock" ] && cp "$_root/uv.lock" "$_root/.venv/.workshop-sync-receipt"
184_run() { uv run --project "$_root" --no-sync __PROG__ "$@"; }
185# The sync a person runs, in the mode that changes nothing a commit
186# holds: the branch stays, no tracked file is written. It installs
187# the tools the lock holds, with a receipt each, and the stubs the type
188# checkers read into typings/, and writes the checkout's own untracked
189# files (the agent's fragments, skills and settings), so a job holds
190# what a person's checkout holds. A lock that is not current refuses
191# here, naming the lock. A tool the store could not supply is named and
192# not fatal: the gate says which step that cost. The emission below
193# puts the receipts' paths on PATH, so a tool the venv does not carry
194# (an archive from its own release) resolves for the gate.
195_run sync --locked >&2 \\
196 || { echo "setup: __PROG__ sync --locked refused; its message names why" >&2; \\
197 return 1 2>/dev/null || exit 1; }
198# Entered here, whether sourced or run, in one call: a sourcing shell
199# keeps it, and under `github` the same call persists the emission
200# for the steps after. Nothing installs after this line: the sync
201# above left the venv complete.
202if [ "${1:-}" = github ]; then
203 eval "$(_run env.emit posix --github)"
204else
205 eval "$(_run env.emit posix)"
206fi
207"""
208
209
210def entry_script(root: Path) -> str:
211 """The emitted ``setup.sh`` body for *root*, header not included.
212
213 The variables the extensions of *root*'s set declare are rendered
214 from their declarations: each one's line, and in each CI branch the
215 check that the job names a directory of its own, once for each
216 variable that names ``{place}``.
217
218 Raises:
219 Failed: when two of the extensions declare one variable, naming
220 both.
221 """
222 from livery.footman import directory_variable
223 from livery.workshop._variables import workspace_variables
224
225 pin = locked_uv_version(root)
226 skipped = " ".join(f"--no-install-package {name}" for name in native_members(root))
227 variables = workspace_variables(root)
228 return (
229 _SCRIPT.replace("__PROG__", footman.prog())
230 .replace("__INSTALLER__", installer_url(pin))
231 .replace("__DATA_DIR_VAR__", directory_variable("DATA_DIR"))
232 .replace("__UV_PIN__", pin)
233 .replace("__NATIVE_SKIP__", skipped)
234 .replace("__GITHUB_PLACE__", _job_place("github", variables))
235 # A shell branch takes no empty body: one that places nothing
236 # does nothing.
237 .replace("__GITLAB_PLACE__", _job_place("gitlab", variables) or " :\n")
238 .replace("__DECLARED__", _declared_lines(variables))
239 )
240
241
242def _job_place(mode: str, variables: tuple[DeclaredVariable, ...]) -> str:
243 """The lines of the script's *mode* branch that name the job's own directory.
244
245 One check for each of *variables* that names ``{place}``, so a job
246 whose runner names no directory stops naming the variable and the
247 extension that declares it, then the directory itself. Empty when
248 none names ``{place}``.
249 """
250 from livery.workshop._variables import JOB_DIRECTORIES
251
252 placed = [variable for variable in variables if variable.placed]
253 if not placed:
254 return ""
255 named, under = JOB_DIRECTORIES[mode]
256 lines = [
257 f' _job_place {named} "${{{named}:-}}" {variable.name}'
258 f" {shlex.quote(variable.extension)} \\\n"
259 " || { return 1 2>/dev/null || exit 1; }\n"
260 for variable in placed
261 ]
262 lines.append(f' _place="${named}{"/" + under if under else ""}"\n')
263 return "".join(lines)
264
265
266def _declared_lines(variables: tuple[DeclaredVariable, ...]) -> str:
267 """One ``_declared`` line for each of *variables*, as the script calls it.
268
269 A value naming ``{place}`` is set only where the script found one.
270 """
271 from livery.workshop._variables import PLACE_WORD
272
273 lines: list[str] = []
274 for variable in variables:
275 value = '"$_place"'.join(
276 shlex.quote(part) if part else ""
277 for part in variable.value.split(PLACE_WORD)
278 )
279 line = " ".join(
280 (
281 "_declared",
282 variable.name,
283 value or "''",
284 "always" if variable.always else "''",
285 shlex.quote(variable.extension),
286 shlex.quote(variable.doc),
287 )
288 )
289 lines.append(
290 f'[ -z "$_place" ] || {line}\n' if variable.placed else f"{line}\n"
291 )
292 return "".join(lines)
293
294
295def native_members(root: Path) -> tuple[str, ...]:
296 """The distribution names of the job-built members uv installs, in path order.
297
298 A member a job of the release point builds before the wave, the
299 workspace's ``job-built-members`` answer, carries native code its
300 install builds against the store's tools, so the entry installs it
301 after the tools are in the environment; every other member installs
302 in the first sync. A job-built member the uv workspace does not hold
303 is no uv install and is left out.
304 """
305 from livery.workshop._identity import roster
306 from livery.workshop._queries import JOB_BUILT_MEMBERS, answer
307
308 if not (root / "packages").is_dir():
309 return ()
310 built = answer(root, JOB_BUILT_MEMBERS)
311 # The roster's dev entry marks a member of the uv workspace.
312 return tuple(
313 entry["name"]
314 for entry in roster(root)
315 if "dev" in entry and f"packages/{entry['dir']}" in built
316 )