# SPDX-License-Identifier: MIT """Run one of megadrive-python's scripts with a passive 32X in the cartridge slot. Milestone 1's acceptance is megadrive-python's own gate with a 32X inserted and ADEN never set (docs/handoff-brief.md): the MAME lockstep, VDPFIFOTesting, the compatibility sweep. Those scripts build their ``System(machine, cartridge, ...)`` themselves, so this wraps ``megadrive_python.system.System.__init__`` before running the script: every System made with a cartridge (or with an empty slot) instead gets ``slot=Sega32X(cartridge)`` and no cartridge of its own -- the 32X holding the game, as the hardware has it. Nothing in megadrive-python is changed. The script, its data and its caches come from the checkout named by ``--megadrive``; the ``megadrive_python`` package is the one this environment has installed, the pin in pyproject.toml (this package imports it before the script can put the checkout's ``src`` first). The harness prints both, and the checkout should sit at the pinned revision. python -m sega32x_python.harness --megadrive ../megadrive-python \\ scripts/run_vdpfifotesting.py --machine genesis The script path is relative to ``--megadrive``. ``--without`` runs the same script without the 32X, through the same entry point, for an A/B. Worker processes the scripts start inherit the patch: the start method is forced to ``fork`` (PyPy 3.11's default already; CPython 3.14 defaults to ``forkserver``, which would not). """ from __future__ import annotations import argparse import atexit import multiprocessing import runpy import subprocess import sys from pathlib import Path #: Systems built under the patch, and claims re-read with ADEN set (which a passive 32X #: never does), printed when the process exits. Worker processes leave through #: ``os._exit`` and print nothing; their parent's line covers what it built itself. INSERTED = {"count": 0, "aden": 0} def insert_32x() -> None: """Wrap ``System.__init__`` so every System is built with a passive 32X holding its cartridge.""" from megadrive_python import system as system_module from .slot import Sega32X class Watched(Sega32X): def claims(self) -> list[tuple[int, int]]: if self.adapter & 1: INSERTED["aden"] += 1 return super().claims() original = system_module.System.__init__ if getattr(original, "sega32x_wrapped", False): return def init(self, machine, cartridge, **kwargs): # type: ignore[no-untyped-def] device = None if kwargs.get("slot") is None: device = kwargs["slot"] = Watched(cartridge) cartridge = None INSERTED["count"] += 1 original(self, machine, cartridge, **kwargs) if device is not None: # Sockets 7 and 8 too, as console.build attaches them: with ADEN = 0 the # composite hands every line back as the Mega Drive's own (None) and PWM gives # no samples, which the gate checks. self.attach_picture(device) self.audio_sources.append(device.pwm) init.sega32x_wrapped = True # type: ignore[attr-defined] system_module.System.__init__ = init # type: ignore[method-assign] def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--megadrive", type=Path, required=True, help="megadrive-python checkout") parser.add_argument("--without", action="store_true", help="run without the 32X (A/B)") parser.add_argument("script", help="path relative to --megadrive") parser.add_argument("args", nargs=argparse.REMAINDER) options = parser.parse_args(argv) root = options.megadrive.resolve() script = root / options.script def git(*args: str) -> str: done = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True) return done.stdout.strip() revision = git("rev-parse", "--short", "HEAD") dirty = git("status", "--porcelain", "--", "src") import megadrive_python print(f"[harness] scripts: megadrive-python {revision}{' (src modified)' if dirty else ''}; " f"package: {Path(megadrive_python.__file__).parent}; " f"32X {'not inserted' if options.without else 'inserted, passive'}", file=sys.stderr, flush=True) # fmt: skip sys.path[:0] = [str(root / "src"), str(script.parent)] if sys.platform.startswith("linux"): multiprocessing.set_start_method("fork", force=True) if not options.without: insert_32x() atexit.register( lambda: print( f"[harness] systems built with a 32X: {INSERTED['count']}; " f"claims read with ADEN set: {INSERTED['aden']}", file=sys.stderr, flush=True, ) ) sys.argv = [str(script), *options.args] try: runpy.run_path(str(script), run_name="__main__") except SystemExit as stop: code = stop.code return code if isinstance(code, int) else (0 if code is None else 1) return 0 if __name__ == "__main__": sys.exit(main())