"""Bring-your-own images: the BIOS and cartridges, read in place, never copied. The BIOS is found by SHA-1 (docs/cartridge.md, "BIOS dumps"): an explicit path, then ``$COLECO_BIOS``, then MAME's ``coleco.zip``/``colecop.zip`` under ``$MAME_ROMPATH``. Cartridges load from a raw dump (``.col``, ``.rom``, ``.bin``) or the first such member of a ``.zip`` (stdlib) or ``.7z`` (the ``7z`` program, output to a pipe). """ from __future__ import annotations import hashlib import os import subprocess import zipfile from pathlib import Path from colecovision_python.machine import BIOS_NTSC_SHA1, BIOS_PAL_SHA1 #: The local ROM sets, by environment variable (relative defaults when unset). MAME_SETS = Path(os.environ.get("MAME_ROMPATH", "MAME")) NO_INTRO = Path(os.environ.get("NO_INTRO_DIR", "No-Intro")) / "Coleco - ColecoVision" #: Where each dump is looked for after $COLECO_BIOS (zip members by name). _BIOS_PLACES = { BIOS_NTSC_SHA1: [ (MAME_SETS / "coleco.zip", "313_10031-4005_73108a.u2"), ], BIOS_PAL_SHA1: [(MAME_SETS / "colecop.zip", "r72114a_8317.u2")], } _IMAGE_SUFFIXES = (".col", ".rom", ".bin", ".cv") def sha1(data: bytes) -> str: return hashlib.sha1(data).hexdigest() def _read_place(path: Path, member: str | None) -> bytes | None: try: if member is None: return path.read_bytes() with zipfile.ZipFile(path) as archive: return archive.read(member) except (OSError, KeyError, zipfile.BadZipFile): return None def load_bios(sha1_wanted: str = BIOS_NTSC_SHA1, path: str | os.PathLike | None = None) -> bytes: """The 8K OS-7 dump with ``sha1_wanted``. An explicit ``path`` (or ``$COLECO_BIOS``) is used as given, even if its hash is another one (a warning is the caller's).""" explicit = path or os.environ.get("COLECO_BIOS") if explicit: data = load_image(explicit) if len(data) != 8192: raise ValueError(f"{explicit}: a BIOS is 8,192 bytes, not {len(data)}") return data for place, member in _BIOS_PLACES.get(sha1_wanted, []): data = _read_place(place, member) if data is not None and sha1(data) == sha1_wanted: return data raise FileNotFoundError( f"no BIOS with SHA-1 {sha1_wanted} found; pass a path or set COLECO_BIOS (bring your own)" ) def load_image(path: str | os.PathLike) -> bytes: """A cartridge (or BIOS) image from a raw file, a zip or a 7z archive.""" path = Path(path) suffix = path.suffix.lower() if suffix == ".zip": with zipfile.ZipFile(path) as archive: names = [n for n in archive.namelist() if not n.endswith("/")] chosen = [n for n in names if n.lower().endswith(_IMAGE_SUFFIXES)] or names return archive.read(chosen[0]) if suffix == ".7z": listing = subprocess.run( ["7z", "l", "-slt", "-ba", str(path)], capture_output=True, text=True, check=True ).stdout names = [line[7:] for line in listing.splitlines() if line.startswith("Path = ")] chosen = [n for n in names if n.lower().endswith(_IMAGE_SUFFIXES)] or names return subprocess.run( ["7z", "e", "-so", str(path), chosen[0]], capture_output=True, check=True ).stdout return path.read_bytes()