Coverage for src/romfarmer/driver/hooks.py: 0%
224 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"""Post-build hooks and deployment as ``Protocol`` implementations.
3Review G4 #11 / intent brief P0 item 7 (2.9-partial): the orchestrator used to
4interpolate config strings into ``subprocess.run(..., shell=True)`` for
5``type: command`` hooks and for rsync deploy. Once an agent authors build
6specs that is remote code execution. Here every hook is a typed object and
7every subprocess is an **argv list** (``shell=False``); the only substitution
8is per-token replacement of ``{output_base}`` / ``{build_name}``.
10Native hooks (``genre_organize``, ``quarantine_unpolished``, ``patch_gamelist``)
11were moved verbatim from ``NewBuildOrchestrator``; their behaviour is unchanged.
12"""
14from __future__ import annotations
16import logging
17import shlex
18import subprocess
19from collections.abc import Mapping, Sequence
20from dataclasses import dataclass
21from pathlib import Path
22from typing import Any, Protocol
24logger = logging.getLogger(__name__)
27# ---------------------------------------------------------------------------
28# Contracts
29# ---------------------------------------------------------------------------
32@dataclass(frozen=True)
33class HookContext:
34 """What a hook may see: the build's output tree and completed platforms."""
36 build_name: str
37 output_base: Path
38 platforms: tuple[str, ...] # completed platforms (or the hook's explicit list)
39 metadata_db: Path
40 workspace_root: Path
43@dataclass(frozen=True)
44class HookResult:
45 ok: bool
46 summary: str = ""
49class PostBuildHook(Protocol):
50 """One post-build action. ``run`` must not shell out with config strings."""
52 kind: str
54 def run(self, hook: Any, ctx: HookContext) -> HookResult: ...
57def _substitute(token: str, ctx: HookContext) -> str:
58 return token.replace("{output_base}", str(ctx.output_base)).replace(
59 "{build_name}", ctx.build_name
60 )
63def _run_argv(argv: Sequence[str], *, cwd: Path | None = None) -> HookResult:
64 """Run an argv list (never a shell) and summarise the outcome."""
65 logger.info(" argv: %s", " ".join(shlex.quote(a) for a in argv))
66 try:
67 result = subprocess.run(list(argv), capture_output=True, text=True, cwd=cwd, check=False)
68 except OSError as exc:
69 return HookResult(False, f"cannot execute {argv[0]!r}: {exc}")
70 head = "\n".join(line for line in result.stdout.strip().splitlines()[:5] if line)
71 if result.returncode == 0:
72 return HookResult(True, head)
73 return HookResult(False, f"exit {result.returncode}: {result.stderr.strip()[:500]}")
76# ---------------------------------------------------------------------------
77# Generic hooks
78# ---------------------------------------------------------------------------
81class CommandHook:
82 """``type: command`` — ``command`` is parsed with ``shlex`` into argv.
84 Placeholders are substituted per token, so an ``output_base`` containing
85 spaces or shell metacharacters is one argument, never re-parsed. Pipes,
86 redirects and ``&&`` are not supported by design; write a native hook.
87 """
89 kind = "command"
91 def run(self, hook: Any, ctx: HookContext) -> HookResult:
92 command = getattr(hook, "command", None)
93 if not command:
94 return HookResult(True, "skipped (no command)")
95 argv = [_substitute(tok, ctx) for tok in shlex.split(command)]
96 return _run_argv(argv)
99class JdupesHook:
100 """``type: jdupes`` — hardlink duplicate files under the output tree.
102 Options: ``args`` (list of extra jdupes flags; default ``["-r", "-L"]``).
103 """
105 kind = "jdupes"
107 def run(self, hook: Any, ctx: HookContext) -> HookResult:
108 opts: Mapping[str, Any] = getattr(hook, "options", None) or {}
109 args = [str(a) for a in (opts.get("args") or ["-r", "-L"])]
110 return _run_argv(["jdupes", *args, str(ctx.output_base)])
113class NativeHook:
114 """Adapter for the in-process hooks below (they log their own summaries)."""
116 def __init__(self, kind: str, fn: Any) -> None:
117 self.kind = kind
118 self._fn = fn
120 def run(self, hook: Any, ctx: HookContext) -> HookResult:
121 self._fn(hook, ctx)
122 return HookResult(True)
125# ---------------------------------------------------------------------------
126# Native hooks (moved from NewBuildOrchestrator, behaviour unchanged)
127# ---------------------------------------------------------------------------
130def _genre_organize(hook: Any, ctx: HookContext) -> None:
131 """
132 Run genre organization for all completed platforms.
134 Iterates over completed platforms, looks each up in the metadata DB
135 by system name, and creates hardlinked 'By Genre/' subdirectories.
136 Zero disk cost on ZFS/same-filesystem hardlinks.
138 Hook options (all optional):
139 mode: hardlink | copy | symlink | move (default: hardlink)
140 merge_small: int — merge genres with < N games into 'Other' (default: 3)
141 exclude_genres: list of genre names to skip
142 system_map: dict mapping platform → system name for DB lookups
143 platforms: list of platforms to process (default: all completed)
144 """
145 from romfarmer.organizers.base import OrganizeMode
146 from romfarmer.organizers.genre import GenreOrganizer
148 mode = OrganizeMode(hook.options.get("mode", "hardlink"))
149 merge_small = hook.options.get("merge_small", 3)
150 exclude_genres = hook.options.get("exclude_genres") or None
151 system_map: dict[str, str] = hook.options.get("system_map") or {}
152 metadata_db = ctx.metadata_db
154 if not metadata_db.exists():
155 logger.warning(f" ⚠ Metadata DB not found: {metadata_db} — skipping genre organization")
156 return
158 # Determine which platforms to process
159 platforms = hook.options.get("platforms") or list(ctx.platforms)
160 if not platforms:
161 logger.info(" No completed platforms to genre-organize")
162 return
164 logger.info(f" Genre organizing {len(platforms)} platform(s) (mode: {mode.value})")
166 total_organized = 0
167 total_skipped = 0
169 for platform in platforms:
170 platform_dir = ctx.output_base / platform
171 if not platform_dir.exists():
172 logger.debug(f" Skipping {platform} (no output dir)")
173 continue
175 system = system_map.get(platform, platform)
177 try:
178 organizer = GenreOrganizer(
179 metadata_db=metadata_db,
180 system=system,
181 mode=mode,
182 merge_small=merge_small,
183 exclude_genres=list(exclude_genres) if exclude_genres else None,
184 )
185 stats = organizer.organize(platform_dir)
186 organized = stats.files_moved + stats.files_copied + stats.symlinks_created
187 total_organized += organized
188 total_skipped += stats.skipped
189 if organized > 0 or stats.errors > 0:
190 logger.info(
191 f" {platform}: {organized} organized, "
192 f"{stats.skipped} skipped"
193 + (f", {stats.errors} errors" if stats.errors else "")
194 )
195 else:
196 logger.debug(f" {platform}: no genre data in DB")
197 except Exception as e:
198 logger.warning(f" {platform}: genre organize failed — {e}")
200 logger.info(
201 f" ✅ Genre organization complete: {total_organized} hardlinks created across {len(platforms)} platforms"
202 )
205def _quarantine_unpolished(hook: Any, ctx: HookContext) -> None:
206 """
207 Move unpolished root-level games into a quarantine subfolder (default: Other/).
209 A game is "unpolished" if it is missing a required metadata field in the
210 root gamelist.xml entry. Unpolished games are:
211 - hardlinked into <folder_name>/ (zero disk cost)
212 - hidden in the root gamelist via <hidden>true</hidden>
213 patch_gamelist then backfills a visible entry for the subdir copy.
215 Files already in any subdir (By Genre/, Best Games/, Translations/, etc.)
216 are never touched.
218 Hook options (all optional):
219 folder_name: destination subdir name (default: Other)
220 require_image: hide if <image> is absent (default: true)
221 require_desc: hide if <desc> is absent (default: true)
222 platforms: list of platforms to process (default: all completed)
223 """
224 import os
225 from xml.etree import ElementTree as ET
227 folder_name = hook.options.get("folder_name", "Other")
228 require_image = hook.options.get("require_image", True)
229 require_desc = hook.options.get("require_desc", True)
231 platforms = hook.options.get("platforms") or list(ctx.platforms)
232 if not platforms:
233 logger.info(" No completed platforms to process")
234 return
236 logger.info(
237 f" Quarantining unpolished games for {len(platforms)} platform(s) "
238 f"→ {folder_name}/ (require_image={require_image}, require_desc={require_desc})"
239 )
240 total_quarantined = 0
242 for platform in platforms:
243 platform_dir = ctx.output_base / platform
244 gamelist_path = platform_dir / "gamelist.xml"
245 if not gamelist_path.exists():
246 continue
248 tree = ET.parse(gamelist_path)
249 xml_root = tree.getroot()
250 quarantine_dir = platform_dir / folder_name
251 quarantined = 0
253 for game in xml_root.findall("game"):
254 path_text = game.findtext("path") or ""
255 rel = path_text.lstrip("./")
256 # Root-level entries only — skip anything already in a subdir
257 if "/" in rel:
258 continue
259 # Skip already-hidden entries
260 if game.findtext("hidden") == "true":
261 continue
263 missing_image = require_image and not (game.findtext("image") or "").strip()
264 missing_desc = require_desc and not (game.findtext("desc") or "").strip()
265 if not missing_image and not missing_desc:
266 continue # polished — leave in root
268 rom_path = platform_dir / rel
269 if not rom_path.exists():
270 continue
272 # Hardlink into quarantine subdir
273 quarantine_dir.mkdir(parents=True, exist_ok=True)
274 dest = quarantine_dir / rom_path.name
275 if not dest.exists():
276 try:
277 os.link(rom_path, dest)
278 except OSError:
279 import shutil
281 shutil.copy2(rom_path, dest)
283 # Hide the root gamelist entry
284 hidden_elem = game.find("hidden")
285 if hidden_elem is None:
286 hidden_elem = ET.SubElement(game, "hidden")
287 hidden_elem.text = "true"
288 quarantined += 1
290 if quarantined > 0:
291 ET.indent(tree, space=" ")
292 tree.write(gamelist_path, encoding="utf-8", xml_declaration=True)
293 logger.info(f" {platform}: {quarantined} games → {folder_name}/")
294 total_quarantined += quarantined
296 logger.info(
297 f" ✅ Quarantine complete: {total_quarantined} games moved to {folder_name}/"
298 f" across {len(platforms)} platforms"
299 )
302def _patch_gamelist(hook: Any, ctx: HookContext) -> None:
303 """
304 Patch gamelist.xml files to include subdirectory entries.
306 GenerateMetadataStage only writes root-level entries. After
307 GenreOrganizer creates By Genre/ hardlinks (and ApplyListsStage
308 creates Best Games/ etc.), those files have no gamelist coverage.
309 This hook clones each root entry for every matching file found in
310 any subdirectory, so EmulationStation can browse by folder.
312 Hook options (all optional):
313 platforms: list of platforms to process (default: all completed)
314 """
315 import importlib.util
317 script_path = ctx.workspace_root / "scripts" / "patch_gamelist_subdirs.py"
318 if not script_path.exists():
319 logger.warning(f" ⚠ patch_gamelist_subdirs.py not found at {script_path}")
320 return
322 spec = importlib.util.spec_from_file_location("patch_gamelist_subdirs", script_path)
323 if spec is None or spec.loader is None:
324 logger.warning(" ⚠ cannot load %s", script_path)
325 return
326 mod = importlib.util.module_from_spec(spec)
327 spec.loader.exec_module(mod)
329 platforms = hook.options.get("platforms") or list(ctx.platforms)
330 if not platforms:
331 logger.info(" No completed platforms to patch")
332 return
334 logger.info(f" Patching gamelist subdirs for {len(platforms)} platform(s)")
335 total_added = 0
337 for platform in platforms:
338 platform_dir = ctx.output_base / platform
339 if not platform_dir.exists():
340 logger.debug(f" Skipping {platform} (no output dir)")
341 continue
343 stats = mod.patch_platform(platform_dir)
344 added = stats.get("added", 0)
345 status = stats.get("status", "?")
346 total_added += added
348 if added > 0:
349 logger.info(f" {platform}: +{added} gamelist entries added")
350 elif status not in ("ok", "skipped (folder format)"):
351 logger.debug(f" {platform}: [{status}]")
353 logger.info(
354 f" ✅ Gamelist patch complete: {total_added} entries added"
355 f" across {len(platforms)} platforms"
356 )
359# ---------------------------------------------------------------------------
360# Registry + driver entry points
361# ---------------------------------------------------------------------------
363HOOKS: dict[str, PostBuildHook] = {
364 "command": CommandHook(),
365 "jdupes": JdupesHook(),
366 "genre_organize": NativeHook("genre_organize", _genre_organize),
367 "quarantine_unpolished": NativeHook("quarantine_unpolished", _quarantine_unpolished),
368 "patch_gamelist": NativeHook("patch_gamelist", _patch_gamelist),
369}
372def run_post_build_hooks(hooks: Sequence[Any], ctx: HookContext) -> list[tuple[str, HookResult]]:
373 """Run every configured hook through the registry; unknown kinds are errors, not shells."""
374 results: list[tuple[str, HookResult]] = []
375 for i, hook in enumerate(hooks, 1):
376 kind = str(getattr(hook, "type", "command"))
377 name = str(getattr(hook, "name", kind))
378 logger.info(" [%d/%d] Hook: %s (type: %s)", i, len(hooks), name, kind)
379 impl = HOOKS.get(kind)
380 if impl is None:
381 res = HookResult(False, f"unknown hook type {kind!r} (known: {sorted(HOOKS)})")
382 else:
383 try:
384 res = impl.run(hook, ctx)
385 except Exception as exc: # a hook must not abort the build report
386 logger.error(" ❌ %s error: %s", name, exc, exc_info=True)
387 res = HookResult(False, str(exc))
388 logger.info(" %s %s", "✅" if res.ok else "❌", res.summary or "")
389 results.append((name, res))
390 return results
393class Deployer(Protocol):
394 method: str
396 def run(
397 self, output_base: Path, destination: str, options: Mapping[str, Any]
398 ) -> HookResult: ...
401class RsyncDeploy:
402 """``method: rsync`` — argv built from options; ``rsync_flags`` is shlex-split."""
404 method = "rsync"
406 def argv(self, output_base: Path, destination: str, options: Mapping[str, Any]) -> list[str]:
407 flags = shlex.split(str(options.get("rsync_flags", "-avH --progress")))
408 argv = ["rsync", *flags]
409 if options.get("delete_extra", False):
410 argv.append("--delete")
411 if options.get("dry_run", False):
412 argv.append("--dry-run")
413 argv += [f"{output_base}/", destination]
414 return argv
416 def run(self, output_base: Path, destination: str, options: Mapping[str, Any]) -> HookResult:
417 return _run_argv(self.argv(output_base, destination, options))
420DEPLOYERS: dict[str, Deployer] = {"rsync": RsyncDeploy()}
423def run_deployment(deploy: Any, output_base: Path) -> HookResult | None:
424 """Deploy ``output_base`` per the build spec's ``deploy`` block; ``None`` if gated by ``confirm``."""
425 method = str(getattr(deploy, "method", "rsync"))
426 destination = str(getattr(deploy, "destination", ""))
427 options: Mapping[str, Any] = getattr(deploy, "options", None) or {}
428 impl = DEPLOYERS.get(method)
429 if impl is None:
430 return HookResult(False, f"unknown deploy method {method!r} (known: {sorted(DEPLOYERS)})")
431 logger.info(" Method: %s", method)
432 logger.info(" Destination: %s", destination)
433 if options.get("confirm", True):
434 logger.info(" (Requires --deploy flag to execute)")
435 return None
436 return impl.run(output_base, destination, options)