Coverage for packages/workshop/src/livery/workshop/_tools.py: 92%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_sync_locked.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_repair.py, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_plugin_tools.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_balance.py, packages/workshop/tests/test_tools_restub.py, packages/workshop/tests/test_tools_materialise.py, packages/workshop/tests/test_kind_tools.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/nanobind/tests/test_nanobind_kind.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_taskref.py, packages/extensions/docs/tests/test_llms.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/docs/tests/test_docs_site.py, packages/extensions/docs/tests/test_docs_phase.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/conan/tests/test_conan_publish.py, packages/extensions/conan/tests/test_conan_kind.py, packages/extensions/cmake/tests/test_measured_run.py, packages/extensions/cmake/tests/test_cpp_kind.py, packages/extensions/agents/tests/test_agents.py ran.

1"""The tools a workspace requires: six declaration sites, one lock, receipts.
2
3A tool requirement is a name with a floor, `git` or `git>=2.40`, and
4six sites declare them: the base, under `[toolroom] requires` in its
5contract file, for uv, which makes the venv every step runs in; the
6steps that judge a present package, each naming its tools; a listed
7extension, the workspace's or one a package's set holds, under
8`[toolroom] requires` in its `extension.toml`, for the tools it runs
9(cmake's cmake and ninja, conan's conan), and in a `[for.<target>]`
10table, for what it needs while that table applies; a plugin the
11project mounts, through its `workshop.tools` entry point; a package
12instance, in its `workshop.toml` under `[toolroom] requires`, for what
13its extensions cannot know; and the project, in the root contract's
14`[toolroom] requires`, for what belongs to the repository. The sites'
15requirements union, and `toolroom.lock` at the root holds one version
16per tool for the whole repository, the newest the catalogue lists that
17satisfies every floor and resolves on every supported host. The root
18contract's `[workspace] hosts` names those hosts, every host key when
19it is absent, and `[toolroom] index` names where the catalogue is read
20from: the published index by URL, a directory holding one, or the
21records that build one.
22
23Entering the environment materialises the bundle the sites require, on
24`fm sync` and on `fm toolroom.add`: each locked tool is supplied through
25the machine's store in one of three modes, its entry points linked
26into the checkout's bin directory, its own directories on PATH, or no
27PATH at all, and a receipt under `.workshop/receipts/` records the
28exact version, the host, the deployment's digest and what reached
29PATH. A receipt is a checkout's statement of what it installed, as the
30release train's receipt is a release's; `fm env.check` reads them
31back and names the drift when the lock's deployment has moved under
32one.
33
34The stubs the type checkers read are materialised too, into `typings/`
35at the root, pyright's default stub path and a search path the rendered
36configuration hands the other three checkers: one rendering per tool
37the lock holds, at the locked version, as `livery.toolroom.stubs`
38modules with `livery.toolroom.handles` beside them declaring each
39handle, which the installed tools package's index imports. Both live
40under the `livery.toolroom` namespace package, beside the tools package
41and never inside its directory: a tree inside it would shadow the
42package for a checker run on explicit paths. The store renders each
43stub from the locked version's own surface, from the records or from
44the index, so no source holds a stub. A tool the workspace does not
45deploy gets no stub. `fm toolroom.restub` writes them, and so do `fm sync`
46and every lock verb.
47"""
48
49from __future__ import annotations
50
51import functools
52from typing import TYPE_CHECKING
53
54if TYPE_CHECKING:
55 from livery.strongroom import Source
56 from livery.toolroom.store import (
57 Catalogue,
58 Deployment,
59 Ensured,
60 Graph,
61 Home,
62 Listed,
63 Lock,
64 Locked,
65 Requirement,
66 )
67 from livery.workshop._packages import Package
68
69import hashlib
70import json
71import os
72import shutil
73import sys
74import tempfile
75from dataclasses import dataclass, field, replace
76from pathlib import Path
77from typing import Any, NoReturn, cast
78
79from livery.footman import Failed, fail, prog, run
80from livery.workshop._contract import load_contract
81from livery.workshop._packages import discover_packages
82
83WORKSPACE = "workspace"
84"""The contract table the supported hosts live under."""
85
86
87DEFAULT_HOSTS: tuple[str, ...] = ()
88"""The hosts supported when `[workspace] hosts` is absent; empty for
89every host key, which the store names and which is read only then."""
90
91VERDICT_PHASES = ("format", "lint", "typecheck", "typecomplete", "test")
92"""The phases whose tools take no host allowance: the version is the verdict."""
93
94PINNED_TOOLS = ("uv",)
95"""The tools no allowance reaches by name: the entry pins uv."""
96
97BASE_SITE = "the base"
98"""The site of the base's own requirements, the ones every workspace has."""
99
100TYPINGS = "typings"
101"""The directory under the root the stubs are written into, pyright's default."""
102
103TYPINGS_PACKAGE = ("livery", "toolroom")
104"""The namespace package the stubs and handles live under, beside the tools package."""
105
106
107def tools_table(path: Path) -> dict[str, object]:
108 """The `[toolroom]` table of the contract at *path*, judged; empty when absent."""
109 from livery.toolroom.store import TABLE
110
111 if not path.is_file():
112 return {}
113 return dict(load_contract(path).get(TABLE) or {})
114
115
116def _requires(table: dict[str, object], *, site: str) -> list[Requirement]:
117 from livery.toolroom.store import LockError, Requirement
118
119 declared = cast("list[str]", table.get("requires", []))
120 try:
121 return [Requirement.parse(text, site=site) for text in declared]
122 except LockError as error:
123 fail(str(error))
124
125
126@functools.cache
127def base_requirements() -> tuple[Requirement, ...]:
128 """The tools the base requires in every workspace, at the site `BASE_SITE`.
129
130 Read from the `[toolroom] requires` of the base's contract file,
131 which spells them as an extension's `extension.toml` does: uv,
132 which makes the venv every step runs in, so a workspace with no
133 package requires it too.
134
135 Raises:
136 Failed: when an entry is not a requirement, naming it.
137 """
138 from livery.toolroom.store import TABLE
139 from livery.workshop._contract_keys import base_contract
140
141 data = base_contract()
142 return tuple(_requires(dict(data.get(TABLE, {})), site=BASE_SITE))
143
144
145def requirements(root: Path) -> tuple[Requirement, ...]:
146 """Every requirement the six sites declare, in site order.
147
148 The base's come first, at the site `BASE_SITE`: a workspace
149 requires uv with or without a package, since its own `tasks.py`
150 and tests run in the venv uv makes. The steps that judge a present
151 package bring the tools they run, each requirement naming
152 `step <name>` as its site, and so do the steps that judge the
153 root's own files, which are judged as a package holding the root's
154 set is.
155 An extension's site is `extension <name>`, read from its
156 ``extension.toml``'s ``[toolroom] requires`` and from each of its
157 ``[for.<target>]`` tables that applies now: cmake's build tools
158 are required while a package's set holds cmake, and a measurer's
159 tool while the workspace lists what it measures for. An extension
160 that neither the workspace lists nor a package's set holds
161 declares nothing here, since listing is the only activation
162 channel. A plugin the project mounts through its direct
163 dependencies is `plugin <name>`, read from its entry module
164 ([livery.workshop._tools.plugin_tools][]).
165 """
166 from livery.toolroom.store import LockError, Requirement
167 from livery.workshop._extensions import extension_tools
168
169 packages = discover_packages(root) if (root / "packages").is_dir() else ()
170 found: list[Requirement] = list(base_requirements())
171 # The steps that judge a present package bring their tools, each
172 # naming its step: unregistering a step removes its tool.
173 from livery.workshop._steps import tools_for
174
175 for tool, step in tools_for(_held(root, packages)):
176 found.append(Requirement.parse(tool, site=f"step {step}"))
177 try:
178 declared_by_extension = extension_tools(root)
179 except RuntimeError as error:
180 fail(str(error))
181 for extension, declared in declared_by_extension.items():
182 try:
183 found += [
184 Requirement.parse(text, site=f"extension {extension}")
185 for text in declared
186 ]
187 except LockError as error:
188 fail(str(error))
189 for plugin, declared in plugin_tools(root).items():
190 try:
191 found += [
192 Requirement.parse(text, site=f"plugin {plugin}") for text in declared
193 ]
194 except LockError as error:
195 fail(str(error))
196 for package in packages:
197 contract = package.directory / "workshop.toml"
198 found += _requires(tools_table(contract), site=f"{package.path}/workshop.toml")
199 found += _requires(tools_table(root / "workshop.toml"), site="workshop.toml")
200 return tuple(found)
201
202
203def _held(root: Path, packages: tuple[Package, ...]) -> tuple[str, ...]:
204 """The extensions the root's own files and the *packages* hold.
205
206 The root's own files, its `tasks.py` and tests, hold the root's
207 set, and are judged as a package holding it is.
208 """
209 from livery.workshop._composition import extension_set
210 from livery.workshop._extensions import root_set
211
212 held = (name for package in packages for name in extension_set(package))
213 return tuple(dict.fromkeys((*root_set(root), *held)))
214
215
216def plugin_tools(root: Path) -> dict[str, tuple[str, ...]]:
217 """The tools each plugin the project mounts declares, by its entry point name.
218
219 The plugins are the ``footman.builtin`` names the project's direct
220 dependencies offer, as footman's project rung mounts them. A plugin
221 declares the tools its verbs need in a data module that its
222 ``workshop.tools`` entry point names, under the plugin's own name:
223 ``"livery.forge" = "livery.forge._dev_tools:TOOLS"``, a tuple of
224 requirement strings, ``("docker?",)`` for one it can do without.
225 Loading it imports that module alone, never the plugin's tasks.
226
227 Raises:
228 Failed: when a declaration is not a tuple or list of strings,
229 naming the plugin.
230 """
231 from livery.footman import installed_entry_points, project_builtins
232
233 declared = {entry.name: entry for entry in installed_entry_points("workshop.tools")}
234 found: dict[str, tuple[str, ...]] = {}
235 for name in project_builtins(root):
236 entry = declared.get(name)
237 if entry is None:
238 continue
239 value: object = entry.load()
240 if not isinstance(value, (tuple, list)) or not all(
241 isinstance(text, str)
242 for text in value # pyright: ignore[reportUnknownVariableType]
243 ):
244 fail(
245 f"plugin {name}: its workshop.tools entry point ({entry.value}) is"
246 ' not a tuple of requirement strings, ("docker?",)'
247 )
248 found[name] = tuple(str(text) for text in value) # pyright: ignore[reportUnknownVariableType, reportUnknownArgumentType]
249 return found
250
251
252def host_allowed(root: Path) -> tuple[str, ...]:
253 """The tools whose copy on the machine may serve: the root contract's.
254
255 The root contract's `[toolroom] host-allowed`, each name once,
256 sorted. A name no site requires yet is kept and named by the lock
257 as an allowance ahead of its requirement: a workspace may allow
258 `cmake` before its first C++ package arrives, and the lock's line
259 is where a misspelling shows. A tool a step reads its verdict from
260 refuses, naming the steps that read it: a linter that varies by
261 machine makes the gate disagree with CI. `uv` refuses by name,
262 since the entry pins it. A tool an extension that writes release
263 notes requires refuses, naming the extension: a release's entries
264 must not depend on the machine. A download whose executable is
265 not named like the tool, or that has none, refuses too: the
266 allowance finds the tool on PATH by its name.
267 """
268 from livery.toolroom.store import LockError, Requirement
269 from livery.workshop._extensions import notes_tools
270 from livery.workshop._steps import step_for, tools_for
271
272 declared = cast(
273 "list[str]", tools_table(root / "workshop.toml").get("host-allowed", [])
274 )
275 names = tuple(sorted(set(declared)))
276 if not names:
277 return ()
278 packages = discover_packages(root) if (root / "packages").is_dir() else ()
279 verdicts: dict[str, set[str]] = {}
280 for tool, step in tools_for(_held(root, packages)):
281 if step_for(step).phase in VERDICT_PHASES:281 ↛ 280line 281 didn't jump to line 280 because the condition on line 281 was always true
282 verdicts.setdefault(tool, set()).add(step)
283 writers: dict[str, str] = {}
284 for extension, requires in notes_tools(root).items():
285 for line in requires:
286 try:
287 parsed = Requirement.parse(line, site=f"extension {extension}")
288 except LockError as error:
289 fail(str(error))
290 writers[parsed.name] = extension
291 for name in names:
292 where = f"workshop.toml: [toolroom] host-allowed names {name}"
293 if name in PINNED_TOOLS:
294 fail(f"{where}, which takes no allowance: the entry pins {name}")
295 if name in writers:
296 fail(
297 f"{where}, which takes no allowance: extension {writers[name]}"
298 " writes the release notes with it"
299 )
300 if name in verdicts:
301 readers = sorted(verdicts[name])
302 fail(
303 f"{where}, whose version is a verdict: {', '.join(readers)}"
304 f" {'reads' if len(readers) == 1 else 'read'} it"
305 )
306 return names
307
308
309def unrequired_allowances(root: Path) -> tuple[str, ...]:
310 """The host-allowed names no site requires yet, sorted: allowances ahead of need."""
311 required = {requirement.name for requirement in requirements(root)}
312 return tuple(name for name in host_allowed(root) if name not in required)
313
314
315def _host_probe_gap(listing: Catalogue, name: str, version: str, host: str) -> str:
316 """Why *name* cannot be found on PATH by its own name; empty when it can."""
317 from livery.toolroom.store import DOWNLOAD_KINDS, CatalogueError, RecordError
318
319 listed = listing.listed(name)
320 if listed.kind not in DOWNLOAD_KINDS:320 ↛ 321line 320 didn't jump to line 321 because the condition on line 320 was never true
321 return ""
322 try:
323 deployment = listing.deployment(name, version, host)
324 except (CatalogueError, RecordError):
325 return ""
326 if not deployment.entry_points:326 ↛ 327line 326 didn't jump to line 327 because the condition on line 326 was never true
327 return (
328 f"{name} has no executable; the allowance finds a tool on PATH by its name"
329 )
330 first = Path(deployment.entry_points[0]).name
331 if first.lower().removesuffix(".exe") != name:
332 return (
333 f"{name}'s executable is {first}; the allowance finds a tool on PATH by"
334 " its name"
335 )
336 return ""
337
338
339def tool_names(root: Path, host: str = "") -> tuple[str, ...]:
340 """The tools the sites require, each once, in the order first declared.
341
342 With *host*, the tools required there: a requirement scoped to other
343 hosts alone (``dotnet_coverage@windows``) requires nothing on it.
344 """
345 return tuple(
346 dict.fromkeys(
347 requirement.name
348 for requirement in requirements(root)
349 if not host or requirement.on((host,))
350 )
351 )
352
353
354def this_host() -> str:
355 """This machine's host key as the store names it: ``macos-arm``."""
356 import platform
357
358 from livery.toolroom.store import host_key
359
360 return host_key(platform.system(), platform.machine())
361
362
363def supported_hosts(root: Path) -> tuple[str, ...]:
364 """The hosts the workspace supports and locks for, in host-key order.
365
366 `[workspace] hosts` names them in the requirement scope tokens:
367 a platform (`macos`), a host key (`linux-arm`), and either with `!`
368 to remove it, a list of removals alone starting from every host.
369 Absent, every host key is supported.
370
371 Raises a refusal for a token that is neither a platform nor a host
372 key, and for a list that is empty or leaves no host.
373 """
374 from livery.toolroom.store import HOSTS, Scope, SpecError
375
376 every = DEFAULT_HOSTS or HOSTS
377 path = root / "workshop.toml"
378 table = load_contract(path).get(WORKSPACE) if path.is_file() else None
379 declared = cast("dict[str, object]", table or {}).get("hosts")
380 if declared is None:
381 return every
382 where = "workshop.toml: [workspace] hosts"
383 tokens = cast("list[str]", declared)
384 if not tokens:
385 fail(f"{where} is empty; name the hosts, or drop the key for every host")
386 try:
387 scope = Scope.parse(",".join(tokens), where=where, spelled=str(tokens))
388 except SpecError as error:
389 fail(str(error))
390 hosts = scope.hosts(every)
391 if not hosts:
392 fail(f"{where} {tokens} leaves no host; name at least one host")
393 return hosts
394
395
396def index_source(root: Path) -> str:
397 """Where the catalogue is read from, as `[toolroom] index` names it.
398
399 Defaults to the published tool index when `[toolroom] index` is
400 omitted. A URL is read as an index; a path, relative to the root,
401 is a directory holding an index or the records that build one.
402 """
403 from livery.toolroom.store import CatalogueError
404 from livery.toolroom.store import index_source as declared_source
405
406 try:
407 return declared_source(tools_table(root / "workshop.toml"), root)
408 except CatalogueError as error:
409 fail(str(error))
410
411
412def _index_label(root: Path) -> str:
413 """Portable label of *root*'s primary catalogue for lock and collision messages."""
414 from livery.toolroom.store import DEFAULT_INDEX
415
416 table = tools_table(root / "workshop.toml")
417 if "index" not in table:417 ↛ 418line 417 didn't jump to line 418 because the condition on line 417 was never true
418 return DEFAULT_INDEX
419 declared = table["index"]
420 return declared if isinstance(declared, str) and declared else DEFAULT_INDEX
421
422
423def _local_records(root: Path, primary: str) -> Path | None:
424 """Local ``records/`` overlay when it holds records distinct from *primary*."""
425 from livery.toolroom.store import LOCAL_RECORDS, is_records
426
427 candidate = root / LOCAL_RECORDS
428 if not is_records(str(candidate)):
429 return None
430 if "://" not in primary and candidate.resolve() == Path(primary).resolve():
431 return None
432 return candidate
433
434
435def has_index(root: Path) -> bool:
436 """Whether *root* has a valid catalogue source (explicit or the default index)."""
437 table = tools_table(root / "workshop.toml")
438 if "index" not in table:
439 return True
440 declared = table["index"]
441 return isinstance(declared, str) and bool(declared)
442
443
444def receipt_gap(tool: str, receipt: ToolReceipt, bin_dir: Path) -> str:
445 """Why what *receipt* claims does not hold here; empty when it does.
446
447 A receipt is the store's own record of what it installed for this
448 checkout, so it is the thing to check: looking for an executable by
449 a tool's name instead answers a different question, and answers it
450 wrongly for a tool that is not a program.
451
452 What a receipt claims depends on how the tool was supplied. One
453 that puts directories on PATH claims they exist and that each entry
454 point runs from one of them, the venv's own bin, or PATH, since a
455 name is not always a binary's (``git_cliff`` installs
456 ``git-cliff``). One that carries environment values claims each
457 value that is a path is there: the cmake-conan provider is a file
458 CMake reads, and no program by that name exists anywhere. One that
459 claims nothing was verified on the host rather than installed, so
460 the host must still answer for it.
461
462 Returns:
463 The first claim that does not hold, as a line to print after
464 the tool's name, or empty when every claim does.
465 """
466 for spelled in receipt.paths:
467 if not Path(spelled).is_dir():
468 return f"MISSING (the receipt's path {spelled} is not there)"
469 for name in receipt.entry_points:
470 if not _entry_point_runs(name, receipt, bin_dir):
471 return f"MISSING (the receipt names {name}, which does not run)"
472 for key, value in sorted(receipt.env.items()):
473 # A value that is a path is checked, and a path is judged by
474 # `is_absolute`: a Windows receipt names `C:\...`, which starts
475 # with a drive and not a slash.
476 named = Path(value)
477 if named.is_absolute() and not named.exists():
478 return f"MISSING ({key} names {value}, which is not there)"
479 # A receipt claiming nothing was verified on the host rather than
480 # installed, so the host has to answer for the tool now.
481 claims_nothing = not (receipt.paths or receipt.entry_points or receipt.env)
482 if claims_nothing and not (shutil.which(tool) or (bin_dir / tool).is_file()):
483 return "MISSING (verified on the host, and not on PATH now)"
484 return ""
485
486
487def _entry_point_runs(name: str, receipt: ToolReceipt, bin_dir: Path) -> bool:
488 """Whether *name* runs: from the receipt's paths, the venv's bin, or PATH."""
489 own = (Path(spelled) / name for spelled in receipt.paths)
490 return (
491 any(candidate.is_file() for candidate in own)
492 or (bin_dir / name).is_file()
493 or bool(shutil.which(name))
494 )
495
496
497def store_cannot_supply(root: Path) -> str:
498 """Why the store supplies nothing here; empty when it can.
499
500 The sites require tools whatever a contract says, because the
501 base requires uv: a workspace with no package still runs in the
502 venv uv makes. Nothing is supplied until a lock names versions,
503 and nothing can be locked until the contract names a catalogue to
504 resolve against, so the two are one question with one answer a
505 reader can act on.
506
507 Empty when a lock is present, and empty for a workspace that
508 requires no tool at all.
509 """
510 required = tool_names(root)
511 if not required or current_lock(root) is not None:
512 return ""
513 named = ", ".join(required[:4])
514 rest = f", and {len(required) - 4} more" if len(required) > 4 else ""
515 lines = [
516 f"the tools this workspace requires are not locked: {named}{rest}."
517 " Nothing is materialised from a store without a lock, so the"
518 " first verb that reaches for one fails with no executable found."
519 ]
520 if not has_index(root):
521 lines += [
522 "",
523 "Name the catalogue to resolve against in workshop.toml:",
524 "",
525 " [toolroom]",
526 ' index = "<the published index\'s URL, or a directory of records>"',
527 ]
528 lines += [
529 "",
530 f"Then `{prog()} toolroom.lock` writes the lock and"
531 f" `{prog()} sync` supplies what it names.",
532 ]
533 return "\n".join(lines)
534
535
536def catalogue(root: Path, *, offline: bool = False) -> Catalogue:
537 """The catalogue the repository resolves against.
538
539 Reads `[toolroom] index` (or the published index by default). When
540 *root* also carries a local `records/` directory holding records
541 distinct from the primary source, those records are layered over the
542 primary catalogue; any colliding tool name refuses naming both.
543 """
544 from livery.toolroom.store import LOCAL_RECORDS, Catalogue, CatalogueError
545
546 primary = index_source(root)
547 label = _index_label(root)
548 base = _read_catalogue(primary, offline=offline)
549 local = _local_records(root, primary)
550 overlay = (
551 _read_catalogue(str(local), offline=offline) if local is not None else None
552 )
553 key = (id(base), label, id(overlay) if overlay is not None else 0)
554 cached = _LAYERED_CATALOGUES.get(key)
555 if cached is not None:
556 return cached
557 tagged = base.with_source(label)
558 if overlay is None:
559 _LAYERED_CATALOGUES[key] = tagged
560 return tagged
561 try:
562 layered = Catalogue.layer(
563 tagged,
564 overlay.with_source(LOCAL_RECORDS),
565 base_source=label,
566 overlay_source=LOCAL_RECORDS,
567 )
568 except CatalogueError as error:
569 fail(str(error))
570 _LAYERED_CATALOGUES[key] = layered
571 return layered
572
573
574#: The catalogues this process read, by source, mode and the source's
575#: identity: one read serves every caller in the process. A sync asks
576#: for the catalogue five times (the lock judged, the tools supplied,
577#: the stubs written); an index by URL answers each read over the
578#: network, and a records directory loads every record each time.
579_CATALOGUES: dict[tuple[Any, ...], Catalogue] = {}
580_LAYERED_CATALOGUES: dict[tuple[Any, ...], Catalogue] = {}
581
582
583def _source_stamp(source: str) -> tuple[Any, ...] | None:
584 """What identifies the catalogue at *source* now.
585
586 None for an index by URL, whose pointer stands for the process. For
587 a directory index, the pointer file's modification time and size,
588 which the verbs that build an index move; for a records directory,
589 every record file's. A pointer that is not there is None too, and
590 the read refuses by name.
591 """
592 if "://" in source:592 ↛ 593line 592 didn't jump to line 593 because the condition on line 592 was never true
593 return None
594 from livery.toolroom.store import POINTER, records_in
595
596 directory = Path(source)
597 pointer = directory / POINTER
598 if pointer.is_file():
599 found = pointer.stat()
600 return (found.st_mtime_ns, found.st_size)
601 stamps = []
602 for path in records_in(directory):
603 try:
604 found = path.stat()
605 except OSError:
606 return None
607 stamps.append((path.name, found.st_mtime_ns, found.st_size))
608 return tuple(stamps) or None
609
610
611def forget_catalogues() -> None:
612 """Drop every catalogue this process read, so the next read is fresh."""
613 _CATALOGUES.clear()
614 _LAYERED_CATALOGUES.clear()
615
616
617def _read_catalogue(source: str, *, offline: bool) -> Catalogue:
618 """The catalogue at *source*, records or index, with no build first.
619
620 A source is read once per process: a second read answers from the
621 first until the source's files change.
622 """
623 from livery.toolroom.store import Catalogue, CatalogueError
624
625 key = (source, offline, _source_stamp(source))
626 held = _CATALOGUES.get(key)
627 if held is not None:
628 return held
629 try:
630 listing = Catalogue.at(source, home=_home(), offline=offline)
631 except CatalogueError as error:
632 fail(str(error))
633 _CATALOGUES[key] = listing
634 return listing
635
636
637def _home() -> Home:
638 return store_home()
639
640
641def store_home() -> Home:
642 """The tool store's home on this machine, where every checkout's tools are.
643
644 The ``toolroom`` directory in the runner's data directory, one per
645 machine and shared by every checkout on it, as a
646 [livery.toolroom.store.Home][].
647 """
648 from livery.footman import data_dir
649 from livery.toolroom.store import Home
650
651 return Home.under(data_dir())
652
653
654def lock_path(root: Path) -> Path:
655 """The lock's file, `toolroom.lock` at the root."""
656 from livery.toolroom.store import LOCK_FILE
657
658 return root / LOCK_FILE
659
660
661def current_lock(root: Path) -> Lock | None:
662 """The lock as committed, or `None` when the repository has none yet."""
663 from livery.toolroom.store import Lock, LockError
664
665 path = lock_path(root)
666 if not path.is_file():
667 return None
668 try:
669 return Lock.load(path)
670 except LockError as error:
671 fail(str(error))
672
673
674def lock_is_current(root: Path, *, offline: bool = False) -> tuple[bool, str]:
675 """Whether `toolroom.lock` is what the sites resolve to now; and what moved.
676
677 The question `--locked` and `--check` ask, and nothing is written to
678 answer it. An entry that still satisfies every floor stands, so a
679 newer version published since the lock was written moves nothing:
680 that is what an upgrade is for. What moves the answer is a
681 requirement the lock does not hold, or holds at a version that no
682 longer satisfies.
683
684 The graphs are not compared: a delegated tool's graph is resolved
685 when its version enters the lock and written beside it, so a fresh
686 resolution never carries one, and reading its absence as a move
687 would move every delegated entry on every check.
688
689 Returns:
690 Whether the lock on disk is current, and why not when it is
691 not: no lock at all, a requirement nothing satisfies, or the
692 tools whose entries would move.
693 """
694 from livery.toolroom.store import LOCK_FILE, LockError, resolve_lock
695
696 held = current_lock(root)
697 if held is None:
698 return False, f"there is no {LOCK_FILE}"
699 listing = catalogue(root, offline=offline)
700 try:
701 fresh = resolve_lock(
702 listing,
703 with_runtimes(tuple(requirements(root)), listing),
704 hosts=supported_hosts(root),
705 keep=held,
706 host_allowed=host_allowed(root),
707 )
708 except LockError as error:
709 return False, str(error)
710 current, resolved = _entries(held), _entries(fresh)
711 if fresh.hosts == held.hosts and resolved == current:
712 return True, ""
713 names = set(resolved) | set(current)
714 moved = sorted(name for name in names if resolved.get(name) != current.get(name))
715 return False, f"the lock would move: {', '.join(moved)}"
716
717
718def _entries(lock: Lock) -> dict[str, dict[str, Any]]:
719 """The lock's entries without their graphs: what the current check compares."""
720 return {
721 name: {key: value for key, value in entry.to_json().items() if key != "graph"}
722 for name, entry in lock.tools.items()
723 }
724
725
726def write_lock(
727 root: Path,
728 *,
729 upgrade: tuple[str, ...] = (),
730 relock: tuple[str, ...] = (),
731 offline: bool = False,
732) -> Lock:
733 """Resolve the sites' requirements and write the lock; the lock written.
734
735 An entry the lock already holds stands unless it is named in
736 *upgrade* or no longer satisfies; a refusal names the tool, each
737 floor with its site, and the host at fault. A delegated tool whose
738 version entered the lock has its graph resolved with it, and one
739 named in *relock* has its graph resolved again though its version
740 stands, which is what an install the graph could not satisfy asks
741 for.
742 """
743 from livery.toolroom.store import LockError, resolve_lock
744
745 listing = catalogue(root, offline=offline)
746 kept = current_lock(root)
747 allowed = host_allowed(root)
748 try:
749 lock = resolve_lock(
750 listing,
751 with_runtimes(tuple(requirements(root)), listing),
752 hosts=supported_hosts(root),
753 keep=kept,
754 upgrade=upgrade,
755 host_allowed=allowed,
756 )
757 except LockError as error:
758 fail(str(error))
759 # What the resolution left out, an optional tool it could not serve.
760 for note in lock.notes:760 ↛ 761line 760 didn't jump to line 761 because the loop on line 760 never started
761 print(f" {note}")
762 for name in allowed:
763 if name not in lock.tools:
764 continue
765 for host in lock.tools[name].on or lock.hosts:
766 if gap := _host_probe_gap(listing, name, lock.tools[name].version, host):
767 fail(f"workshop.toml: [toolroom] host-allowed: {gap}")
768 lock, notes = with_graphs(root, lock, listing, kept=kept, relock=relock)
769 lock.save(lock_path(root))
770 for note in notes:
771 print(f" {note}")
772 for name in unrequired_allowances(root):
773 print(f" host-allowed: {name} is allowed and no site requires it yet")
774 for note in unreached_scopes(root, lock):
775 print(f" {note}")
776 return lock
777
778
779def unreached_scopes(root: Path, lock: Lock) -> list[str]:
780 """One line per scoped requirement no locked host matches, and so locks nothing."""
781 lines: list[str] = []
782 seen: set[str] = set()
783 for requirement in requirements(root):
784 if not requirement.hosts or requirement.name in lock.tools:
785 continue
786 spelled = str(requirement)
787 if spelled in seen or requirement.on(lock.hosts):787 ↛ 788line 787 didn't jump to line 788 because the condition on line 787 was never true
788 continue
789 seen.add(spelled)
790 lines.append(
791 f"{spelled} ({requirement.site}): no locked host is"
792 f" {', '.join(requirement.hosts)}; not locked"
793 )
794 return lines
795
796
797def resolve_graph(
798 root: Path,
799 name: str,
800 package: str,
801 version: str,
802 *,
803 kind: str,
804 runtime: str,
805) -> tuple[Graph | None, str]:
806 """Resolve *package* at *version* and write its graph; the graph or why not.
807
808 A `pypi` graph is uv's universal hashed requirements, resolved
809 against the workspace's Python floor, so one file covers every
810 interpreter the workspace supports. An `npm` graph is the
811 runtime's own lockfile, resolved without installing anything.
812 Neither runs unless what resolves it is here: a checkout that has
813 not materialised its tools yet locks the version and says the
814 graph waits.
815 """
816 from livery.strongroom import digest_of
817 from livery.toolroom.store import Graph
818
819 directory = graphs_dir(root)
820 directory.mkdir(parents=True, exist_ok=True)
821 target = directory / _graph_file(name, kind)
822 writer = _pypi_graph if kind == "pypi" else _npm_graph
823 by, why = writer(root, package, version, target, runtime=runtime)
824 if not by:
825 return None, why
826 return Graph(target.name, digest_of(target.read_bytes()), by=by), ""
827
828
829def _pypi_graph(
830 root: Path, package: str, version: str, target: Path, *, runtime: str
831) -> tuple[str, str]:
832 """Uv's universal hashed requirements for *package*; what resolved it."""
833 _ = runtime
834 import livery.toolroom.tools as toolroom
835 from livery.workshop._pythons import python_floor
836
837 with tempfile.TemporaryDirectory() as scratch:
838 wanted = Path(scratch) / "in.txt"
839 wanted.write_text(f"{package}=={version}\n", encoding="utf-8")
840 done = toolroom.uv.opts(nofail=True, recorded=False)(
841 "pip",
842 "compile",
843 "--generate-hashes",
844 "--universal",
845 "--quiet",
846 # The header names the command that wrote it, the output
847 # path included, and each annotation names the input file,
848 # whose directory is new on every run: either would make two
849 # resolutions of one version differ in bytes, and the lock
850 # would churn.
851 "--no-header",
852 "--no-annotate",
853 f"--python-version={python_floor(root)}",
854 f"--output-file={target}",
855 str(wanted),
856 )
857 if done.code != 0:857 ↛ 858line 857 didn't jump to line 858 because the condition on line 857 was never true
858 return "", f"uv could not resolve it (exit {done.code})"
859 return f"uv {_tool_version(root, 'uv')}", ""
860
861
862def _npm_graph(
863 root: Path, package: str, version: str, target: Path, *, runtime: str
864) -> tuple[str, str]:
865 """The runtime's own lockfile for *package*, resolved without installing."""
866 if runtime != "node":
867 return "", f"a graph of a {runtime} tool is not written yet"
868 held = tool_receipts(root).get("node")
869 if held is None:
870 return "", "node is not materialised here; the next lock writes it"
871 node = Path(held.tool_dir) / "bin" / exe("node")
872 if not node.is_file():
873 node = Path(held.tool_dir) / exe("node")
874 if not node.is_file():
875 return "", f"the node receipt names no executable under {held.tool_dir}"
876 from livery.toolroom.store import npm_cli
877
878 with tempfile.TemporaryDirectory() as scratch:
879 where = Path(scratch)
880 (where / "package.json").write_text(
881 json.dumps(
882 {
883 "name": "graph",
884 "version": "0.0.0",
885 "dependencies": {package: version},
886 }
887 )
888 + "\n",
889 encoding="utf-8",
890 )
891 done = run(
892 [
893 str(node),
894 str(npm_cli(node)),
895 "install",
896 "--package-lock-only",
897 "--no-audit",
898 "--no-fund",
899 ],
900 cwd=where,
901 nofail=True,
902 recorded=False,
903 capture=True,
904 )
905 written = where / "package-lock.json"
906 if done.code != 0 or not written.is_file():
907 return "", f"npm could not resolve it (exit {done.code})"
908 target.write_bytes(written.read_bytes())
909 return f"node {held.version}", ""
910
911
912def _tool_version(root: Path, name: str) -> str:
913 """The version the lock pins for *name*, or empty when it holds none."""
914 lock = current_lock(root)
915 held = lock.tools.get(name) if lock is not None else None
916 return held.version if held is not None else ""
917
918
919def exe(name: str) -> str:
920 """*name* as this platform spells an executable."""
921 return f"{name}.exe" if sys.platform == "win32" else name
922
923
924def _graph_path(root: Path, locked: Locked) -> Path | None:
925 """The graph file the lock names for this version, when it is here and whole.
926
927 A graph named but missing, or whose bytes are not the ones the
928 lock recorded, is not installed from: the tool installs the way
929 it did, and the next lock writes the graph again.
930 """
931 from livery.strongroom import digest_of
932
933 if locked.graph is None:
934 return None
935 path = graphs_dir(root) / locked.graph.file
936 if not path.is_file() or digest_of(path.read_bytes()) != locked.graph.digest:
937 return None
938 return path(empty)
939
940
941def graphs_dir(root: Path) -> Path:
942 """Where the resolved graphs live, beside the lock."""
943 from livery.toolroom.store import GRAPHS
944
945 return root / GRAPHS
946
947
948def _graph_file(name: str, kind: str) -> str:
949 """The graph's file name for *name*: the installer's own format."""
950 return f"{name}.txt" if kind == "pypi" else f"{name}.json"
951
952
953def _kept_graph(
954 root: Path, name: str, locked: Locked, kept: Lock | None
955) -> Graph | None:
956 """The graph the lock already had for this version, when it still stands.
957
958 A graph is resolved once, when a version enters the lock, and kept
959 after: a lock names artefacts and their hashes, so an install
960 re-runs no resolution and a newer installer installs the same
961 graph. A version that moved, a graph never written, and a file
962 edited or gone since are each resolved again.
963 """
964 from livery.strongroom import digest_of
965
966 before = kept.tools.get(name) if kept is not None else None
967 if before is None or before.version != locked.version or before.graph is None:
968 return None
969 path = graphs_dir(root) / before.graph.file
970 if not path.is_file() or digest_of(path.read_bytes()) != before.graph.digest:
971 return None
972 return before.graph
973
974
975def with_graphs(
976 root: Path,
977 lock: Lock,
978 listing: Catalogue,
979 *,
980 kept: Lock | None = None,
981 relock: tuple[str, ...] = (),
982) -> tuple[Lock, list[str]]:
983 """*lock* with a graph per delegated tool, and what to say about it.
984
985 A `pypi` tool's graph is uv's hashed requirements, a `npm` tool's
986 is its runtime's lockfile, each written under `GRAPHS` beside the
987 lock and named there by its digest; a `dotnet` tool has none, since
988 its package carries its dependencies and the version pins the
989 whole. A graph that cannot be
990 resolved now, the runtime it needs being absent on a checkout
991 that has not materialised yet, leaves the tool as it was: it
992 installs the way it did and says so, and the next lock writes it.
993
994 A tool named in *relock* is resolved again though its version
995 stands. Nothing here re-resolves on its own: a resolve is a fresh
996 answer from an index, so it moves the lock, and a lock moves when
997 a person says so, never as a side effect of installing.
998 """
999 from livery.toolroom.store import CatalogueError
1000
1001 directory = graphs_dir(root)
1002 tools: dict[str, Locked] = {}
1003 notes: list[str] = []
1004 wanted: set[str] = set()
1005 for name, locked in lock.tools.items():
1006 try:
1007 kind = listing.listed(name).kind
1008 except CatalogueError:
1009 tools[name] = locked
1010 continue
1011 if kind not in ("pypi", "npm"):
1012 tools[name] = locked
1013 continue
1014 standing = None if name in relock else _kept_graph(root, name, locked, kept)
1015 if standing is not None:
1016 wanted.add(standing.file)
1017 tools[name] = replace(locked, graph=standing)
1018 continue
1019 listed = listing.listed(name)
1020 graph, why = resolve_graph(
1021 root,
1022 name,
1023 listed.package or name,
1024 locked.version,
1025 kind=kind,
1026 runtime=runtime_of(listed),
1027 )
1028 if graph is None:
1029 notes.append(f"graphs: {name} {locked.version}: {why}")
1030 tools[name] = replace(locked, graph=None)
1031 continue
1032 wanted.add(graph.file)
1033 notes.append(f"graphs: {name} {locked.version} resolved by {graph.by}")
1034 tools[name] = replace(locked, graph=graph)
1035 if directory.is_dir():
1036 # A graph the lock no longer names is a file nothing installs
1037 # from: it goes with the tool or the version it belonged to.
1038 for stale in sorted(directory.iterdir()):
1039 if stale.is_file() and stale.name not in wanted:
1040 stale.unlink()
1041 notes.append(f"graphs: removed {stale.name}")
1042 return replace(lock, tools=tools), notes
1043
1044
1045def runtime_of(listed: Listed) -> str:
1046 """The runtime a tool runs on: an `npm` tool's record's, node unless it says bun.
1047
1048 A `dotnet` tool runs on dotnet, the SDK. Empty for every other
1049 kind, which runs on nothing the lock supplies.
1050 """
1051 if listed.kind == "npm":
1052 return listed.runtime or "node"
1053 if listed.kind == "dotnet":
1054 return "dotnet"
1055 return ""
1056
1057
1058def with_runtimes(
1059 found: tuple[Requirement, ...], listing: Catalogue
1060) -> tuple[Requirement, ...]:
1061 """*found*, plus each runtime a tool among them runs on and nothing names.
1062
1063 An `npm` or `dotnet` tool is installed through its runtime and
1064 runs on it, so the runtime is the tool's dependency and the lock
1065 holds it as such, on the hosts the tool is required on: the site
1066 named is the tool that needs it. A runtime some site requires on
1067 every host needs no more; otherwise one requirement per distinct
1068 scope is added, and the lock unions them. A requirement the
1069 catalogue does not list is left for the resolver to refuse by
1070 name.
1071 """
1072 from livery.toolroom.store import CatalogueError, Requirement
1073
1074 everywhere = {requirement.name for requirement in found if not requirement.hosts}
1075 present = {(requirement.name, requirement.hosts) for requirement in found}
1076 added: list[Requirement] = []
1077 for requirement in found:
1078 try:
1079 listed = listing.listed(requirement.name)
1080 except CatalogueError:
1081 continue
1082 runtime = runtime_of(listed)
1083 if (
1084 not runtime
1085 or runtime in everywhere
1086 or (runtime, requirement.hosts) in present
1087 ):
1088 continue
1089 present.add((runtime, requirement.hosts))
1090 added.append(
1091 Requirement(
1092 runtime,
1093 site=f"{requirement.name} ({listed.kind})",
1094 hosts=requirement.hosts,
1095 )
1096 )
1097 return (*found, *added)
1098
1099
1100def declare(root: Path, text: str) -> bool:
1101 """Add *text* to the project's `[toolroom] requires`; whether the contract changed.
1102
1103 A requirement already declared at the project site, in the same
1104 spelling, is left as it is. The contract is edited in place: the
1105 `[toolroom]` table gains the entry, or is added at the end with it.
1106 """
1107 from livery.toolroom.store import TABLE, LockError, Requirement
1108
1109 try:
1110 Requirement.parse(text, site="workshop.toml")
1111 except LockError as error:
1112 fail(str(error))
1113 path = root / "workshop.toml"
1114 declared = tools_table(path).get("requires", [])
1115 if isinstance(declared, list) and text in declared:
1116 return False
1117 source = path.read_text(encoding="utf-8") if path.is_file() else ""
1118 lines = source.split("\n")
1119 header = next(
1120 (n for n, line in enumerate(lines) if line.strip() == f"[{TABLE}]"), None
1121 )
1122 if header is None:
1123 trimmed = source.rstrip("\n")
1124 path.write_text(
1125 (trimmed + "\n\n" if trimmed else "")
1126 + f'[{TABLE}]\nrequires = ["{text}"]\n',
1127 encoding="utf-8",
1128 )
1129 return True
1130 end = next(
1131 (n for n in range(header + 1, len(lines)) if lines[n].startswith("[")),
1132 len(lines),
1133 )
1134 for n in range(header + 1, end):
1135 if lines[n].split("=", 1)[0].strip() == "requires":
1136 if lines[n].rstrip().endswith("]"):
1137 body = lines[n].split("=", 1)[1].strip()[1:-1].strip()
1138 items = f"{body}, " if body else ""
1139 lines[n] = f'requires = [{items}"{text}"]'
1140 else:
1141 close = next(m for m in range(n + 1, end) if lines[m].strip() == "]")
1142 lines.insert(close, f' "{text}",')
1143 path.write_text("\n".join(lines), encoding="utf-8")
1144 return True
1145 lines.insert(header + 1, f'requires = ["{text}"]')
1146 path.write_text("\n".join(lines), encoding="utf-8")
1147 return True
1148
1149
1150# --- receipts and materialisation -------------------------------------------------
1151
1152RECEIPTS = ".workshop/receipts"
1153"""Where a checkout keeps its receipts, one file per tool, gitignored."""
1154
1155BIN = ".workshop/bin"
1156"""The checkout's bin directory: the entry points of every tool in `link` mode."""
1157
1158RECEIPT_SCHEMA = 1
1159"""A receipt's shape. Bumped when a reader must know."""
1160
1161
1162@dataclass(frozen=True)
1163class ToolReceipt:
1164 """What this checkout installed of one tool, as its file records it.
1165
1166 `fm sync` writes one receipt per tool under the checkout's
1167 ``.workshop/receipts/``; [livery.workshop.tool_receipts][] reads
1168 them all.
1169
1170 Attributes:
1171 tool: The tool's name.
1172 version: The exact version installed, the lock's.
1173 host: The host key it was installed for, this machine's.
1174 kind: The installer kind.
1175 mode: How it reached PATH, one of
1176 [livery.toolroom.store.MODES][].
1177 deployment: The digest of the deployment installed; empty for a
1178 delegated kind, whose installer resolves the host.
1179 tool_dir: Where the tool is, under the machine's store home
1180 ([livery.workshop.store_home][]).
1181 paths: The absolute directories the tool puts on PATH in `path`
1182 mode; empty otherwise.
1183 env: The variables the tool sets, resolved against its directory.
1184 entry_points: The executables' names the tool puts on PATH:
1185 linked into the checkout's bin directory in `link` mode,
1186 found on `paths` in `path` mode; empty in `none` mode. A
1187 check resolves the tool by these, never by its name, since
1188 a name (`git_cliff`) is not always a binary (`git-cliff`).
1189 source: `store` for a tool the store supplied, `host` for a
1190 copy already on the machine that served under the
1191 allowance; `version` is the lock's either way, what the
1192 stubs render for and the drift check speaks of.
1193 answered: The version the host's copy printed when it served;
1194 empty for a store install.
1195 stamp: The host copy's identity when it served: its `path`,
1196 `size` and `mtime`, so a sync that finds the same file
1197 probes nothing; empty for a store install.
1198 """
1199
1200 tool: str
1201 version: str
1202 host: str
1203 kind: str
1204 mode: str
1205 deployment: str = ""
1206 tool_dir: str = ""
1207 paths: tuple[str, ...] = ()
1208 env: dict[str, str] = field(default_factory=dict)
1209 entry_points: tuple[str, ...] = ()
1210 source: str = "store"
1211 answered: str = ""
1212 stamp: dict[str, str] = field(default_factory=dict)
1213
1214 def to_json(self) -> dict[str, Any]:
1215 """The receipt as a JSON object."""
1216 return {
1217 "schema": RECEIPT_SCHEMA,
1218 "tool": self.tool,
1219 "version": self.version,
1220 "host": self.host,
1221 "kind": self.kind,
1222 "mode": self.mode,
1223 "deployment": self.deployment,
1224 "tool_dir": self.tool_dir,
1225 "paths": list(self.paths),
1226 "env": dict(self.env),
1227 "entry_points": list(self.entry_points),
1228 "source": self.source,
1229 "answered": self.answered,
1230 "stamp": dict(self.stamp),
1231 }
1232
1233 @classmethod
1234 def load(cls, path: Path) -> ToolReceipt:
1235 """The receipt at *path*.
1236
1237 Raises:
1238 ValueError: for a file that is not a receipt of this schema,
1239 naming the file.
1240 """
1241 try:
1242 data = json.loads(path.read_text(encoding="utf-8"))
1243 except (OSError, ValueError) as error:
1244 raise ValueError(f"{path}: not a receipt ({error})") from None
1245 if not isinstance(data, dict) or data.get("schema") != RECEIPT_SCHEMA:
1246 raise ValueError(f"{path}: not a receipt of schema {RECEIPT_SCHEMA}")
1247 try:
1248 return cls(
1249 str(data["tool"]),
1250 str(data["version"]),
1251 str(data["host"]),
1252 str(data["kind"]),
1253 str(data["mode"]),
1254 str(data.get("deployment", "")),
1255 str(data.get("tool_dir", "")),
1256 tuple(str(p) for p in data.get("paths", [])),
1257 {str(k): str(v) for k, v in data.get("env", {}).items()},
1258 tuple(str(e) for e in data.get("entry_points", [])),
1259 str(data.get("source", "store")),
1260 str(data.get("answered", "")),
1261 {str(k): str(v) for k, v in data.get("stamp", {}).items()},
1262 )
1263 except (KeyError, TypeError, AttributeError) as error:
1264 raise ValueError(f"{path}: not a receipt ({error})") from None
1265
1266
1267def _runtimes_first(
1268 wanted: tuple[str, ...], lock: Lock, listing: Catalogue
1269) -> tuple[str, ...]:
1270 """*wanted* with each runtime ahead of the tools that run on it.
1271
1272 An `npm` tool is installed through its runtime's executable, so the
1273 runtime is supplied first and its path handed on; a runtime the
1274 lock holds joins a narrowed *wanted* that names such a tool without
1275 it.
1276 """
1277 needed: list[str] = []
1278 for name in wanted:
1279 runtime = runtime_of(listing.listed(name))
1280 if runtime and runtime not in needed:
1281 needed.append(runtime)
1282 if not needed:
1283 return wanted
1284 rest = tuple(name for name in wanted if name not in needed)
1285 return (*(runtime for runtime in needed if runtime in lock.tools), *rest)
1286
1287
1288def receipts_dir(root: Path) -> Path:
1289 """The checkout's receipts directory."""
1290 return root / RECEIPTS
1291
1292
1293def bin_dir(root: Path) -> Path:
1294 """The checkout's bin directory."""
1295 return root / BIN
1296
1297
1298def tool_receipts(root: Path) -> dict[str, ToolReceipt]:
1299 """What the checkout at *root* installed of each tool, by the tool's name.
1300
1301 The receipts the last sync wrote, each a
1302 [livery.workshop.ToolReceipt][]: a receipt names the version the
1303 lock pins and where the tool is on this machine. Empty for a
1304 checkout no sync has supplied.
1305
1306 Raises:
1307 ValueError: for a file under the receipts directory that is not
1308 a receipt, naming it.
1309 """
1310 directory = receipts_dir(root)
1311 if not directory.is_dir():
1312 return {}
1313 found = {}
1314 for path in sorted(directory.glob("*.json")):
1315 receipt = ToolReceipt.load(path)
1316 found[receipt.tool] = receipt
1317 return found
1318
1319
1320def mode_of(
1321 root: Path, name: str, kind: str, declared: str = "", *, paths: tuple[str, ...] = ()
1322) -> str:
1323 """The mode *name* materialises in: the project's say, the record's, the kind's.
1324
1325 *paths* are the deployment's, which decide a download's default.
1326 Raises a refusal naming the override when it is not one of `MODES`.
1327 """
1328 from livery.toolroom.store import MODES, default_mode
1329
1330 overrides = cast(
1331 "dict[str, str]", tools_table(root / "workshop.toml").get("modes", {})
1332 )
1333 chosen = overrides.get(name, declared) or default_mode(kind, paths)
1334 if chosen not in MODES:1334 ↛ 1335line 1334 didn't jump to line 1335 because the condition on line 1334 was never true
1335 fail(
1336 f"workshop.toml: [toolroom] modes names {chosen!r} for {name}; the modes"
1337 f" are {', '.join(MODES)}"
1338 )
1339 return str(chosen)
1340
1341
1342def sources(root: Path) -> tuple[Source, ...]:
1343 """The tiers consulted before an origin, `[toolroom] sources`: folders or URLs."""
1344 from livery.strongroom import FolderSource, HttpSource
1345
1346 declared = cast("list[str]", tools_table(root / "workshop.toml").get("sources", []))
1347 found: list[Source] = []
1348 for entry in declared:
1349 if "://" in entry:1349 ↛ 1350line 1349 didn't jump to line 1350 because the condition on line 1349 was never true
1350 found.append(HttpSource(entry))
1351 else:
1352 found.append(FolderSource(root / entry))
1353 return tuple(found)
1354
1355
1356@dataclass(frozen=True)
1357class Materialised:
1358 """What one materialisation did to one tool.
1359
1360 Attributes:
1361 receipt: The receipt written, or `None` when the tool could not
1362 be supplied and *strict* was off.
1363 installed: Whether the store installed it on this call.
1364 failure: Why the tool could not be supplied; empty when it was.
1365 note: What the sync should say beyond the receipt: why a host
1366 copy was passed over for the store's version; empty
1367 otherwise.
1368 """
1369
1370 receipt: ToolReceipt | None
1371 installed: bool
1372 failure: str = ""
1373 note: str = ""
1374
1375
1376def _stamp(found: Path) -> dict[str, str]:
1377 """The identity of *found* a later sync compares before probing; empty when gone."""
1378 try:
1379 stat = found.stat()
1380 except OSError:
1381 return {}
1382 return {
1383 "path": str(found),
1384 "size": str(stat.st_size),
1385 "mtime": str(stat.st_mtime_ns),
1386 }
1387
1388
1389def _fresh_host_receipt(root: Path, name: str) -> ToolReceipt | None:
1390 """*name*'s receipt when a host copy served and the same file is still there."""
1391 path = receipts_dir(root) / f"{name}.json"
1392 if not path.is_file():
1393 return None
1394 try:
1395 receipt = ToolReceipt.load(path)
1396 except ValueError:
1397 return None
1398 if receipt.source != "host" or not receipt.stamp.get("path"):
1399 return None
1400 if _stamp(Path(receipt.stamp["path"])) != receipt.stamp:
1401 return None
1402 return receipt
1403
1404
1405def site_floors(root: Path) -> dict[str, tuple[str, str]]:
1406 """The highest floor the sites declare per tool, with the site that asked.
1407
1408 A tool no site floors is absent. The lock already honours these
1409 floors when it chooses a version; the check of a system tool on a
1410 machine honours them here, since the machine's own copy is never
1411 the locked version.
1412 """
1413 from livery.toolroom.store import version_key
1414
1415 highest: dict[str, tuple[str, str]] = {}
1416 for requirement in requirements(root):
1417 if not requirement.floor:
1418 continue
1419 held = highest.get(requirement.name)
1420 if held is None or version_key(requirement.floor) > version_key(held[0]):1420 ↛ 1416line 1420 didn't jump to line 1416 because the condition on line 1420 was always true
1421 highest[requirement.name] = (requirement.floor, requirement.site)
1422 return highest
1423
1424
1425def materialise(
1426 root: Path,
1427 names: tuple[str, ...] = (),
1428 *,
1429 offline: bool = False,
1430 strict: bool = True,
1431) -> tuple[Materialised, ...]:
1432 """Supply every locked tool, or *names* alone, and write their receipts.
1433
1434 The bundle is what the sites require: every tool the lock holds
1435 for this host; one locked for other hosts alone is skipped, and
1436 named it refuses. A downloaded kind is supplied from the
1437 catalogue's deployment for
1438 this host through the store's sources and the origin; a delegated
1439 kind through its installer. A system tool is the machine's own,
1440 held to the highest of the record's floor and the sites' floors;
1441 the refusal names the site whose floor it is under. A tool the
1442 lock marks `allow-host` is looked for on PATH first: a copy that
1443 satisfies the floor serves, its receipt saying `host` and the
1444 version that answered, and the store installs nothing for it; a
1445 copy that is absent or below the floor is passed over with a
1446 note, and the locked version is supplied as for any other tool. A
1447 host receipt whose file is unchanged since it was written is
1448 reused without a probe. Tools in
1449 `link` mode are linked into the checkout's bin directory together,
1450 so a name two tools offer goes to the first. A receipt is written
1451 per tool supplied, and on a materialise of the whole bundle the
1452 receipt of a tool the lock no longer holds is removed, so its
1453 paths leave the environment with it.
1454
1455 Raises a refusal naming the tool when the lock does not hold it.
1456 A tool the store cannot supply refuses too, naming the reason,
1457 unless *strict* is off: then it is reported in its outcome and the
1458 others are supplied, which is what `sync` wants, since one tool's
1459 origin being unreachable must not stop the environment from
1460 entering. A tool the lock marks optional is reported and never
1461 refused, strict or not: the verbs that need it name its absence
1462 when they run.
1463 """
1464 from livery.toolroom.store import (
1465 DOWNLOAD_KINDS,
1466 LOCK_FILE,
1467 RUNTIMES,
1468 CatalogueError,
1469 Store,
1470 StoreError,
1471 SupplyRequest,
1472 version_key,
1473 )
1474
1475 lock = current_lock(root)
1476 if lock is None:
1477 fail(f"no {LOCK_FILE}: lock the tools first with `{prog()} toolroom.lock`")
1478 listing = catalogue(root, offline=offline)
1479 store = Store(_home(), sources=sources(root), offline=offline)
1480 host = store.host
1481 supported = supported_hosts(root)
1482 if host not in supported:
1483 # A runner's label is free text on every forge, so the host
1484 # itself is where an unsupported runner can be told apart.
1485 reason = (
1486 f"this host ({host}) is not one the workspace supports;"
1487 f" [workspace] hosts supports {', '.join(supported)}"
1488 )
1489 if strict or os.environ.get("CI"):
1490 fail(reason)
1491 print(f" {reason}")
1492 here = lock.on_host(host)
1493 wanted = names or here
1494 if not names:
1495 for name, entry in sorted(lock.tools.items()):
1496 if entry.optional and name not in here:1496 ↛ 1497line 1496 didn't jump to line 1497 because the condition on line 1496 was never true
1497 print(
1498 f" {name}: optional, and not locked for this host ({host});"
1499 " the verbs that need it say so"
1500 )
1501 for name in wanted:
1502 if name not in lock.tools:
1503 fail(
1504 f"{name} is not in {LOCK_FILE}; the lock holds"
1505 f" {', '.join(sorted(lock.tools)) or 'nothing'}"
1506 )
1507 if name not in here:
1508 fail(
1509 f"{name} is locked for {', '.join(lock.tools[name].on)} and not"
1510 f" for this host ({host}); the sites require it there alone"
1511 )
1512 floors = site_floors(root)
1513 done_by_name: dict[str, Materialised] = {}
1514 linked: list[tuple[ToolReceipt, Ensured]] = []
1515 wanted = _runtimes_first(wanted, lock, listing)
1516 runtimes: dict[str, Path] = {}
1517 requests: list[SupplyRequest] = []
1518 pending_meta: dict[str, tuple[str, str, Deployment | None, str]] = {}
1519 for name in wanted:
1520 locked = lock.tools[name]
1521 listed = listing.listed(name)
1522 floor, site = listed.min_version, ""
1523 asked = floors.get(name) if listed.kind == "system-check" else None
1524 if asked is not None and (
1525 not floor or version_key(asked[0]) > version_key(floor)
1526 ):
1527 floor, site = asked
1528 note = ""
1529 if locked.allow_host:
1530 fresh = _fresh_host_receipt(root, name)
1531 if fresh is not None:
1532 if name in RUNTIMES:1532 ↛ 1533line 1532 didn't jump to line 1533 because the condition on line 1532 was never true
1533 runtimes[name] = Path(fresh.stamp["path"])
1534 done_by_name[name] = Materialised(fresh, False)
1535 continue
1536 asked = floors.get(name)
1537 host_floor = asked[0] if asked is not None else listed.min_version
1538 try:
1539 served = store.supply(
1540 name, "system-check", locked.version, None, min_version=host_floor
1541 )
1542 except StoreError as error:
1543 note = f"{error}; the store's {locked.version} serves"
1544 else:
1545 found = served.tool_dir / exe(name)
1546 if name in RUNTIMES:1546 ↛ 1547line 1546 didn't jump to line 1547 because the condition on line 1546 was never true
1547 runtimes[name] = found
1548 receipt = ToolReceipt(
1549 name,
1550 locked.version,
1551 host,
1552 listed.kind,
1553 "none",
1554 tool_dir=str(served.tool_dir),
1555 source="host",
1556 answered=served.answered,
1557 stamp=_stamp(found),
1558 )
1559 done_by_name[name] = Materialised(receipt, False)
1560 continue
1561 deployment: Deployment | None = None
1562 if listed.kind in DOWNLOAD_KINDS:
1563 try:
1564 deployment = listing.deployment(name, locked.version, host)
1565 except CatalogueError as error:
1566 # A host outside the lock's set, or one the version has
1567 # no build for: the tool is reported and the others are
1568 # supplied, as any tool the store cannot supply is.
1569 reason = f"{name} {locked.version}: not locked for {host}: {error}"
1570 if strict and not locked.optional:
1571 fail(reason)
1572 done_by_name[name] = Materialised(None, False, reason)
1573 continue
1574 pending_meta[name] = (floor, site, deployment, note)
1575 requests.append(
1576 SupplyRequest(
1577 name,
1578 listed.kind,
1579 locked.version,
1580 deployment,
1581 package=listed.package,
1582 min_version=floor,
1583 runtime=listed.runtime,
1584 runtime_exe=runtimes.get(runtime_of(listed)),
1585 graph=_graph_path(root, locked),
1586 )
1587 )
1588 supplied = {result.name: result for result in store.supply_many(requests)}
1589 done: list[Materialised] = []
1590 for name in wanted:
1591 already = done_by_name.get(name)
1592 if already is not None:
1593 done.append(already)
1594 continue
1595 locked = lock.tools[name]
1596 listed = listing.listed(name)
1597 floor, site, deployment, note = pending_meta[name]
1598 outcome = supplied[name]
1599 if outcome.ensured is None:
1600 reason = outcome.error
1601 if site and "below the floor" in reason:
1602 reason += f"; {site} requires {name}>={floor}"
1603 # An optional tool the host cannot supply is named, never
1604 # refused: the verbs that need it say so when they run.
1605 if strict and not locked.optional:
1606 fail(reason)
1607 done.append(Materialised(None, False, reason))
1608 continue
1609 ensured = outcome.ensured
1610 mode = mode_of(
1611 root,
1612 name,
1613 listed.kind,
1614 listed.mode,
1615 paths=deployment.paths if deployment is not None else (),
1616 )
1617 receipt = ToolReceipt(
1618 name,
1619 locked.version,
1620 host,
1621 listed.kind,
1622 mode,
1623 str(deployment.digest()) if deployment is not None else "",
1624 str(ensured.tool_dir),
1625 tuple(str(p) for p in ensured.paths) if mode == "path" else (),
1626 ensured.env,
1627 tuple(Path(e).name for e in ensured.deployment.entry_points)
1628 if mode in ("link", "path")
1629 else (),
1630 )
1631 if mode == "link":
1632 linked.append((receipt, ensured))
1633 done.append(Materialised(receipt, ensured.installed, note=note))
1634 if linked or bin_dir(root).is_dir():
1635 store.link([ensured for _, ensured in linked], bin_dir(root))
1636 receipts_dir(root).mkdir(parents=True, exist_ok=True)
1637 for made in done:
1638 if made.receipt is None:
1639 continue
1640 path = receipts_dir(root) / f"{made.receipt.tool}.json"
1641 path.write_text(
1642 json.dumps(made.receipt.to_json(), indent=2) + "\n", encoding="utf-8"
1643 )
1644 if not names:
1645 # A tool that left the lock, or is locked for other hosts
1646 # alone, leaves the environment: a receipt kept past its tool
1647 # would keep the tool's directory on PATH ahead of whatever
1648 # replaced it.
1649 for stale in receipts_dir(root).glob("*.json"):
1650 if stale.stem not in here:
1651 stale.unlink()
1652 return tuple(done)
1653
1654
1655def typings_dir(root: Path) -> Path:
1656 """The typings directory the stubs are written under."""
1657 return root / TYPINGS
1658
1659
1660def stubs_dir(root: Path) -> Path:
1661 """The `stubs` package under the typings directory's `livery.toolroom`."""
1662 return typings_dir(root).joinpath(*TYPINGS_PACKAGE) / "stubs"
1663
1664
1665def stubs_present(root: Path) -> int:
1666 """How many tool stubs the typings directory holds."""
1667 return sum(1 for p in stubs_dir(root).glob("*.pyi") if p.stem != "__init__")
1668
1669
1670@dataclass(frozen=True)
1671class Stubbed:
1672 """What `write_stubs` did.
1673
1674 Attributes:
1675 written: The tools whose stub changed on disk, or was new.
1676 kept: The tools whose stub was already what the catalogue holds.
1677 skipped: Per tool the catalogue lists and no stub was written
1678 for, why.
1679 removed: Stubs of tools the catalogue no longer lists.
1680 """
1681
1682 written: tuple[str, ...]
1683 kept: tuple[str, ...]
1684 skipped: dict[str, str]
1685 removed: tuple[str, ...]
1686
1687
1688def _no_command(listing: Catalogue, name: str, version: str) -> bool:
1689 """Whether *name* is a download with no entry point: no command, so no stub."""
1690 import platform
1691
1692 from livery.toolroom.store import CatalogueError, RecordError, host_key
1693
1694 if listing.listed(name).kind != "download":
1695 return False
1696 try:
1697 deployment = listing.deployment(
1698 name, version, host_key(platform.system(), platform.machine())
1699 )
1700 except (CatalogueError, RecordError):
1701 return False
1702 return not deployment.entry_points
1703
1704
1705def write_stubs(root: Path, *, offline: bool = False) -> Stubbed:
1706 """Write the stubs of the locked tools into the typings directory.
1707
1708 One stub per tool `toolroom.lock` holds, rendered by the store from the
1709 locked version's own surface, from the records or from the index:
1710 a tool the workspace does not deploy gets no stub, and its handle
1711 types as a bare `Tool`. The `handles` module beside the stubs
1712 declares the handles, one import and one `name: Class[Result]` per
1713 stub written, and the installed tools package's index imports every
1714 name from it. The handles cannot live in the stubs package's own
1715 index: a package's index binds its submodules, and `uv` would name
1716 `uv.pyi` rather than the handle. Nothing is written inside the
1717 tools package's own directory, and a tree left there is removed:
1718 it shadows the package for a checker run on explicit paths. Without
1719 a lock nothing is written.
1720
1721 A receipt under `.workshop/state/` names the lock and the source
1722 the last write rendered from, a records directory by its stat
1723 fingerprint and an index by its pointer. When both stand and every file it
1724 wrote is there, nothing is read and nothing is written, which is
1725 the steady state of every sync; otherwise a stub already on disk
1726 as the source renders it is kept, so a checker's cache stands.
1727 """
1728 from livery.toolroom.store import CatalogueError
1729
1730 source = index_source(root)
1731 local = _local_records(root, source)
1732 lock = current_lock(root)
1733 locked = dict(lock.tools) if lock is not None else {}
1734 shutil.rmtree(
1735 typings_dir(root).joinpath(*TYPINGS_PACKAGE, "tools"), ignore_errors=True
1736 )
1737 directory = stubs_dir(root)
1738 directory.mkdir(parents=True, exist_ok=True)
1739 seen = None
1740 if locked:
1741 try:
1742 seen = source_mark(source)
1743 if local is not None:
1744 seen = f"{seen}+{source_mark(str(local))}"
1745 except CatalogueError as error:
1746 fail(str(error))
1747 standing = _stubs_standing(root, seen, sorted(locked))
1748 if standing is not None:
1749 return standing
1750 listing = catalogue(root, offline=offline) if locked else None
1751 written: list[str] = []
1752 kept: list[str] = []
1753 skipped: dict[str, str] = {}
1754 declared: list[str] = []
1755 for name in sorted(locked):
1756 version = locked[name].version
1757 assert listing is not None
1758 if _no_command(listing, name, version):
1759 continue(empty)
1760 try:
1761 text = listing.stub(name, version)
1762 except CatalogueError as error:
1763 # A tool/version genuinely never observed has no underlying
1764 # cause and is skipped; an unreadable object in the index
1765 # (missing blob/tree, transport error) fails closed rather
1766 # than silently falling back to a bare stub and writing a
1767 # standing receipt.
1768 if error.__cause__ is not None:
1769 fail(str(error))
1770 skipped[name] = str(error)
1771 continue
1772 path = directory / f"{name}.pyi"
1773 if path.is_file() and path.read_text(encoding="utf-8") == text:
1774 kept.append(name)
1775 else:
1776 path.write_text(text, encoding="utf-8")
1777 written.append(name)
1778 declared.append(name)
1779 removed: list[str] = []
1780 for stale in sorted(directory.glob("*.pyi")):
1781 if stale.stem != "__init__" and stale.stem not in declared:
1782 stale.unlink()
1783 removed.append(stale.stem)
1784 _write_if_changed(directory / "__init__.pyi", "")
1785 _write_if_changed(handles_path(root), handles_index(declared))
1786 if seen is not None:
1787 _write_stubs_receipt(root, seen, sorted(locked), declared)
1788 return Stubbed(tuple(written), tuple(kept), skipped, tuple(removed))
1789
1790
1791def source_mark(source: str) -> str:
1792 """What the catalogue source is right now, in one digest, without reading it whole.
1793
1794 A directory of records is its stat fingerprint; an index, by
1795 directory or URL, is the digest of its pointer document.
1796 """
1797 from livery.strongroom import canonical, digest_of
1798 from livery.toolroom.store import is_records, read_pointer, tree_fingerprint
1799
1800 if is_records(source):
1801 return tree_fingerprint([source])
1802 return str(digest_of(canonical(read_pointer(source))))
1803
1804
1805STUBS_RECEIPT = ".workshop/state/stubs.json"
1806"""The receipt naming the lock and the source the last stub write rendered from.
1807
1808Under `state/` rather than `receipts/`: that directory is the tool
1809receipts, which `tool_receipts()` reads as a set and refuses a file of
1810another shape in. Each kind of thing under `.workshop/` keeps its own
1811directory, so no walk of one kind can reach another.
1812"""
1813
1814
1815def _stubs_receipt_path(root: Path) -> Path:
1816 return root / STUBS_RECEIPT
1817
1818
1819def _lock_digest(root: Path) -> str:
1820 return "sha256:" + hashlib.sha256(lock_path(root).read_bytes()).hexdigest()
1821
1822
1823def _stubs_standing(root: Path, stubs: str, locked: list[str]) -> Stubbed | None:
1824 """The last write's answer when the lock, the source and the files stand."""
1825 try:
1826 held = json.loads(_stubs_receipt_path(root).read_text(encoding="utf-8"))
1827 except (OSError, ValueError):
1828 return None
1829 if not isinstance(held, dict) or held.get("schema") != 1:1829 ↛ 1830line 1829 didn't jump to line 1830 because the condition on line 1829 was never true
1830 return None
1831 if held.get("source") != stubs or held.get("lock") != _lock_digest(root):
1832 return None
1833 if held.get("locked") != locked:1833 ↛ 1834line 1833 didn't jump to line 1834 because the condition on line 1833 was never true
1834 return None
1835 written = held.get("written")
1836 if not isinstance(written, list) or not all(isinstance(n, str) for n in written):1836 ↛ 1837line 1836 didn't jump to line 1837 because the condition on line 1836 was never true
1837 return None
1838 # A locked tool with no stub is named on every write, so a write that
1839 # skipped one is never answered from the receipt.
1840 if written != locked:
1841 return None
1842 present = {p.stem for p in stubs_dir(root).glob("*.pyi")} - {"__init__"}
1843 if present != set(written) or not handles_path(root).is_file():
1844 return None
1845 return Stubbed((), tuple(written), {}, ())
1846
1847
1848def _write_stubs_receipt(
1849 root: Path, stubs: str, locked: list[str], written: list[str]
1850) -> None:
1851 path = _stubs_receipt_path(root)
1852 path.parent.mkdir(parents=True, exist_ok=True)
1853 document = {
1854 "schema": 1,
1855 "source": stubs,
1856 "lock": _lock_digest(root),
1857 "locked": locked,
1858 "written": written,
1859 }
1860 path.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8")
1861
1862
1863def handles_path(root: Path) -> Path:
1864 """The `handles.pyi` module beside the stubs, declaring the typed handles."""
1865 return typings_dir(root).joinpath(*TYPINGS_PACKAGE) / "handles.pyi"
1866
1867
1868def handles_index(names: list[str]) -> str:
1869 """The `handles` module declaring the handles of *names*, in order.
1870
1871 The installed tools package's own index imports every name from
1872 this module, so the handle `uv` types as `Uv[Result]` exactly
1873 when `stubs/uv.pyi` is beside it.
1874 """
1875 from livery.toolroom.store import class_name
1876
1877 lines = [
1878 f"# Rendered by `{prog()} toolroom.restub`: the handles this workspace",
1879 "# locks. Do not edit by hand.",
1880 "from livery.toolroom.tools import Result",
1881 ]
1882 lines += [
1883 f"from livery.toolroom.stubs.{name} import"
1884 f" {class_name(name)} as {class_name(name)}"
1885 for name in names
1886 ]
1887 lines.append("")
1888 lines += [f"{name}: {class_name(name)}[Result]" for name in names]
1889 return "\n".join(lines) + "\n"
1890
1891
1892def _write_if_changed(path: Path, text: str) -> None:
1893 if path.is_file() and path.read_text(encoding="utf-8") == text:
1894 return
1895 path.write_text(text, encoding="utf-8")
1896
1897
1898def stub_lines(root: Path, *, offline: bool = False, strict: bool = True) -> list[str]:
1899 """Write the stubs and say what happened, as `sync` and the lock verbs print it.
1900
1901 A refusal is raised when *strict*; otherwise it is the one line
1902 returned, naming the reason, since a lock written or a bundle
1903 materialised stands whether or not the stubs could follow.
1904 """
1905 if strict:
1906 made = write_stubs(root, offline=offline)
1907 else:
1908 try:
1909 made = write_stubs(root, offline=offline)
1910 except Failed as refusal:
1911 return [f" stubs: not written: {refusal}"]
1912 held = len(made.written) + len(made.kept)
1913 line = f" stubs: {held} in {TYPINGS}/"
1914 if made.written:
1915 line += f", wrote {len(made.written)}"
1916 if made.removed:1916 ↛ 1917line 1916 didn't jump to line 1917 because the condition on line 1916 was never true
1917 line += f", removed {', '.join(made.removed)}"
1918 lines = [line]
1919 lines += [f" stubs: {name}: {why}" for name, why in made.skipped.items()]
1920 return lines
1921
1922
1923def emission(root: Path) -> tuple[tuple[str, ...], dict[str, str]]:
1924 """What the receipts add to an entered shell: PATH entries and variables.
1925
1926 The checkout's bin directory first when any receipt links into it,
1927 then each `path` receipt's directories in tool order, then the
1928 variables, a later receipt's value winning.
1929 """
1930 held = tool_receipts(root)
1931 paths: list[str] = []
1932 env: dict[str, str] = {}
1933 if any(r.mode == "link" for r in held.values()):
1934 paths.append(str(bin_dir(root)))
1935 for receipt in held.values():
1936 for entry in receipt.paths:
1937 if entry not in paths:1937 ↛ 1936line 1937 didn't jump to line 1936 because the condition on line 1937 was always true
1938 paths.append(entry)
1939 env.update(receipt.env)
1940 return tuple(paths), env
1941
1942
1943def drift(root: Path) -> dict[str, str]:
1944 """Per tool the sites require, what `fm env.check` says of its receipt.
1945
1946 An empty string is a tool whose receipt matches the lock; anything
1947 else names the problem: no receipt, a receipt at another version
1948 than the lock, or a deployment the lock has moved under it.
1949 """
1950 lock = current_lock(root)
1951 held = tool_receipts(root)
1952 found: dict[str, str] = {}
1953 for name in tool_names(root, this_host()):
1954 if lock is None or name not in lock.tools:
1955 found[name] = f"not locked; run `{prog()} toolroom.lock`"
1956 continue
1957 locked = lock.tools[name]
1958 receipt = held.get(name)
1959 if receipt is None:
1960 found[name] = (
1961 f"no receipt for {locked.version}; run `{prog()} sync` to materialise"
1962 )
1963 continue
1964 if receipt.version != locked.version:
1965 found[name] = (
1966 f"receipt {receipt.version}, lock {locked.version}; run `{prog()} sync`"
1967 )
1968 continue
1969 expected = locked.hosts.get(receipt.host)
1970 if receipt.source == "host":
1971 continue
1972 if expected is not None and str(expected) != receipt.deployment:
1973 found[name] = (
1974 f"DRIFT: the deployment of {locked.version} on {receipt.host} moved"
1975 f" under the receipt ({receipt.deployment[:19]}... is now"
1976 f" {str(expected)[:19]}...); run `{prog()} sync`"
1977 )
1978 continue
1979 found[name] = ""
1980 return found
1981
1982
1983def undeployed(name: str) -> NoReturn:
1984 """Refuse the task: *name* is a tool of the store and is not on ``PATH``.
1985
1986 Call it where a step spawns a tool of the store and the spawn
1987 raises ``OSError``, or where ``shutil.which`` finds nothing for a
1988 tool the step spawns by its path. A toolroom handle spawns its tool
1989 by name from ``PATH``, and the store's tools are on ``PATH`` only
1990 after the machine has deployed them and the shell has entered the
1991 environment. A traceback from the spawn names nothing a person can
1992 act on. This refusal names the tool and the next action: run
1993 ``fm sync``, then the ``env.emit`` line it prints, then run the task
1994 again.
1995
1996 It never returns.
1997
1998 Args:
1999 name: The tool's name, as its handle spawns it.
2000
2001 Raises:
2002 Failed: always, naming *name* and the sync that deploys it.
2003 """
2004 fail(
2005 f"{name} is not on PATH: it is a tool of the store, so enter the"
2006 f" environment (`{prog()} sync`, then the printed"
2007 " env.emit line) and re-run"
2008 )