Coverage for packages/workshop/src/livery/workshop/_isolated.py: 84%

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_isolated.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_governance.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/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_docs.py ran.

1"""Isolated Tier 1 bootstrapper for pinned ``livery-workshop`` jobs.
2
3Tier 1 jobs (``govern`` holding ``FORGE_ADMIN_TOKEN`` and ``publish``
4holding ``PYPI_TOKEN`` / OIDC) never run ``setup.sh``, never install
5non-privileged workspace members from ``packages/*/``, never import
6``tasks.py``, and never fold ``.repo.env``. Instead they launch
7``uv run --isolated --no-project`` with either the pinned external
8``livery-workshop==<version>`` from ``uv.lock`` (consumer repositories)
9or the ``CODEOWNERS``-guarded transitive editable closure of
10``livery-workshop`` (self-hosting repositories such as ``livery``), and
11invoke the target entry module under ``python3 -I``.
12"""
13
14from __future__ import annotations
15
16import tomllib
17from collections.abc import Sequence
18from pathlib import Path
19from typing import Any
20
21#: The distribution driving isolated Tier 1 jobs.
22DRIVER_DIST = "livery-workshop"
23
24#: The default PyPI simple index; omitted when it is the locked source.
25_PYPI_SIMPLE = "https://pypi.org/simple"
26
27
28def _lock_packages(lock_path: Path) -> list[dict[str, Any]]:
29 """Every ``[[package]]`` table in *lock_path*, refusing unreadable locks."""
30 if not lock_path.is_file():
31 raise RuntimeError(
32 f"cannot bootstrap isolated {DRIVER_DIST}: {lock_path} does not exist"
33 )
34 try:
35 data = tomllib.loads(lock_path.read_text("utf-8"))
36 except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError) as error:
37 raise RuntimeError(f"cannot read {lock_path}: {error}") from error
38 packages = data.get("package")
39 if not isinstance(packages, list):39 ↛ 40line 39 didn't jump to line 40 because the condition on line 39 was never true
40 raise RuntimeError(f"{lock_path} carries no [[package]] entries")
41 return [entry for entry in packages if isinstance(entry, dict)]
42
43
44def _editable_closure(
45 packages: list[dict[str, Any]], root_name: str
46) -> tuple[str, ...]:
47 """Transitive editable paths of *root_name* in *packages*, deterministic order."""
48 by_name = {
49 entry["name"]: entry for entry in packages if isinstance(entry.get("name"), str)
50 }
51 visited: set[str] = set()
52 ordered: list[str] = []
53
54 def visit(name: str) -> None:
55 if name in visited:55 ↛ 56line 55 didn't jump to line 56 because the condition on line 55 was never true
56 return
57 visited.add(name)
58 entry = by_name.get(name)
59 if entry is None:59 ↛ 60line 59 didn't jump to line 60 because the condition on line 59 was never true
60 return
61 source = entry.get("source")
62 if not isinstance(source, dict) or "editable" not in source:62 ↛ 63line 62 didn't jump to line 63 because the condition on line 62 was never true
63 return
64 for dep in entry.get("dependencies") or ():
65 if isinstance(dep, dict) and isinstance(dep.get("name"), str):65 ↛ 64line 65 didn't jump to line 64 because the condition on line 65 was always true
66 visit(dep["name"])
67 ordered.append(str(source["editable"]))
68
69 visit(root_name)
70 return tuple(ordered)
71
72
73def isolated_command(
74 root: Path,
75 module: str,
76 args: Sequence[str] = (),
77 *,
78 workshop_version: str = "",
79) -> list[str]:
80 """Build the ``uv run --isolated --no-project`` argv for Tier 1 *module*.
81
82 Consumer repositories install ``livery-workshop==<locked-version>``
83 from the locked index (never installing ``packages/*/``).
84 Self-hosting repositories install only ``livery-workshop`` and its
85 transitive editable dependencies (all guarded in ``CODEOWNERS``).
86 An explicit *workshop_version* overrides ``uv.lock`` (for
87 ``release.yml --workshop`` recovery runs).
88 """
89 cmd = ["uv", "run", "--isolated", "--no-project"]
90 if workshop_version:
91 cmd.extend(["--with", f"{DRIVER_DIST}=={workshop_version}"])
92 else:
93 packages = _lock_packages(root / "uv.lock")
94 driver = next(
95 (entry for entry in packages if entry.get("name") == DRIVER_DIST),
96 None,
97 )
98 if driver is None:
99 raise RuntimeError(
100 f"uv.lock names no {DRIVER_DIST} entry; cannot run isolated {module}"
101 )
102 source = driver.get("source")
103 if isinstance(source, dict) and "editable" in source:
104 for rel_path in _editable_closure(packages, DRIVER_DIST):
105 cmd.extend(["--with", f"./{rel_path}"])
106 else:
107 version = str(driver.get("version") or "").strip()
108 if not version:108 ↛ 109line 108 didn't jump to line 109 because the condition on line 108 was never true
109 raise RuntimeError(
110 f"uv.lock entry for {DRIVER_DIST} carries no version"
111 )
112 registry = (
113 str(source.get("registry") or "").strip()
114 if isinstance(source, dict)
115 else ""
116 )
117 if registry and registry.rstrip("/") != _PYPI_SIMPLE:117 ↛ 119line 117 didn't jump to line 119 because the condition on line 117 was always true
118 cmd.extend(["--extra-index-url", registry])
119 cmd.extend(["--with", f"{DRIVER_DIST}=={version}"])
120 cmd.extend(["--", "python3", "-I", "-m", module, *args])
121 return cmd
122
123
124def isolated_shell_launcher(
125 module: str,
126 args: Sequence[str] = (),
127 *,
128 workshop_env: str = "",
129) -> str:
130 """Render a self-contained stdlib ``python3 -I -c`` command for CI YAML.
131
132 Reads ``uv.lock`` with stdlib ``tomllib`` under ``python3 -I`` (so
133 nothing in the checkout directory or ``PYTHONPATH`` can shadow
134 stdlib or execute before ``uv`` starts) and launches *module* in an
135 isolated ephemeral environment with ``python3 -I -m <module>``.
136 """
137 # Keep the bootstrap snippet pure stdlib and single-quoted safe.
138 args_repr = ", ".join(repr(arg) for arg in args)
139 script = (
140 "import os, pathlib, subprocess, sys, tomllib\n"
141 f"mod = {module!r}\n"
142 f"extra = [{args_repr}]\n"
143 f"pin = os.environ.get({workshop_env!r}, '').strip()"
144 f" if {bool(workshop_env)!r} else ''\n"
145 "cmd = ['uv', 'run', '--isolated', '--no-project']\n"
146 "if pin:\n"
147 f" cmd += ['--with', f'{DRIVER_DIST}=={{pin}}']\n"
148 "else:\n"
149 " pkgs = [p for p in tomllib.loads("
150 "pathlib.Path('uv.lock').read_text('utf-8')).get('package', [])"
151 " if isinstance(p, dict)]\n"
152 " by = {p['name']: p for p in pkgs if 'name' in p}\n"
153 f" drv = by.get({DRIVER_DIST!r})\n"
154 " if drv is None:\n"
155 f" sys.exit('uv.lock names no {DRIVER_DIST} entry')\n"
156 " src = drv.get('source') or {}\n"
157 " if 'editable' in src:\n"
158 " seen, order = set(), []\n"
159 " def walk(n):\n"
160 " if n in seen: return\n"
161 " seen.add(n)\n"
162 " e = by.get(n)\n"
163 " if not e or 'editable' not in (e.get('source') or {}): return\n"
164 " for d in e.get('dependencies') or ():\n"
165 " if isinstance(d, dict) and 'name' in d: walk(d['name'])\n"
166 " order.append(e['source']['editable'])\n"
167 f" walk({DRIVER_DIST!r})\n"
168 " for p in order: cmd += ['--with', f'./{p}']\n"
169 " else:\n"
170 " reg = str(src.get('registry') or '').strip()\n"
171 f" if reg and reg.rstrip('/') != {_PYPI_SIMPLE!r}:\n"
172 " cmd += ['--extra-index-url', reg]\n"
173 f" cmd += ['--with', f'{DRIVER_DIST}=={{drv[\"version\"]}}']\n"
174 "cmd += ['--', 'python3', '-I', '-m', mod] + extra\n"
175 "sys.exit(subprocess.call(cmd))\n"
176 )
177 return script