From 745ab63e63c847371d872f05ecfd03c039b372ec Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:31:48 +0100 Subject: [PATCH] refactor: hand exporters the profiles they read --- scripts/exporter/base_exporter.py | 19 ++++++++++--------- scripts/exporter/batocera_exporter.py | 4 ++-- scripts/exporter/native.py | 18 +++++++++++------- scripts/exporter/retrobat_exporter.py | 4 ++-- scripts/exporter/rocknix_exporter.py | 4 ++-- scripts/exporter/romm_exporter.py | 4 ++-- tests/test_export_counts.py | 5 +---- tests/test_export_report.py | 9 +++++++-- tests/test_exporters.py | 27 ++++++++++++++++++--------- 9 files changed, 55 insertions(+), 39 deletions(-) diff --git a/scripts/exporter/base_exporter.py b/scripts/exporter/base_exporter.py index 664895826..3f364c5e8 100644 --- a/scripts/exporter/base_exporter.py +++ b/scripts/exporter/base_exporter.py @@ -11,8 +11,7 @@ from __future__ import annotations from abc import ABC, abstractmethod from typing import Generic, TypeVar, Union -from core.paths import EMULATORS_DIR, REPO_ROOT -from model.profiles import core_key_index, load_emulator_profiles, platform_core_profiles +from model.profiles import core_key_index, platform_core_profiles from resolve.reconcile import NativeFile, NativeSystem, Report # What a produced file holds: text for every format, bytes besides for one @@ -27,6 +26,12 @@ class BaseExporter(ABC, Generic[Content]): # truth accepts under several cannot be written whole. SINGLE_HASH_FIELD: str | None = None + def __init__(self, profiles: dict[str, dict] | None = None) -> None: + """``profiles`` are the emulator profiles a core name in the + platform's own file is read against, none when not given.""" + self._profiles: dict[str, dict] = profiles or {} + self._core_index = core_key_index(self._profiles, include_aliases=True) + @staticmethod @abstractmethod def platform_name() -> str: @@ -234,13 +239,9 @@ class BaseExporter(ABC, Generic[Content]): revision Batocera builds under that name, and load order picked either one. """ - cached = getattr(self, "_core_profiles", None) - if cached is None: - profiles = load_emulator_profiles(str(REPO_ROOT / EMULATORS_DIR)) - cached = (profiles, core_key_index(profiles, include_aliases=True)) - self._core_profiles = cached - profiles, index = cached - return platform_core_profiles(index, profiles, name, self.platform_name(), mode) + return platform_core_profiles( + self._core_index, self._profiles, name, self.platform_name(), mode + ) def required_value(self, fe: NativeFile) -> bool: """The requirement the render writes for an entry. diff --git a/scripts/exporter/batocera_exporter.py b/scripts/exporter/batocera_exporter.py index 20410fb5b..ac9e0e5c8 100644 --- a/scripts/exporter/batocera_exporter.py +++ b/scripts/exporter/batocera_exporter.py @@ -183,8 +183,8 @@ class Exporter(BaseExporter[str]): # AmberELEC's and EmuELEC's destinations already start at /storage/roms. PATH_PREFIX = "bios/" - def __init__(self) -> None: - super().__init__() + def __init__(self, profiles: dict[str, dict] | None = None) -> None: + super().__init__(profiles) # The emulator and core each system entry of the original is gated # on, read by render. self._gates: dict[str, tuple[str, str | None] | None] = {} diff --git a/scripts/exporter/native.py b/scripts/exporter/native.py index ac90d89b8..9059e0a7a 100644 --- a/scripts/exporter/native.py +++ b/scripts/exporter/native.py @@ -58,9 +58,13 @@ class StaleTruth(ValueError): def _truth_sources(platforms_dir: str) -> tuple[dict, dict, dict | None]: """Registry, profiles and database, as generate_truth reads them.""" registry = load_platform_registry(platforms_dir) - profiles = load_emulator_profiles("emulators") db = load_database(TRUTH_DB) if Path(TRUTH_DB).exists() else None - return registry, profiles, db + return registry, _profiles(), db + + +def _profiles() -> dict[str, dict]: + """The emulator profiles the truth and the exporters read.""" + return load_emulator_profiles("emulators") def current_truth(platform: str, config: dict, platforms_dir: str) -> dict: @@ -114,7 +118,7 @@ def refresh_cache( except StaleTruth as exc: return False, [str(exc)] systems, _ = build_native_model(truth or {}, scraped) - exporter: BaseExporter = exporter_class() + exporter: BaseExporter = exporter_class(_profiles()) wanted = wanted_sources(exporter, systems, scraped) off_pin = unpinned(wanted, scraped) if off_pin: @@ -140,7 +144,7 @@ def doubled_in(scraped: dict | None, platforms_dir: str) -> list[dict]: return [] db, zip_contents = _collection(TRUTH_DB) return doubled_destinations( - scraped, load_emulator_profiles("emulators"), db, zip_contents, + scraped, _profiles(), db, zip_contents, load_data_dir_registry(platforms_dir), ) @@ -171,7 +175,8 @@ def export_platform( if not systems: return False, ["nothing to write: neither the platform nor the truth has data"] - exporter: BaseExporter = exporter_class() + profiles = _profiles() + exporter: BaseExporter = exporter_class(profiles) produced, issues, stopped = _produce( exporter, systems, report, scraped, upstream_dir, allow_fetch, ) @@ -198,8 +203,7 @@ def export_platform( unwritten = _unwritten(refused, withheld, report) # Reported, never removed: the platform's file keeps every entry. candidates = removal_candidates( - systems, scraped, load_emulator_profiles("emulators"), - load_data_dir_registry(platforms_dir), + systems, scraped, profiles, load_data_dir_registry(platforms_dir), ) # Reported, never rewritten: both declarations stay as the platform wrote them. doubled = doubled_in(scraped, platforms_dir) diff --git a/scripts/exporter/retrobat_exporter.py b/scripts/exporter/retrobat_exporter.py index b625a0a83..201ed4395 100644 --- a/scripts/exporter/retrobat_exporter.py +++ b/scripts/exporter/retrobat_exporter.py @@ -81,8 +81,8 @@ class Exporter(BaseExporter[str]): return bool(self.single_value(fe, "md5")) return super().states(fe, field_name) - def __init__(self) -> None: - super().__init__() + def __init__(self, profiles: dict[str, dict] | None = None) -> None: + super().__init__(profiles) # Additions render did not write: another entry holds their path. self._merged: set[int] = set() diff --git a/scripts/exporter/rocknix_exporter.py b/scripts/exporter/rocknix_exporter.py index 3e531b691..1b886667b 100644 --- a/scripts/exporter/rocknix_exporter.py +++ b/scripts/exporter/rocknix_exporter.py @@ -30,8 +30,8 @@ _ADD_EMU_CORE = re.compile(r"^\s*add_emu_core\s+(\S+)\s+(\S+)\s+(\S+)", re.MULTI class Exporter(BatoceraExporter): """Write ROCKNIX's rocknix-systems, corrected.""" - def __init__(self) -> None: - super().__init__() + def __init__(self, profiles: dict[str, dict] | None = None) -> None: + super().__init__(profiles) self._pairs: set[tuple[str, str]] = set() def _runner_pair(self, runner: tuple[bool, str]) -> tuple[str, str | None] | None: diff --git a/scripts/exporter/romm_exporter.py b/scripts/exporter/romm_exporter.py index 833d8262c..33f92e036 100644 --- a/scripts/exporter/romm_exporter.py +++ b/scripts/exporter/romm_exporter.py @@ -34,8 +34,8 @@ _FIELDS = (("size", "size"), ("crc", "crc32"), ("md5", "md5"), ("sha1", "sha1")) class Exporter(BaseExporter[str]): """Write RomM's known_bios_files.json, corrected.""" - def __init__(self) -> None: - super().__init__() + def __init__(self, profiles: dict[str, dict] | None = None) -> None: + super().__init__(profiles) # (system, filename) keys the platform itself declares, and the # addition that claims each other key first: both set by render. self._platform_keys: set[tuple[str, str]] = set() diff --git a/tests/test_export_counts.py b/tests/test_export_counts.py index f142b1cf1..8cb55d330 100644 --- a/tests/test_export_counts.py +++ b/tests/test_export_counts.py @@ -16,7 +16,6 @@ import unittest from collections import OrderedDict from pathlib import Path -from model.profiles import core_key_index from resolve.reconcile import NativeFile, NativeSystem, Report, build_native_model from exporter.bizhawk_exporter import Exporter as BizHawk from exporter.misterfpga_exporter import Exporter as Mister @@ -672,9 +671,7 @@ class RetroPieProposals(unittest.TestCase): @staticmethod def _knowing(**profiles: dict) -> RetroPie: """An exporter that reads these profiles instead of emulators/.""" - exporter = RetroPie() - exporter._core_profiles = (profiles, core_key_index(profiles, include_aliases=True)) - return exporter + return RetroPie(profiles) @staticmethod def _module(module_id: str, help_text: str) -> dict[str, str]: diff --git a/tests/test_export_report.py b/tests/test_export_report.py index eafc6a0fc..2bfd20b61 100644 --- a/tests/test_export_report.py +++ b/tests/test_export_report.py @@ -18,6 +18,7 @@ from pathlib import Path from exporter import native from exporter.landed import landed_changes from exporter.native import current_truth, export_platform, write_report +from model.profiles import load_emulator_profiles from sitegen.exports import generate_exports_page, load_export_reports ROOT = Path(__file__).resolve().parent.parent @@ -329,7 +330,9 @@ class ReportedChangesAreTheDiff(unittest.TestCase): truth = current_truth(platform, config, str(ROOT / "platforms")) scraped = native_layer(config) systems, report = build_native_model(truth, scraped) - exporter = discover_exporters()[platform]() + exporter = discover_exporters()[platform]( + load_emulator_profiles(str(ROOT / "emulators")) + ) original = original_path.read_text(encoding="utf-8") originals = { p.name: p.read_text(encoding="utf-8") @@ -406,7 +409,9 @@ class ReportedChangesAreTheDiff(unittest.TestCase): truth = current_truth("retropie", config, str(ROOT / "platforms")) scraped = native_layer(config) systems, report = build_native_model(truth, scraped) - exporter = discover_exporters()["retropie"]() + exporter = discover_exporters()["retropie"]( + load_emulator_profiles(str(ROOT / "emulators")) + ) originals = exporter.unpack(archive.read_bytes()) produced = exporter.render(systems, report, originals, scraped) self.assertTrue(produced, "nothing changed, the comparison proves nothing") diff --git a/tests/test_exporters.py b/tests/test_exporters.py index b61f7aa8d..10cf974e6 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -30,9 +30,9 @@ import zipfile from collections import OrderedDict from pathlib import Path -from model.profiles import core_key_index from model.registry import list_registered_platforms from model.platforms import load_platform_config, native_layer +from model.profiles import load_emulator_profiles from model.safeparse import parse_untrusted_xml from exporter import discover_exporters from exporter.base_exporter import BaseExporter @@ -768,7 +768,9 @@ class SearchOrder(unittest.TestCase): cd("jp_mcd1_9112.bin", "japan", 2)] script = ('rp_module_id="lr-picodrive"\nrp_module_help="The Sega CD requires the ' 'BIOS files us_scd1_9210.bin, eu_mcd1_9210.bin copied to $biosdir"\n') - exporter = discover_exporters()["retropie"]() + exporter = discover_exporters()["retropie"]( + {"picodrive": {"type": "libretro", "cores": ["picodrive"]}} + ) # The cap is the longest list RetroPie writes: xm7 names thirteen. longest = ('rp_module_id="xm7"\nrp_module_help="Copy bios files ' + ", ".join(f"n{i}.rom" for i in range(12)) + ' and n12.rom to $biosdir"\n') @@ -806,7 +808,9 @@ class SearchOrder(unittest.TestCase): 'Naomi/Atomiswave BIOS files naomi.zip and awbios.zip to $biosdir/dc"\n') longest = ('rp_module_id="xm7"\nrp_module_help="Copy bios files ' + ", ".join(f"n{i}.rom" for i in range(12)) + ' and n12.rom to $biosdir"\n') - exporter = discover_exporters()["retropie"]() + exporter = discover_exporters()["retropie"]( + {"flycast": {"type": "libretro", "cores": ["flycast"]}} + ) written = exporter.render( systems, None, {"scriptmodules/libretrocores/lr-flycast.sh": script, @@ -1413,7 +1417,11 @@ class RecalboxExport(unittest.TestCase): "_required_by": ["same_cdi"]}, ]}}} systems, report = build_native_model(truth, scraped) - exporter = discover_exporters()["recalbox"]() + exporter = discover_exporters()["recalbox"]({ + "same_cdi": {"type": "libretro", "cores": ["same_cdi"]}, + "mame0278": {"type": "libretro", "cores": ["mame0278"], + "built_by": ["recalbox"]}, + }) produced = exporter.render(systems, report, {}, None)["es_bios.xml"] mandatory = { b.get("path"): b.get("mandatory") for b in ET.fromstring(produced).iter("bios") @@ -1495,8 +1503,7 @@ class RecalboxExport(unittest.TestCase): "built_by": ["recalbox"]}, } systems, _ = build_native_model(truth, scraped) - exporter = discover_exporters()["recalbox"]() - exporter._core_profiles = (profiles, core_key_index(profiles, include_aliases=True)) + exporter = discover_exporters()["recalbox"](profiles) declared = next(fe for s in systems.values() for fe in s.files if fe.platform) self.assertFalse(exporter.required_value(declared)) @@ -1513,8 +1520,7 @@ class RecalboxExport(unittest.TestCase): }]}}} profiles = {"fba2x": {"type": "standalone", "cores": ["fba2x", "pifba"]}} systems, _ = build_native_model(truth, scraped) - exporter = discover_exporters()["recalbox"]() - exporter._core_profiles = (profiles, core_key_index(profiles, include_aliases=True)) + exporter = discover_exporters()["recalbox"](profiles) declared = next(fe for s in systems.values() for fe in s.files if fe.platform) self.assertTrue(exporter.required_value(declared)) @@ -2524,7 +2530,10 @@ class UpstreamFidelity(unittest.TestCase): self.skipTest(f"no cached original for {platform}") scraped = load_platform_config(platform, str(REPO_ROOT / "platforms")) systems, report = build_native_model(truth or {"systems": {}}, scraped) - exporter = discover_exporters()[platform]() + # The profiles the export pipeline hands every exporter. + exporter = discover_exporters()[platform]( + load_emulator_profiles(str(REPO_ROOT / "emulators")) + ) originals: dict[str, str] = {} for path in cache.rglob("*"): if not path.is_file():