Coverage for src/romfarmer/cli/doctor.py: 0%
164 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
1"""``romfarmer doctor`` — environment and determinism checks.
3``romfarmer doctor`` reports which external tools the transforms can find.
4``romfarmer doctor --determinism`` runs each available transform twice on a
5tiny synthetic fixture (with the input's mtime changed between runs) and
6reports whether the output bytes are identical. This is the empirical check
7behind the reproducibility claim; the flag table in the transforms is only a
8hypothesis until this passes on the operator's machine.
9"""
11from __future__ import annotations
13import hashlib
14import os
15import shutil
16import tempfile
17import time
18from collections.abc import Callable
19from dataclasses import dataclass
20from pathlib import Path
22import click
23from rich.console import Console
24from rich.table import Table
26from romfarmer.engine.transforms.archive import ArchiveTransform
27from romfarmer.engine.transforms.chd import CHDTransform
28from romfarmer.engine.transforms.squashfs import SquashFSTransform
29from romfarmer.ir.tool_impl import IMPL_VERSIONS
30from romfarmer.planner.lowering.base import probe_tool_version
32console = Console()
34# Deterministic pseudo-random payload: same bytes on every machine, so the
35# report can be compared across hosts.
36_SEED = b"romfarmer-doctor"
39def _payload(size: int) -> bytes:
40 out = bytearray()
41 counter = 0
42 while len(out) < size:
43 out += hashlib.sha256(_SEED + counter.to_bytes(4, "big")).digest()
44 counter += 1
45 return bytes(out[:size])
48def _sha256(path: Path) -> str:
49 h = hashlib.sha256()
50 with path.open("rb") as f:
51 for chunk in iter(lambda: f.read(1 << 20), b""):
52 h.update(chunk)
53 return h.hexdigest()
56@dataclass(frozen=True)
57class _Probe:
58 tool: str
59 make_fixture: Callable[[Path], list[Path]]
60 run: Callable[[list[Path], Path], list[Path]]
63def _fixture_file(root: Path) -> list[Path]:
64 p = root / "Game (USA).bin"
65 p.write_bytes(_payload(300_000))
66 return [p]
69def _fixture_cue(root: Path) -> list[Path]:
70 (root / "Game (USA).bin").write_bytes(_payload(2352 * 64))
71 cue = root / "Game (USA).cue"
72 cue.write_text('FILE "Game (USA).bin" BINARY\n TRACK 01 MODE1/2352\n INDEX 01 00:00:00\n')
73 return [cue]
76def _fixture_dir(root: Path) -> list[Path]:
77 d = root / "Game (USA)"
78 d.mkdir()
79 (d / "default.xbe").write_bytes(_payload(100_000))
80 (d / "data.bin").write_bytes(_payload(200_000))
81 return [d]
84_PROBES: list[_Probe] = [
85 _Probe("7z", _fixture_file, lambda i, s: ArchiveTransform().run(i, {"format": "7z"}, s)),
86 _Probe("7z (zip)", _fixture_file, lambda i, s: ArchiveTransform().run(i, {"format": "zip"}, s)),
87 _Probe("chdman", _fixture_cue, lambda i, s: CHDTransform().run(i, {"mode": "createcd"}, s)),
88 _Probe("mksquashfs", _fixture_dir, lambda i, s: SquashFSTransform().run(i, {}, s)),
89]
92def _touch_all(paths: list[Path]) -> None:
93 """Bump mtimes so timestamp leaks show up as a hash difference."""
94 later = time.time() + 86400
95 for p in paths:
96 targets = [p, *p.rglob("*")] if p.is_dir() else [p]
97 for t in targets:
98 os.utime(t, (later, later))
101def _run_probe(probe: _Probe) -> tuple[str, str]:
102 """Return (status, detail) for one transform."""
103 with tempfile.TemporaryDirectory(prefix="romfarmer-doctor-") as tmp:
104 root = Path(tmp)
105 fixture_dir = root / "fixture"
106 fixture_dir.mkdir()
107 inputs = probe.make_fixture(fixture_dir)
108 hashes: list[str] = []
109 for n in (1, 2):
110 scratch = root / f"scratch{n}"
111 scratch.mkdir()
112 try:
113 outputs = probe.run(inputs, scratch)
114 except Exception as exc: # tool missing or failed — report, don't abort
115 return "unavailable", str(exc)[:80]
116 hashes.append(",".join(_sha256(o) for o in sorted(outputs)))
117 _touch_all(inputs)
118 if hashes[0] == hashes[1]:
119 return "deterministic", hashes[0][:16]
120 return "NON-DETERMINISTIC", f"{hashes[0][:16]} != {hashes[1][:16]}"
123_TOOL_BINARIES = {
124 "7z": ("7z", "7zz", "7za"),
125 "chdman": ("chdman",),
126 "mksquashfs": ("mksquashfs",),
127 "extract-xiso": ("extract-xiso", "tools/bin/extract-xiso"),
128 "dolphin-tool": ("dolphin-tool", "tools/bin/dolphin-tool"),
129 "wit": ("wit", "tools/bin/wit"),
130 "ps3dec": ("ps3dec", "tools/bin/ps3dec"),
131}
134def _locate(candidates: tuple[str, ...]) -> Path | None:
135 for c in candidates:
136 found = shutil.which(c)
137 if found:
138 return Path(found)
139 if Path(c).exists():
140 return Path(c).resolve()
141 return None
144def _check_builds(builds: tuple[str, ...]) -> int:
145 """RESOLVE-only health check per platform; returns the number of problems."""
146 import logging
148 from romfarmer.new_orchestrator import NewBuildOrchestrator
150 logging.disable(logging.WARNING) # _find_dat_file warns; the table reports it
151 problems = 0
152 for build in builds:
153 try:
154 orch = NewBuildOrchestrator.from_config(build)
155 except Exception as exc:
156 console.print(f"[red]{build}: cannot load — {str(exc).splitlines()[-1][:160]}[/red]")
157 problems += 1
158 continue
159 try:
160 profile = orch._load_target_profile()
161 except Exception as exc:
162 console.print(f"[red]{build}: target profile — {str(exc)[:160]}[/red]")
163 problems += 1
164 profile = None
165 table = Table(title=f"{build} (target: {orch.build_spec.target})")
166 for col in ("Platform", "Type", "Sources", "DAT", "Chain"):
167 table.add_column(col)
168 for r in orch.resolved_configs:
169 srcs = [s.path for s in (r.sources or ()) if s.path is not None]
170 missing = [p for p in srcs if not p.exists()]
171 src_cell = (
172 f"[red]{len(missing)}/{len(srcs)} missing[/red]" if missing else f"{len(srcs)} ok"
173 )
174 dat_needed = (
175 r.dat is not None and "none" not in str(getattr(r.dat, "source", "")).lower()
176 )
177 dat_file = orch._find_dat_file(r) if dat_needed else None
178 if not dat_needed:
179 dat_cell = "[dim]n/a[/dim]"
180 elif dat_file:
181 dat_cell = dat_file.name[:48]
182 else:
183 dat_cell = "[red]missing[/red]"
184 try:
185 rb = orch.resolve(r) if profile is not None else None
186 chain_cell = "→".join(rb.chain) if rb is not None else "[red]no profile[/red]"
187 except Exception as exc:
188 chain_cell = f"[red]{str(exc)[:70]}[/red]"
189 bad = bool(missing) or (dat_needed and not dat_file) or chain_cell.startswith("[red]")
190 problems += int(bad)
191 table.add_row(r.platform, r.extraction_type.value, src_cell, dat_cell, chain_cell)
192 console.print(table)
193 console.print(
194 f"\n{problems} problem(s)" if problems else "\n[green]all platforms resolve[/green]"
195 )
196 return 1 if problems else 0
199@click.command("doctor")
200@click.option(
201 "--determinism", is_flag=True, help="Run each transform twice and compare output bytes."
202)
203@click.option(
204 "--build",
205 "builds",
206 multiple=True,
207 help="Check every platform of a build (source dirs, DAT, format negotiation). Repeatable.",
208)
209def doctor(determinism: bool, builds: tuple[str, ...]) -> None:
210 """Check external tools, build configs and, optionally, byte-reproducibility."""
211 if builds:
212 raise click.exceptions.Exit(_check_builds(builds))
214 table = Table(title="External tools", show_lines=False)
215 table.add_column("Tool")
216 table.add_column("Found")
217 table.add_column("Version (as keyed)")
218 table.add_column("impl", justify="right")
219 for tool, candidates in _TOOL_BINARIES.items():
220 path = _locate(candidates)
221 version = probe_tool_version(str(path)) if path else "-"
222 table.add_row(
223 tool,
224 str(path) if path else "[red]missing[/red]",
225 version,
226 str(IMPL_VERSIONS.get(tool, 1)),
227 )
228 console.print(table)
230 if not determinism:
231 return
233 console.print()
234 det = Table(title="Determinism (run twice, input mtime changed between runs)")
235 det.add_column("Transform")
236 det.add_column("Result")
237 det.add_column("Detail")
238 failures = 0
239 for probe in _PROBES:
240 status, detail = _run_probe(probe)
241 color = {"deterministic": "green", "unavailable": "yellow"}.get(status, "red")
242 if status == "NON-DETERMINISTIC":
243 failures += 1
244 det.add_row(probe.tool, f"[{color}]{status}[/{color}]", detail)
245 det.add_row("extract-xiso", "[yellow]not probed[/yellow]", "requires a real XISO fixture")
246 console.print(det)
247 if failures:
248 raise click.exceptions.Exit(1)