Coverage for src/romfarmer/engine/transforms/chd.py: 80%
55 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""CHD transform — chdman CD/DVD compression.
3Supports ``createcd`` (CUE/BIN, GDI) and ``createdvd`` (ISO). The input may
4be the disc image itself or a ZIP containing it (Redump/Myrient layout); a ZIP
5is extracted into a private directory so multi-track BIN files stay next to
6their CUE without ever entering the CAS as intermediates.
7"""
9from __future__ import annotations
11import shutil
12import subprocess
13import zipfile
14from collections.abc import Mapping
15from pathlib import Path
17from .base import Transform, TransformError, pinned_env
19_SHEET_PRIORITY = (".cue", ".gdi", ".toc", ".iso")
22def _pick_disc_image(files: list[Path]) -> Path:
23 for ext in _SHEET_PRIORITY:
24 for f in files:
25 if f.suffix.lower() == ext:
26 return f
27 return max(files, key=lambda f: f.stat().st_size)
30class CHDTransform:
31 """Compress a disc image (CUE/BIN, GDI or ISO — loose or zipped) to CHD.
33 Recognised params:
34 mode: ``"createcd"`` (default) or ``"createdvd"``
35 compression: chdman codec, e.g. ``"lzma"`` (default for createdvd)
36 chdman_path: override path to chdman binary
37 """
39 name = "chdman"
41 def run(
42 self,
43 inputs: list[Path],
44 params: Mapping[str, str],
45 scratch: Path,
46 ) -> list[Path]:
47 if not inputs:
48 raise TransformError("CHDTransform: no input files provided")
50 input_file = inputs[0]
51 mode = params.get("mode", "createcd")
52 chdman = self._find_chdman(params.get("chdman_path"))
53 if chdman is None:
54 raise TransformError("chdman not found; install it or set chdman_path param")
56 output_name = input_file.stem + ".chd"
57 output_path = scratch / output_name
59 if zipfile.is_zipfile(input_file):
60 extract_dir = scratch / f"{input_file.stem}.extracted"
61 extract_dir.mkdir(exist_ok=True)
62 with zipfile.ZipFile(input_file) as zf:
63 members = [m for m in zf.namelist() if not m.endswith("/")]
64 if not members:
65 raise TransformError(f"{input_file.name} is an empty archive")
66 zf.extractall(extract_dir)
67 input_file = _pick_disc_image([extract_dir / m for m in members])
69 cmd = [str(chdman), mode, "-i", str(input_file), "-o", str(output_path)]
70 if mode == "createdvd" and "compression" in params:
71 cmd += ["-c", params["compression"]]
73 result = subprocess.run(cmd, capture_output=True, text=True, check=False, env=pinned_env())
74 if result.returncode != 0:
75 raise TransformError(
76 f"chdman {mode} failed for {input_file.name}: {result.stderr[:500]}"
77 )
78 if not output_path.exists():
79 raise TransformError(f"chdman did not produce expected output {output_path}")
80 return [output_path]
82 @staticmethod
83 def _find_chdman(override: str | None) -> Path | None:
84 if override:
85 p = Path(override).resolve()
86 return p if p.exists() else None
87 workspace_bin = Path("tools/bin/chdman")
88 if workspace_bin.exists():
89 return workspace_bin.resolve()
90 found = shutil.which("chdman")
91 return Path(found).resolve() if found else None
94# Satisfy the Transform protocol at type-check time
95_: Transform = CHDTransform()