Coverage for src/romfarmer/engine/transforms/unzip.py: 87%
30 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"""Generic unzip transform — extract files from a ZIP archive.
3Used for cartridge ROMs and other platforms where the source is a ZIP
4containing one or more ROM files.
5"""
7from __future__ import annotations
9import shutil
10import zipfile
11from collections.abc import Mapping
12from pathlib import Path
14from .base import Transform, TransformError
17class UnzipTransform:
18 """Extract all non-directory members from a ZIP archive.
20 Recognised params:
21 extension_filter: comma-separated list of extensions to keep,
22 e.g. ``"nes,sfc"`` (default: all members)
23 """
25 name = "unzip"
27 def run(
28 self,
29 inputs: list[Path],
30 params: Mapping[str, str],
31 scratch: Path,
32 ) -> list[Path]:
33 if not inputs:
34 raise TransformError("UnzipTransform: no input files provided")
36 zip_path = inputs[0]
37 ext_filter: set[str] | None = None
38 if "extension_filter" in params:
39 ext_filter = {
40 e.strip().lower().lstrip(".") for e in params["extension_filter"].split(",")
41 }
43 extracted: list[Path] = []
45 with zipfile.ZipFile(zip_path, "r") as zf:
46 infos = [m for m in zf.infolist() if not m.filename.endswith("/")]
47 if ext_filter is not None:
48 infos = [
49 m for m in infos if Path(m.filename).suffix.lower().lstrip(".") in ext_filter
50 ]
51 if not infos:
52 raise TransformError(f"No matching files found in {zip_path.name}")
53 # Output index 0 is the "dominant member" (same rule as ZipIdentity):
54 # the cue/gdi sheet for disc images, otherwise the largest file.
55 infos.sort(
56 key=lambda m: (
57 Path(m.filename).suffix.lower() not in (".cue", ".gdi"),
58 -m.file_size,
59 m.filename,
60 )
61 )
62 for info in infos:
63 target = scratch / Path(info.filename).name
64 with zf.open(info) as src, target.open("wb") as dst:
65 shutil.copyfileobj(src, dst)
66 extracted.append(target)
68 return extracted
71_: Transform = UnzipTransform()