Coverage for packages/workshop/src/livery/workshop/_registries.py: 99%
Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_registries.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_lifecycle.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_dev_release.py, packages/workshop/tests/test_workshop_contract_file.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/conan/tests/test_conan_releases.py, packages/extensions/conan/tests/test_conan_publish.py ran.
Keys
- r m x p show or hide the lines of a kind
- j k the next or previous highlighted chunk
- 0 the top of the page
- 1 the first highlighted chunk
- [ ] the previous or next file
- u the index
- ? show or hide this help
1"""Where each artifact kind's registry lives: the resolution ladder.
3One resolution for every artifact kind the ecosystem publishes or
4probes, so no caller derives a registry address on its own. The
5ladder, per kind: the declaration wins (the env cascade's variables
6first, machine truth over committed; then the contract's
7``[registries]`` table), else the forge's own hosted registry of
8that kind, else the ecosystem default where one exists (pypi.org
9for python), else a refusal naming the kind and the rungs it tried.
10A declaration may be a local folder or share: every kind publishes
11to a path, so a workspace can work with no registry server at all.
14from __future__ import annotations
17from dataclasses import MISSING, dataclass, fields
18from pathlib import Path
19from typing import TYPE_CHECKING, cast
21from livery.footman import fail
22from livery.workshop._contract import load_contract
24if TYPE_CHECKING:
25 from collections.abc import Mapping
27 from livery.forge import RegistryKind
29#: The env cascade's declaration variables, per kind. The python
30#: pair predates the ladder and stays: addresses in the committed
31#: env are the machine-facing declaration the CI rung materialises.
33 "python": ("PYTHON_REGISTRY_URL", "PYTHON_PUBLISH_INDEX"),
34 "conan": ("CONAN_REMOTE_URL",),
35 "container": ("CONTAINER_REGISTRY",),
38#: The ecosystem default, where one exists: the read index and the
39#: upload endpoint. The publish step refuses an empty address, so a
40#: deliberate PyPI publish arrives there as this rung's explicit URL;
41#: trusted publishing or a token carries the credential.
43 "python": ("https://pypi.org/simple", "https://upload.pypi.org/legacy/"),
46#: The env cascade's credential variable, per kind. Read on every
47#: rung, because the credential is independent of where the address
48#: came from: a declared or default URL may still need auth. Secrets
49#: never ride the contract's [registries] table.
50_CREDENTIAL_VARS = {
51 "python": "PYTHON_REGISTRY_TOKEN",
55@dataclass(frozen=True)
56class RegistryTarget:
57 """One resolved registry for one artifact kind.
60 kind: Which artifact registry this is.
61 url: The registry's address: the read index for python (the
62 publish endpoint is ``publish_url``), the remote for
63 conan, the reference prefix for container. A local path
64 when the declaration was a folder.
65 publish_url: Where python dists upload; empty means the
66 publisher's own default resolution (uv publish and
67 trusted publishing on pypi.org). Unused by other kinds.
68 local: True when the target is a folder or share rather
70 releases: True when the artifacts ride the forge's own
71 releases, attached to each member's receipt tag. The
72 route a conan package takes on a forge that hosts no
73 conan registry; `url` is then the repository's page, for
75 token: The registry credential, for reads and uploads alike:
76 the kind's credential variable when set, else the forge
77 lane's token when the forge rung answered. Empty reads
78 anonymously and lets the publisher's own resolution
84 publish_url: str = ""
85 local: bool = False
87 releases: bool = False
90 def from_table(cls, table: Mapping[str, object]) -> RegistryTarget:
91 """The target a ``registry-target`` table holds.
93 The engine gives each step of the ``publish`` phase the registry
94 it resolved as the ``registry-target`` key: a table of this
95 class's fields by name, which the step reads back with this
96 constructor. The table holds ``kind`` and ``url``, and a field
97 it leaves out takes its default.
100 table: Each field of the target by its name.
103 The target the table holds.
106 ValueError: when the table is not a registry target: it has
107 no ``kind`` or no ``url``, a value has another type than
108 its field, or a key names no field. The message names
109 the field and what it takes, and never a value, since
110 ``token`` is a credential.
112 names = tuple(field.name for field in fields(cls))
113 unknown = [name for name in table if name not in names]
115 raise ValueError(
116 f"not a registry target: the table holds {', '.join(unknown)};"
117 f" a registry target holds {', '.join(names)}"
119 for field in fields(cls):
120 if field.default is MISSING and field.name not in table:
121 raise ValueError(
122 f"not a registry target: the table has no {field.name},"
123 " which every registry target holds"
126 kind=_text(table, "kind"),
127 url=_text(table, "url"),
128 publish_url=_text(table, "publish_url"),
129 local=_flag(table, "local"),
130 token=_text(table, "token"),
131 releases=_flag(table, "releases"),
134 def to_table(self) -> dict[str, object]:
135 """This target as the ``publish`` phase's ``registry-target`` table."""
139 "publish_url": self.publish_url,
142 "releases": self.releases,
146def _text(table: Mapping[str, object], name: str) -> str:
147 """*table*'s string at *name*; empty when the table has none."""
148 value = table.get(name, "")
149 if not isinstance(value, str):
150 raise ValueError(_wrong_type(name, "str", value))
154def _flag(table: Mapping[str, object], name: str) -> bool:
155 """*table*'s boolean at *name*; false when the table has none."""
156 value = table.get(name, False)
157 if not isinstance(value, bool):
158 raise ValueError(_wrong_type(name, "bool", value))
162def _wrong_type(name: str, wanted: str, value: object) -> str:
163 """The refusal of a field whose value is not a *wanted*, naming no value."""
165 f"not a registry target: {name} takes a {wanted}, and the table's"
166 f" {name} is of type {type(value).__name__}"
170def target_table(target: RegistryTarget) -> dict[str, object]:
171 """*target* as the ``publish`` phase's ``registry-target``: its fields by name."""
172 return target.to_table()
175def _is_local(value: str) -> bool:
176 if value.startswith("file://"):
178 return "://" not in value and (value.startswith(("/", "./", "~")) or ":\\" in value)
181def _normalise(value: str) -> str:
182 if value.startswith("file://"):
183 return value.removeprefix("file://")
187def registry(root: Path, kind: str) -> RegistryTarget:
188 """The registry the workspace at *root* reads and publishes *kind* artifacts at.
190 *kind* is ``python``, ``conan`` or ``container``. The first rung
191 that names one wins: the environment's variables for the kind, the
192 contract's ``[registries]`` table, the forge's own registry of the
193 kind, then the ecosystem's default.
196 Failed: when *kind* is not an artifact registry kind, naming
199 return resolve_registry(root, kind)
202def resolve_registry(root: Path, kind: str) -> RegistryTarget:
203 """The registry for *kind*, through the ladder; refusal teaches.
205 The rungs, in order: the env cascade's variables (machine truth
206 over committed declarations), the contract's ``[registries]``
207 table, the forge's own registry of the kind, the ecosystem
208 default. A python declaration may split read and publish
209 addresses; the other kinds carry one.
211 env_vars = _ENV_VARS.get(kind)
212 if env_vars is None:
213 fail(f"{kind!r} is not an artifact registry kind: python, conan, container")
214 token = os.environ.get(_CREDENTIAL_VARS.get(kind, ""), "")
215 declared_read = os.environ.get(env_vars[0], "")
216 declared_publish = os.environ.get(env_vars[1], "") if len(env_vars) > 1 else ""
217 if not declared_read and not declared_publish:
218 contract = load_contract(root / "workshop.toml")
219 table = contract.get("registries") or {}
220 entry = table.get(kind) if isinstance(table, dict) else None
221 if isinstance(entry, str):
222 declared_read = entry
223 elif isinstance(entry, dict):
224 declared_read = str(entry.get("url", ""))
225 declared_publish = str(entry.get("publish", ""))
226 if declared_read or declared_publish:
227 read = declared_read or declared_publish
229 # A declaration naming the forge's own registry keeps the
230 # forge lane token: committing the address must not lose
231 # the credential the forge rung would have carried. A
232 # foreign address never inherits it.
233 resolved = _forge_registry(root, kind)
234 if resolved is not None:
235 forge_url, lane_token = resolved
236 if forge_url and (
237 read.startswith(forge_url) or declared_publish.startswith(forge_url)
239 token = lane_token
240 return RegistryTarget(
242 url=_normalise(read),
243 publish_url=_normalise(declared_publish),
244 local=_is_local(read),
247 resolved = _forge_registry(root, kind)
248 if resolved is None and kind == "conan":
249 # A forge with no conan registry still has releases, and a
250 # conan package is a file: each member's caches ride its own
251 # receipt tag. The consumer reads them back through the same
252 # forge, so nothing outside the repository is involved.
253 return _forge_releases(root)
254 if resolved is not None:
255 forge_url, lane_token = resolved
256 if kind == "python":
257 # The forge-registry shape: the base takes uploads and
258 # serves the simple index under /simple.
259 return RegistryTarget(
261 url=f"{forge_url}/simple",
262 publish_url=forge_url,
263 token=token or lane_token,
265 return RegistryTarget(kind=kind, url=forge_url, token=token or lane_token)
266 default = _ECOSYSTEM.get(kind)
267 if default is not None:267 ↛ 271line 267 didn't jump to line 271 because the condition on line 267 was always true
268 return RegistryTarget(
269 kind=kind, url=default[0], publish_url=default[1], token=token
272 f"no {kind} registry resolves: nothing declared (env or the"
273 " [registries] table), this forge hosts none, and the kind has"
274 " no ecosystem default. Declare one, a local folder included."
278def _forge_releases(root: Path) -> RegistryTarget:
279 """The conan target on a forge whose releases carry the caches.
281 The address is the repository itself: the publisher attaches each
282 host's saved cache to the member's release, and the probe reads
283 the same listing. The refusal names what to declare when this
284 workspace has no forge either.
286 from livery.workshop._forge_lane import this_repository
287 from livery.workshop._tokens import forge_token
289 contract = load_contract(root / "workshop.toml")
290 forge_table = contract.get("forge") or {}
292 repository = this_repository(root)
293 except BaseException as error:
295 f"no conan registry resolves: nothing declared (env or the"
296 f" [registries] table), and this forge's releases did not"
297 f" answer either ({error}). Declare [registries.conan] in"
298 " workshop.toml, a local folder included."
300 token, _ = forge_token(
301 str(forge_table.get("kind", "")), str(forge_table.get("url", ""))
303 return RegistryTarget(
305 url=repository.web_url(),
311def _forge_registry(root: Path, kind: str) -> tuple[str, str] | None:
312 """The forge's registry of *kind* and the lane token, or None.
314 The token is the lane's own (``FORGE_TOKEN``, host-qualified
315 first), because the forge's registry authenticates with the same
316 credential as its API. It can be empty: a backend that resolves
317 its token through its own dialect never surfaces it here, and the
318 read then rides anonymously, which a public owner serves.
320 from livery.forge import Unsupported
321 from livery.workshop._forge_lane import this_forge
322 from livery.workshop._tokens import forge_token
324 contract = load_contract(root / "workshop.toml")
325 forge_table = contract.get("forge") or {}
326 owner = str(forge_table.get("owner", ""))
330 forge = this_forge(root)
331 except BaseException as error:
332 # No reachable forge is a rung that does not answer, not a
333 # resolution failure: the ladder continues, and the reason is
334 # printed rather than swallowed.
335 print(f" the forge rung did not answer: {error}")
337 # resolve_registry validated the kind at its boundary; the cast
338 # states that proof for the checkers.
339 registry_kind = cast("RegistryKind", kind)
341 url = forge.registry_url(registry_kind, owner)
342 except Unsupported:
344 forge_kind = str(forge_table.get("kind", ""))
345 lane_token, _ = forge_token(forge_kind, str(forge_table.get("url", "")))
346 if not lane_token:
347 # The connection is the one source of the resolved
348 # credential: the backend read its own dialect variable at
349 # connect time, and the registry authenticates with the same
351 lane_token = forge.token
352 return url, lane_token