1"""The workshop's doctors, registered under footman's ``footman.doctors`` group.
3Four: the forge doctor, which reaches the forge and says who you are
4there, which server it is, what it grants, whether every declared owner
5exists and which admin token ladder is set; the host doctor, which
6reads the machine, the compilers the workspace's packages need, the
7tools the host serves, the listed extensions that are dormant, and the
8installed extensions the contract does not list; the uv cache doctor,
9which measures uv's cache against the workspace's limit; and the ssh
10doctor, which says whether the git plugin shares one connection per
11host and names a `ControlMaster` entry of the person's own. Each
12returns findings ([livery.footman.Finding][]). Only the finding of a
13cache over its limit carries a repair, the prune `fm doctor --fix`
14runs; every other fix is a person's. `fm doctor` prints them,
15footman's own first.
16"""
18from __future__ import annotations
20import os
21import re
22from pathlib import Path
23from typing import Any
25from livery.footman import Finding
26from livery.forge import Capability, Forge
27from livery.workshop._contract import load_contract
28from livery.workshop._extensions import workspace_root
30#: The forge capabilities the workshop can use; the doctor says which are granted.
31CAPABILITIES: tuple[Capability, ...] = (
32 "auto_merge",
33 "force_cancel",
34 "required_contexts",
35 "ci_secrets",
36 "schedule_events",
37)
40def forge_findings(forge: Forge, root: Path | None) -> list[Finding]:
41 """The forge doctor's findings for *forge*; *root*'s contract is read when given."""
42 findings: list[Finding] = []
43 if root is not None:
44 from livery.workshop._governance import unknown_owners
45 from livery.workshop._tokens import admin_token
47 contract = load_contract(root / "workshop.toml")
48 owner = str((contract.get("forge") or {}).get("owner", ""))
49 kind = str((contract.get("forge") or {}).get("kind", ""))
50 url = str((contract.get("forge") or {}).get("url", ""))
51 _, admin_var = admin_token(kind, url)
52 if admin_var.startswith("FORGE_ADMIN_TOKEN"):
53 findings.append(Finding(f"admin ladder: {admin_var} set"))
54 elif admin_var:54 ↛ 55line 54 didn't jump to line 55 because the condition on line 54 was never true
55 findings.append(
56 Finding(
57 "admin ladder: FORGE_ADMIN_TOKEN unset"
58 f" ({admin_var} is the fallback)"
59 )
60 )
61 else:
62 findings.append(
63 Finding(
64 "admin ladder: FORGE_ADMIN_TOKEN unset"
65 " (everyday token is the fallback)"
66 )
67 )
68 try:
69 unknown = unknown_owners(root, forge, owner)
70 except Exception as error:
71 findings.append(Finding(f"owners: not checked ({error})"))
72 else:
73 for entry in unknown:
74 findings.append(
75 Finding(
76 "owners",
77 f"unknown {entry}",
78 "add the user or team on the forge, or drop it from the"
79 " contract's owners",
80 )
81 )
82 if not unknown:
83 findings.append(
84 Finding("owners: every declared owner exists on the forge")
85 )
86 findings.append(Finding(f"{forge.whoami()} on {forge.server_version()}"))
87 granted = [name for name in CAPABILITIES if forge.supports(name)]
88 missing = [name for name in CAPABILITIES if name not in granted]
89 if granted:89 ↛ 91line 89 didn't jump to line 91 because the condition on line 89 was always true
90 findings.append(Finding(f"grants: {', '.join(granted)}"))
92 findings.append(
93 Finding(
94 "grants",
95 f"missing: {', '.join(missing)}",
96 "a token or a plan that grants them; the workshop works around"
97 " each one it lacks",
98 )
99 )
100 else:
101 findings.append(Finding("every capability the workshop can use is granted"))
102 return findings
105def forge(**facts: Any) -> list[Finding]:
106 """The forge doctor: who you are on the forge, what it is, what it grants."""
107 from livery.workshop._forge_lane import this_forge
109 root = workspace_root()
110 if root is None:110 ↛ 111line 110 didn't jump to line 111 because the condition on line 110 was never true
111 return [Finding("forge: no workspace here, not checked")]
112 return forge_findings(this_forge(root), root)
115def host(**facts: Any) -> list[Finding]:
116 """The host doctor: compilers, the host's tools, dormant and unlisted extensions."""
117 from livery.workshop._env_tasks import missing_host_tools, served_by
118 from livery.workshop._extensions import (
119 available_extensions,
120 composes_per_package,
121 dormancy,
122 extension_names,
123 )
124 from livery.workshop._tools import tool_receipts
126 root = workspace_root()
127 if root is None:127 ↛ 128line 127 didn't jump to line 128 because the condition on line 127 was never true
128 return [Finding("host: no workspace here, not checked")]
129 findings: list[Finding] = []
130 missing = list(missing_host_tools(root))
131 for tool in missing:
132 findings.append(
133 Finding(
134 f"host: {tool}",
135 "MISSING, a compiler the workspace's packages need",
136 "install the platform toolchain",
137 )
138 )
139 if not missing:
140 findings.append(
141 Finding("host: every compiler the workspace's packages need is present")
142 )
143 hosted = [
144 f"{name} ({served_by(receipt)})"
145 for name, receipt in sorted(tool_receipts(root).items())
146 if receipt.source == "host"
147 ]
148 if hosted:148 ↛ 149line 148 didn't jump to line 149 because the condition on line 148 was never true
149 findings.append(Finding(f"tools: served by the host: {', '.join(hosted)}"))
150 for name, waits in dormancy(root).items():
151 # Information, not a fault: a listing kept for a contributor
152 # still to come is a statement of intent.
153 findings.append(Finding(f"extensions: {name}: dormant, {waits}"))
154 for module, dist in available_extensions(extension_names(root)):
155 # Information, not a fault: an extension a wheel ships that this
156 # workspace has no use for is the common case.
157 findings.append(
158 Finding(unlisted(module, dist, per_package=composes_per_package(module)))
159 )
160 return findings
163def unlisted(module: str, dist: str, *, per_package: bool) -> str:
164 """The doctor's line for an installed extension the workspace lists nowhere.
166 The root's list takes any extension, and a package's list one that
167 composes something in a package. The line names `[workspace]
168 extensions`, and a package's `extensions` too when *per_package*
169 says the extension composes something in a package that holds it
170 ([livery.workshop._extensions.composes_per_package][]).
171 """
172 named = f" ({dist})" if dist else ""
173 places = "[workspace] extensions"
174 if per_package:
175 places += " or a package's extensions"
176 return (
177 f"extensions: {module}{named} is installed and not listed; it does"
178 f" nothing until {places} names it"
179 )
182def ssh(**facts: Any) -> list[Finding]:
183 """The ssh doctor: the shared connection, and a person's own multiplexing."""
184 import livery.footman as footman
185 from livery import git
187 del facts
188 findings: list[Finding] = []
189 config = Path.home() / ".ssh" / "config"
190 if config.is_file():
191 lines = [
192 line.strip()
193 for line in config.read_text("utf-8", errors="replace").splitlines()
194 if line.strip().lower().startswith(("controlmaster", "controlpath"))
195 ]
196 if lines:
197 findings.append(
198 Finding(
199 f"ssh: {config} multiplexes on its own ({'; '.join(lines)}); the"
200 " git plugin's command adds a master beside it"
201 )
202 )
203 socket_dir = git.ssh_sockets(footman.data_dir())
204 environment, reason = git.ssh_environment(
205 socket_dir,
206 configured=git.config_get(footman.cwd(), "core.sshCommand"),
207 )
208 if reason:
209 findings.append(
210 Finding(reason, "", f"delete {socket_dir / 'unsupported'} to try again")
211 )
212 elif not environment:
213 findings.append(
214 Finding("ssh: a command of your own stands; the plugin adds nothing")
215 )
216 else:
217 findings.append(
218 Finding(f"ssh: one connection per host, sockets in {socket_dir}")
219 )
220 return findings
223#: The size uv's cache may reach before the doctor reports it, when the
224#: contract sets no `[workspace] uv-cache-limit`.
225UV_CACHE_LIMIT = "10G"
227_UNITS = {"K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4}
230def parse_size(text: str) -> int:
231 """The bytes a size such as ``10G`` or ``500M`` names.
233 Raises:
234 ValueError: for any other shape, naming the accepted one.
235 """
236 match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([KMGT])B?\s*", text, flags=re.I)
237 if match is None:
238 raise ValueError(
239 f"{text!r} is not a size: a number with K, M, G or T, like 10G"
240 )
241 return int(float(match.group(1)) * _UNITS[match.group(2).upper()])
244def show_size(size: int) -> str:
245 """A size in the largest unit that keeps one decimal, ``47.2G``."""
246 for unit in ("T", "G", "M", "K"):
247 if size >= _UNITS[unit]:
248 return f"{size / _UNITS[unit]:.1f}{unit}"
249 return f"{size}B"
252def _tree_size(root: Path) -> int:
253 total = 0
254 stack = [root]
255 while stack:
256 current = stack.pop()
257 try:
258 with os.scandir(current) as entries:
259 for entry in entries:
260 if entry.is_dir(follow_symlinks=False):
261 stack.append(Path(entry.path))
262 elif entry.is_file(follow_symlinks=False):262 ↛ 259line 262 didn't jump to line 259 because the condition on line 262 was always true
263 total += entry.stat(follow_symlinks=False).st_size
264 except OSError:
265 continue
266 return total
269def uv_cache_dir() -> Path:
270 """Where uv keeps its cache on this machine, as the locked uv answers."""
271 from livery.toolroom import tools
273 result = tools.uv.opts(nofail=True, recorded=False)("cache", "dir")
274 if result.code != 0:
275 raise RuntimeError(
276 f"uv cache dir exited {result.code}: {result.stderr.strip()}"
277 )
278 return Path(result.stdout.strip())
281def prune_uv_cache() -> None:
282 """Drop the cache entries nothing references, through the locked uv."""
283 from livery.toolroom import tools
285 tools.uv.opts(recorded=False)("cache", "prune")
288def uv_cache(**facts: Any) -> list[Finding]:
289 """The uv cache doctor: its size against the limit the workspace sets."""
290 root = workspace_root()
291 if root is None:291 ↛ 292line 291 didn't jump to line 292 because the condition on line 291 was never true
292 return [Finding("uv cache: no workspace here, not checked")]
293 workspace = load_contract(root / "workshop.toml").get("workspace") or {}
294 declared = str(workspace.get("uv-cache-limit", UV_CACHE_LIMIT))
295 try:
296 limit = parse_size(declared)
297 except ValueError as error:
298 return [
299 Finding(
300 "uv cache",
301 f"[workspace] uv-cache-limit: {error}",
302 "set it to a size such as 10G in workshop.toml",
303 )
304 ]
305 try:
306 cache = uv_cache_dir()
307 except RuntimeError as error:
308 return [Finding("uv cache", str(error), "fm sync installs the locked uv")]
309 size = _tree_size(cache) if cache.is_dir() else 0
310 if size <= limit:
311 return [Finding(f"uv cache: {show_size(size)}, under the {declared} limit")]
312 return [
313 Finding(
314 "uv cache",
315 f"{show_size(size)}, over the {declared} limit",
316 "fm doctor --fix runs `uv cache prune`; `uv cache clean` empties it;"
317 " raise [workspace] uv-cache-limit in workshop.toml if this machine"
318 " needs a larger one",
319 prune_uv_cache,
320 )
321 ]