From 9a93ccdd70728e68a653cecfa5656fd326089537 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:53:58 +0100 Subject: [PATCH 1/9] refactor: split verify stages into helpers --- scripts/verify.py | 3065 ++++++++++++++++++++++++++------------------- 1 file changed, 1751 insertions(+), 1314 deletions(-) diff --git a/scripts/verify.py b/scripts/verify.py index 2520e4f73..d1d5064b2 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -31,7 +31,9 @@ import os import sys from collections import Counter from collections.abc import Callable, Mapping +from dataclasses import dataclass, field from pathlib import Path +from typing import TYPE_CHECKING, TypedDict import slots @@ -100,7 +102,6 @@ from common import ( system_dir_path, ) -yaml = require_yaml() from exporter.candidates import BIOS, EntryCategories from launchers import LauncherLayer, declared_destinations, held_record, launcher_unproven from cross_reference import launcher_reads_not_held @@ -135,6 +136,13 @@ from validation import ( ) from packpaths import core_save_folder +if TYPE_CHECKING: + from typing_extensions import Unpack + + from packextras import ExtraResolver + +yaml = require_yaml() + DEFAULT_DB = "database.json" DEFAULT_PLATFORMS_DIR = "platforms" DEFAULT_BIOS_DIR = "bios" @@ -219,6 +227,42 @@ def verify_entry_existence( return result +def _verify_zipped_md5( + base: dict, local_path: str, zipped_file: str, md5_list: list[str], +) -> dict: + """The md5 check of an entry naming the ROM inside its ZIP (zipped_file).""" + found_in_zip = False + had_error = False + for md5_candidate in md5_list or [""]: + result = check_inside_zip(local_path, zipped_file, md5_candidate) + if result == Status.OK: + return {**base, "status": Status.OK, "path": local_path} + if result == "error": + had_error = True + elif result != "not_in_zip": + found_in_zip = True + if had_error and not found_in_zip: + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"{local_path} read error", + } + if not found_in_zip: + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"{zipped_file} not found inside ZIP", + } + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"{zipped_file} MD5 mismatch inside ZIP", + } + + def verify_entry_md5( file_entry: dict, local_path: str | None, @@ -254,36 +298,7 @@ def verify_entry_md5( } if zipped_file: - found_in_zip = False - had_error = False - for md5_candidate in md5_list or [""]: - result = check_inside_zip(local_path, zipped_file, md5_candidate) - if result == Status.OK: - return {**base, "status": Status.OK, "path": local_path} - if result == "error": - had_error = True - elif result != "not_in_zip": - found_in_zip = True - if had_error and not found_in_zip: - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"{local_path} read error", - } - if not found_in_zip: - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"{zipped_file} not found inside ZIP", - } - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"{zipped_file} MD5 mismatch inside ZIP", - } + return _verify_zipped_md5(base, local_path, zipped_file, md5_list) if not md5_list: if resolve_status == "hash_mismatch": @@ -497,6 +512,324 @@ def _identity_of(entry: dict) -> dict: } +def _gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: + """The destination a gap entry is keyed and reported at.""" + # One destination rule for the dedup key and for the entry: a + # standalone build without standalone_path falls back on path. + # The key used to skip that fallback, so clk's Acorn/basic.rom and + # Electron/basic.rom both keyed as "basic.rom" under Batocera's + # standalone clk and the second was dropped. + # A file the libretro build reads below the save directory is + # placed there, apart from the system directory the platform + # lays out: no declaration of the BIOS tree answers for it. + if is_standalone: + return f.get("standalone_path") or f.get("path") or fname + if save_root: + return f.get("path") or fname + return system_dir_path(f, f.get("path") or fname) + + +def _region_key(f: dict) -> tuple[str, ...]: + raw_regions = f.get("region") or [] + return tuple( + str(value) for value in ( + raw_regions if isinstance(raw_regions, list) else [raw_regions] + ) + ) + + +SetRecord = tuple[tuple, dict, bool, "tuple[dict, dict | None] | None"] + + +@dataclass +class _GapScan: + """What find_undeclared_files reads and gathers while it walks the cores.""" + + config: dict + db: dict + data_names: set[str] | None + include_all: bool + declared_names: Mapping[str, list[tuple[int | None, str]]] + folded_slots: frozenset[str] + declared_contents: Mapping[str, set[str]] + # Whether the builder drops a file whose local copy contradicts its + # declared hash, which decides if such a copy counts as held here. + shipped_on_mismatch: bool + launcher_layer: LauncherLayer + by_name: dict = field(init=False) + by_name_lower: dict[str, str] = field(init=False) + by_path_suffix: dict = field(init=False) + launcher_candidates: list[tuple[str, bool, dict, dict]] = field(default_factory=list) + # Each grouped requirement met, as (set keys, entry, fills, (reported + # entry, the entry it is a claim on)): settled once every core is read. + set_records: list[SetRecord] = field(default_factory=list) + undeclared: list[dict] = field(default_factory=list) + seen_files: set[tuple] = field(default_factory=set) + # Key -> the entry reported for it. A later profile reading the same + # requirement is kept on that entry rather than counted again: a pack + # built without the first profile still has to name the file. + reported: dict[tuple, dict] = field(default_factory=dict) + # Track archives: archive_name -> {in_repo, emulator, files: [...], ...} + archive_entries: dict[tuple, dict] = field(default_factory=dict) + + def __post_init__(self) -> None: + self.by_name = self.db.get("indexes", {}).get("by_name", {}) + self.by_name_lower = {k.lower(): k for k in self.by_name} + self.by_path_suffix = self.db.get("indexes", {}).get("by_path_suffix", {}) + + def scan_file(self, emu_name: str, layout: dict, is_standalone: bool, f: dict) -> None: + """Consider one profile entry of one build as a gap.""" + fname = f.get("name", "") + save_root = read_from_save_dir(f, is_standalone) + dest = _gap_destination(f, fname, is_standalone, save_root) + region_key = _region_key(f) + # Same-name requirements at different paths, for different systems, + # or in distinct variant groups are not interchangeable. + seen_key = ( + fname, + f.get("archive"), + dest, + f.get("system"), + f.get("selection_slot"), + region_key, + # Below the save directory each core is handed a folder + # of its own: two cores reading hiscore.dat there read + # two files. + ("save", core_save_folder(layout)) if save_root + else (f["root"],) if f.get("root") in OUTER_ROOTS + # In the emulator's own folder: no other core reads it. + else ("emulator", emu_name) if f.get("unplaced") else None, + ) + if not fname or unread_on(f, self.config.get("_key", "")): + return + first = self.reported.get(seen_key) + duplicate = seen_key in self.seen_files + if duplicate and (first is None or first["profile"] == emu_name): + return + outer = save_root or f.get("root") in OUTER_ROOTS + # Nor does it answer for one read below the roms directory. + verdict = _candidate_verdict( + f, fname, is_standalone, self.include_all, + {} if outer else self.declared_names, + dest, self.folded_slots, + None if outer else self.declared_contents, + ) + if verdict == "settled": + self.seen_files.add(seen_key) + if (self.launcher_layer and not f.get("unsourceable") and not outer + and not f.get("unplaced")): + self.launcher_layer.declared_elsewhere(emu_name, is_standalone, f) + # Answered by the platform's own declaration, which its + # report covers: the set it belongs to is spoken for. + self.set_records.append((set_keys((emu_name, is_standalone), f), f, True, None)) + return + if verdict == "skip": + return + + archive = f.get("archive") + self.seen_files.add(seen_key) + + if archive: + self._count_archive_member(emu_name, layout, is_standalone, f, region_key) + return + + in_repo = self._held(emu_name, layout, f, fname, dest) + entry = self._gap_entry(emu_name, layout, f, fname, dest, in_repo, save_root) + if self.launcher_layer and not outer: + # One read outside the BIOS tree is still served where a + # launcher links that very file: RetroDECK links Cemu's + # keys.txt to bios/cemu/keys.txt. + self.launcher_candidates.append((emu_name, is_standalone, f, entry)) + keys = set_keys((emu_name, is_standalone), f) + if duplicate and first is not None: + first.setdefault("other_claims", []).append(entry) + self.set_records.append((keys, f, in_repo, (entry, first))) + return + self.reported[seen_key] = entry + self.undeclared.append(entry) + self.set_records.append((keys, f, in_repo, (entry, None))) + + def _count_archive_member( + self, emu_name: str, layout: dict, is_standalone: bool, f: dict, + region_key: tuple[str, ...], + ) -> None: + archive = f["archive"] + archive_key = ( + archive, + f.get("system_dir"), + f.get("system"), + f.get("selection_slot"), + region_key, + is_standalone, + ) + if archive_key not in self.archive_entries: + in_repo = _name_in_index( + archive, self.by_name, self.by_path_suffix, self.data_names, + self.by_name_lower, + ) + self.archive_entries[archive_key] = { + "profile": emu_name, + "emulator": layout.get("emulator", emu_name), + "systems": entry_system_ids(f, layout), + "system": f.get("system"), + "region": f.get("region"), + "selection_slot": f.get("selection_slot"), + "name": archive, + "archive": archive, + "path": system_dir_path(f, archive), + "required": False, + "hle_fallback": False, + "category": f.get("category", "bios"), + "in_repo": in_repo, + "note": "", + "checks": [], + "source_ref": None, + "expected": {}, + "archive_file_count": 0, + "archive_required_count": 0, + "members": archive_members(archive, layout.get("files", [])), + } + if f.get("system_dir"): + self.archive_entries[archive_key]["system_dir"] = f["system_dir"] + # The archive's own declaration names its sets: an + # archive is a member like a loose file. + own = archive_entry(archive, layout.get("files", [])) + self.archive_entries[archive_key].update(set_fields(own, layout)) + self.set_records.append(( + set_keys((emu_name, is_standalone), own), own, in_repo, + (self.archive_entries[archive_key], None), + )) + entry = self.archive_entries[archive_key] + entry["archive_file_count"] += 1 + if f.get("required", False): + entry["archive_required_count"] += 1 + entry["required"] = True + + def _held(self, emu_name: str, layout: dict, f: dict, fname: str, dest: str) -> bool: + """Whether the collection holds the file as the builder would ship it.""" + # Resolution: name, then path basename + # storage: release names where the bytes are served from, not + # that the collection holds them: resolved like any file. + # Resolved as the asker, as the builder's ExtraResolver does: + # another casing of the name in another emulator's tree is + # not this emulator's file (dosbox-x's et4000.bin and pcem's + # et4000.BIN). + owned = {**f, "source_profile": emu_name} + if self.shipped_on_mismatch and (f.get("md5") or f.get("sha1")): + # The entry states what its content should be and the builder + # drops a copy that contradicts it, so content decides here + # too. A name match would not do: generic names collide across + # systems, and answering yes on one describes a pack that will + # not contain the file. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + return _lp is not None and _st != "hash_mismatch" + in_repo = self._held_by_name(owned, f, fname, dest) + if in_repo and "size" in _parse_validation(f.get("validation")): + # On any platform the core measures what it opens: a + # copy it turns away by its own size check is not + # held for it, the rule the builder's lookup applies + # (packextras.ExtraResolver). The Apple IIGS' 128 KB + # ROM is not Basilisk II's ROM. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + if core_size_refusal( + f, _lp, same_slot_entries(layout.get("files"), fname, dest) + ): + in_repo = False + return in_repo + + def _held_by_name(self, owned: dict, f: dict, fname: str, dest: str) -> bool: + foreign = functools.partial(_in_foreign_tree, self.db, _owner_tokens(owned)) + in_repo = _name_in_index( + fname, self.by_name, self.by_path_suffix, self.data_names, self.by_name_lower, + foreign, + ) + if not in_repo and dest != fname: + path_base = dest.rsplit("/", 1)[-1] + in_repo = _name_in_index( + path_base, self.by_name, self.by_path_suffix, self.data_names, + self.by_name_lower, foreign, + ) + if in_repo and not any( + f.get(h) for h in ("sha1", "md5", "crc32", "sha256") + ): + # A name alone answers nothing when every copy of that + # name fails the size the code checks: the resolver + # rejects them all. NanoBoyAdvance's 16 KB bios.bin met + # only PCem's and QEMU's PC BIOS images of that name. + # The fallback below then decides as for any mismatch. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + if _st == "hash_mismatch": + in_repo = False + if not in_repo: + # Hash fallback: the repo may hold the content under a + # different filename (exos21.rom vs exos21.bin). + # + # A copy contradicting the declared hash counts as held + # only where the builder would ship it. Under existence + # the frontend never opens the file, so the pack carries + # it and reports the divergence. Under a digest mode the + # frontend would reject it, the builder leaves it out, and + # calling it available here would describe a pack that + # does not contain it. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + in_repo = _st != "not_found" and _lp is not None + if in_repo and _st == "hash_mismatch" and self.shipped_on_mismatch: + in_repo = False + return in_repo + + def _gap_entry( + self, emu_name: str, layout: dict, f: dict, fname: str, dest: str, + in_repo: bool, save_root: bool, + ) -> dict: + checks = _parse_validation(f.get("validation")) + entry = { + "profile": emu_name, + "emulator": layout.get("emulator", emu_name), + "systems": entry_system_ids(f, layout), + "system": f.get("system"), + "region": f.get("region"), + "selection_slot": f.get("selection_slot"), + "name": fname, + "path": dest, + "required": f.get("required", False), + "hle_fallback": f.get("hle_fallback", False), + "bundled": installed_with_emulator(f, self.config.get("_key", "")), + "category": f.get("category", "bios"), + "in_repo": in_repo, + "note": f.get("note", ""), + "checks": sorted(checks) if checks else [], + **set_fields(f, layout), + "source_ref": f.get("source_ref"), + "expected": _build_expected(f, checks), + **_identity_of(f), + "sha1": f.get("sha1"), + "md5": f.get("md5"), + } + if f.get("contents"): + entry["contents"] = f["contents"] + if save_root: + entry["root"] = "save" + folder = core_save_folder(layout) + if folder is not None: + entry["core_folder"] = folder + elif f.get("system_dir"): + entry["system_dir"] = f["system_dir"] + members = with_archive_members(f, layout.get("files", [])).get("members") + if members: + entry["members"] = members + if f.get("layout_path"): + entry["layout_path"] = f["layout_path"] + if f.get("unprefixed"): + entry["unprefixed"] = True + if f.get("unplaced"): + entry["unplaced"] = f["unplaced"] + elif f.get("root") in OUTER_ROOTS: + # Read below the roms directory (ROCKNIX's roms/pico-8) + # or in an emulator folder (RetroBat's emulators/pico8). + entry["root"] = f["root"] + return entry + + def find_undeclared_files( config: dict, emulators_dir: str, @@ -518,22 +851,6 @@ def find_undeclared_files( folded_slots = case_folded_slots(config, declared_names) declared_contents = platform_declared_contents(config, db) - # Whether the builder drops a file whose local copy contradicts its - # declared hash, which decides if such a copy counts as held here. - shipped_on_mismatch = hash_mismatch_excludes_file( - config.get("verification_mode") - ) - - declared_dd: set[str] = set() - for sys_id, system in config.get("systems", {}).items(): - for dd in system.get("data_directories", []): - ref = dd.get("ref", "") - if ref: - declared_dd.add(ref) - - by_name = db.get("indexes", {}).get("by_name", {}) - by_name_lower = {k.lower(): k for k in by_name} - by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {}) profiles = ( emu_profiles if emu_profiles is not None @@ -547,18 +864,12 @@ def find_undeclared_files( launcher_layer = LauncherLayer( config, profiles, relevant, db, declared_destinations(config) ) - launcher_candidates: list[tuple[str, bool, dict, dict]] = [] - # Each grouped requirement met, as (set keys, entry, fills, (reported - # entry, the entry it is a claim on)): settled once every core is read. - set_records: list[tuple[tuple, dict, bool, tuple[dict, dict | None] | None]] = [] - undeclared = [] - seen_files: set[tuple] = set() - # Key -> the entry reported for it. A later profile reading the same - # requirement is kept on that entry rather than counted again: a pack - # built without the first profile still has to name the file. - reported: dict[tuple, dict] = {} - # Track archives: archive_name -> {in_repo, emulator, files: [...], ...} - archive_entries: dict[tuple, dict] = {} + scan = _GapScan( + config, db, data_names, include_all, declared_names, folded_slots, + declared_contents, + hash_mismatch_excludes_file(config.get("verification_mode")), + launcher_layer, + ) for emu_name, profile in sorted(profiles.items()): if profile.get("type") in ("launcher", "alias"): @@ -573,271 +884,26 @@ def find_undeclared_files( agnostic = profile.get("bios_mode") == "agnostic" for layout, is_standalone in platform_layouts(emu_name, profile, standalone_set): - for f in expand_directory_entries( layout.get("files", []), db, is_standalone ): if agnostic and not f.get("unplaced"): continue - fname = f.get("name", "") - # One destination rule for the dedup key and for the entry: a - # standalone build without standalone_path falls back on path. - # The key used to skip that fallback, so clk's Acorn/basic.rom and - # Electron/basic.rom both keyed as "basic.rom" under Batocera's - # standalone clk and the second was dropped. - # A file the libretro build reads below the save directory is - # placed there, apart from the system directory the platform - # lays out: no declaration of the BIOS tree answers for it. - save_root = read_from_save_dir(f, is_standalone) - if is_standalone: - dest = f.get("standalone_path") or f.get("path") or fname - elif save_root: - dest = f.get("path") or fname - else: - dest = system_dir_path(f, f.get("path") or fname) - raw_regions = f.get("region") or [] - region_key = tuple( - str(value) for value in ( - raw_regions if isinstance(raw_regions, list) else [raw_regions] - ) - ) - # Same-name requirements at different paths, for different systems, - # or in distinct variant groups are not interchangeable. - seen_key = ( - fname, - f.get("archive"), - dest, - f.get("system"), - f.get("selection_slot"), - region_key, - # Below the save directory each core is handed a folder - # of its own: two cores reading hiscore.dat there read - # two files. - ("save", core_save_folder(layout)) if save_root - else (f["root"],) if f.get("root") in OUTER_ROOTS - # In the emulator's own folder: no other core reads it. - else ("emulator", emu_name) if f.get("unplaced") else None, - ) - if not fname or unread_on(f, config.get("_key", "")): - continue - first = reported.get(seen_key) - duplicate = seen_key in seen_files - if duplicate and (first is None or first["profile"] == emu_name): - continue - # Nor does it answer for one read below the roms directory. - verdict = _candidate_verdict( - f, fname, is_standalone, include_all, - {} if save_root or f.get("root") in OUTER_ROOTS else declared_names, - dest, folded_slots, - None if save_root or f.get("root") in OUTER_ROOTS else declared_contents, - ) - if verdict == "settled": - seen_files.add(seen_key) - if (launcher_layer and not f.get("unsourceable") and not save_root - and f.get("root") not in OUTER_ROOTS and not f.get("unplaced")): - launcher_layer.declared_elsewhere(emu_name, is_standalone, f) - # Answered by the platform's own declaration, which its - # report covers: the set it belongs to is spoken for. - set_records.append((set_keys((emu_name, is_standalone), f), f, True, None)) - continue - if verdict == "skip": - continue - - archive = f.get("archive") - seen_files.add(seen_key) - - if archive: - archive_key = ( - archive, - f.get("system_dir"), - f.get("system"), - f.get("selection_slot"), - region_key, - is_standalone, - ) - if archive_key not in archive_entries: - in_repo = _name_in_index( - archive, by_name, by_path_suffix, data_names, - by_name_lower, - ) - archive_entries[archive_key] = { - "profile": emu_name, - "emulator": layout.get("emulator", emu_name), - "systems": entry_system_ids(f, layout), - "system": f.get("system"), - "region": f.get("region"), - "selection_slot": f.get("selection_slot"), - "name": archive, - "archive": archive, - "path": system_dir_path(f, archive), - "required": False, - "hle_fallback": False, - "category": f.get("category", "bios"), - "in_repo": in_repo, - "note": "", - "checks": [], - "source_ref": None, - "expected": {}, - "archive_file_count": 0, - "archive_required_count": 0, - "members": archive_members(archive, layout.get("files", [])), - } - if f.get("system_dir"): - archive_entries[archive_key]["system_dir"] = f["system_dir"] - # The archive's own declaration names its sets: an - # archive is a member like a loose file. - own = archive_entry(archive, layout.get("files", [])) - archive_entries[archive_key].update(set_fields(own, layout)) - set_records.append(( - set_keys((emu_name, is_standalone), own), own, in_repo, - (archive_entries[archive_key], None), - )) - entry = archive_entries[archive_key] - entry["archive_file_count"] += 1 - if f.get("required", False): - entry["archive_required_count"] += 1 - entry["required"] = True - continue - - # Resolution: name, then path basename - # storage: release names where the bytes are served from, not - # that the collection holds them: resolved like any file. - # Resolved as the asker, as the builder's ExtraResolver does: - # another casing of the name in another emulator's tree is - # not this emulator's file (dosbox-x's et4000.bin and pcem's - # et4000.BIN). - owned = {**f, "source_profile": emu_name} - foreign = functools.partial(_in_foreign_tree, db, _owner_tokens(owned)) - if shipped_on_mismatch and (f.get("md5") or f.get("sha1")): - # The entry states what its content should be and the builder - # drops a copy that contradicts it, so content decides here - # too. A name match would not do: generic names collide across - # systems, and answering yes on one describes a pack that will - # not contain the file. - _lp, _st = resolve_local_file(owned, db, dest_hint=dest) - in_repo = _lp is not None and _st != "hash_mismatch" - else: - in_repo = _name_in_index( - fname, by_name, by_path_suffix, data_names, by_name_lower, - foreign, - ) - if not in_repo and dest != fname: - path_base = dest.rsplit("/", 1)[-1] - in_repo = _name_in_index( - path_base, by_name, by_path_suffix, data_names, - by_name_lower, foreign, - ) - if in_repo and not any( - f.get(h) for h in ("sha1", "md5", "crc32", "sha256") - ): - # A name alone answers nothing when every copy of that - # name fails the size the code checks: the resolver - # rejects them all. NanoBoyAdvance's 16 KB bios.bin met - # only PCem's and QEMU's PC BIOS images of that name. - # The fallback below then decides as for any mismatch. - _lp, _st = resolve_local_file(owned, db, dest_hint=dest) - if _st == "hash_mismatch": - in_repo = False - if not in_repo: - # Hash fallback: the repo may hold the content under a - # different filename (exos21.rom vs exos21.bin). - # - # A copy contradicting the declared hash counts as held - # only where the builder would ship it. Under existence - # the frontend never opens the file, so the pack carries - # it and reports the divergence. Under a digest mode the - # frontend would reject it, the builder leaves it out, and - # calling it available here would describe a pack that - # does not contain it. - _lp, _st = resolve_local_file(owned, db, dest_hint=dest) - in_repo = _st != "not_found" and _lp is not None - if in_repo and _st == "hash_mismatch" and shipped_on_mismatch: - in_repo = False - if in_repo and "size" in _parse_validation(f.get("validation")): - # On any platform the core measures what it opens: a - # copy it turns away by its own size check is not - # held for it, the rule the builder's lookup applies - # (packextras.ExtraResolver). The Apple IIGS' 128 KB - # ROM is not Basilisk II's ROM. - _lp, _st = resolve_local_file(owned, db, dest_hint=dest) - if core_size_refusal( - f, _lp, same_slot_entries(layout.get("files"), fname, dest) - ): - in_repo = False - - checks = _parse_validation(f.get("validation")) - entry = { - "profile": emu_name, - "emulator": layout.get("emulator", emu_name), - "systems": entry_system_ids(f, layout), - "system": f.get("system"), - "region": f.get("region"), - "selection_slot": f.get("selection_slot"), - "name": fname, - "path": dest, - "required": f.get("required", False), - "hle_fallback": f.get("hle_fallback", False), - "bundled": installed_with_emulator(f, config.get("_key", "")), - "category": f.get("category", "bios"), - "in_repo": in_repo, - "note": f.get("note", ""), - "checks": sorted(checks) if checks else [], - **set_fields(f, layout), - "source_ref": f.get("source_ref"), - "expected": _build_expected(f, checks), - **_identity_of(f), - "sha1": f.get("sha1"), - "md5": f.get("md5"), - } - if f.get("contents"): - entry["contents"] = f["contents"] - if save_root: - entry["root"] = "save" - folder = core_save_folder(layout) - if folder is not None: - entry["core_folder"] = folder - elif f.get("system_dir"): - entry["system_dir"] = f["system_dir"] - members = with_archive_members(f, layout.get("files", [])).get("members") - if members: - entry["members"] = members - if f.get("layout_path"): - entry["layout_path"] = f["layout_path"] - if f.get("unprefixed"): - entry["unprefixed"] = True - if f.get("unplaced"): - entry["unplaced"] = f["unplaced"] - elif f.get("root") in OUTER_ROOTS: - # Read below the roms directory (ROCKNIX's roms/pico-8) - # or in an emulator folder (RetroBat's emulators/pico8). - entry["root"] = f["root"] - if launcher_layer and not save_root and f.get("root") not in OUTER_ROOTS: - # One read outside the BIOS tree is still served where a - # launcher links that very file: RetroDECK links Cemu's - # keys.txt to bios/cemu/keys.txt. - launcher_candidates.append((emu_name, is_standalone, f, entry)) - keys = set_keys((emu_name, is_standalone), f) - if duplicate: - first.setdefault("other_claims", []).append(entry) - set_records.append((keys, f, in_repo, (entry, first))) - continue - reported[seen_key] = entry - undeclared.append(entry) - set_records.append((keys, f, in_repo, (entry, None))) + scan.scan_file(emu_name, layout, is_standalone, f) + undeclared = scan.undeclared settled: set[int] = set() if launcher_layer: added, settled = launcher_layer.settle( - launcher_candidates, lambda report: held_record(report, db) + scan.launcher_candidates, lambda report: held_record(report, db) ) undeclared = [u for u in undeclared if id(u) not in settled] undeclared.extend(added) - for entry in sorted(archive_entries.values(), key=lambda e: e["name"]): - undeclared.append(entry) + undeclared.extend(sorted(scan.archive_entries.values(), key=lambda e: e["name"])) return _split_bundled_claims( - _settle_core_sets(undeclared, set_records, settled, profiles) + _settle_core_sets(undeclared, scan.set_records, settled, profiles) ) @@ -1088,36 +1154,44 @@ _HIDDEN_REASONS = { } +@dataclass(frozen=True) +class _BuilderPass: + """The arguments the builder's own pass over the core files is run with.""" + + emulators_dir: str + db: dict + emu_profiles: dict | None + target_cores: set[str] | None + region_drops: set[str] | None + report: list[dict] | None + resolver: ExtraResolver | None + placed_kind: dict[str, str] | None + system_ids: list[str] | None + required_only: bool + + def _mark_hidden( config: dict, undeclared: list[dict], - emulators_dir: str, - db: dict, - emu_profiles: dict | None, shipped: dict[str, str | None], - target_cores: set[str] | None, - region_drops: set[str] | None = None, - report: list[dict] | None = None, - resolver: object | None = None, - placed_kind: dict[str, str] | None = None, - system_ids: list[str] | None = None, - required_only: bool = False, + builder: _BuilderPass, ) -> set[str]: """What the builder holds but cannot place beside the files it packed. Returns the full destinations the builder fills with a core's file. - ``report`` is the gap report the caller already computed with the + ``builder.report`` is the gap report the caller already computed with the builder's arguments. Without it the builder's pass computes its own. """ from packextras import hidden_extras placed: set[str] = set() hidden = hidden_extras( - config, emulators_dir, db, - emu_profiles if emu_profiles is not None - else load_emulator_profiles(emulators_dir), - shipped, target_cores, region_drops, placed, report, resolver, placed_kind, - system_ids=system_ids, required_only=required_only, + config, builder.emulators_dir, builder.db, + builder.emu_profiles if builder.emu_profiles is not None + else load_emulator_profiles(builder.emulators_dir), + shipped, builder.target_cores, builder.region_drops, placed, + report=builder.report, resolver=builder.resolver, placed_kind=builder.placed_kind, + system_ids=builder.system_ids, required_only=builder.required_only, ) for u in undeclared: reason = hidden.get( @@ -1193,10 +1267,25 @@ def _twin_index( return preferred_entries, winners +@dataclass(frozen=True) +class _DeclarationResolver: + """How a platform run resolves its declarations, as the builder does.""" + + db: dict + zip_contents: dict + data_dir_registry: dict | None + slot_overrides: dict[str, str] + mode: str + platform_profiles: dict + # Which declaration the pack ships at each destination, and every + # declaration by id (_twin_index). + preferred_entries: dict[str, int] + winners: dict[int, tuple[str, dict]] + base_dest: str + + def _resolve_declaration( - file_entry: dict, sys_id: str, twins: tuple, db: dict, zip_contents: dict, - data_dir_registry: dict | None, slot_overrides: dict, mode: str, - platform_profiles: dict, + file_entry: dict, sys_id: str, resolver: _DeclarationResolver, ) -> tuple[str | None, str, str | None]: """Resolve a declaration to the file the pack ships at its destination. @@ -1204,15 +1293,16 @@ def _resolve_declaration( returned and the evidence reset: the winner's hash match is not this declaration's, which is hashed against the shipped file. """ - preferred_entries, winners, base_dest = twins + base_dest = resolver.base_dest bare = sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) - preferred = preferred_entries.get(f"{base_dest}/{bare}" if base_dest else bare) + preferred = resolver.preferred_entries.get(f"{base_dest}/{bare}" if base_dest else bare) held_by, winner = (None, file_entry) if preferred is not None and preferred != id(file_entry): - held_by, winner = winners[preferred] + held_by, winner = resolver.winners[preferred] local_path, resolve_status = _resolve_for_platform( - winner, held_by or sys_id, db, zip_contents, data_dir_registry, - slot_overrides, mode, platform_profiles, + winner, held_by or sys_id, resolver.db, resolver.zip_contents, + resolver.data_dir_registry, resolver.slot_overrides, resolver.mode, + resolver.platform_profiles, ) return local_path, "" if held_by else resolve_status, held_by @@ -1290,6 +1380,432 @@ def _resolve_for_platform( return local_path, status +class PackNarrowing(TypedDict, total=False): + """The narrowings of a platform pack that verify_platform reports on.""" + + regions: list[str] | None + system_filter: list[str] | None + no_game_data: bool + required_only: bool + + +@dataclass(frozen=True) +class _PlatformRun: + """The inputs of one verify_platform run, read by each of its stages.""" + + config: dict + db: dict + emulators_dir: str + emu_profiles: dict | None + profiles: dict + target_cores: set[str] | None + data_dir_registry: dict | None + zip_contents: dict + system_filter: list[str] | None + required_only: bool + mode: str + base_dest: str + + def full(self, destination: str) -> str: + return f"{self.base_dest}/{destination}" if self.base_dest else destination + + +@dataclass +class _PlatformTally: + """Each declaration's verdict, and the verdicts aggregated by destination.""" + + run: _PlatformRun + platform: str + resolver: _DeclarationResolver + region_drops: set[str] + validation_index: dict + validation_owners: dict[str, list[tuple[str, str]]] + hle_index: dict[str, bool] + categories: EntryCategories + details: list[dict] = field(default_factory=list) + file_status: dict[str, str] = field(default_factory=dict) + file_required: dict[str, bool] = field(default_factory=dict) + file_severity: dict[str, str] = field(default_factory=dict) + # What each entry is: firmware, a game's data, or a name no core the + # platform runs opens. Only firmware gaps carry a severity. + file_category: dict[str, str] = field(default_factory=dict) + # (system, full destination, local copy) of each declaration the builder + # writes, and None for one whose slot it keeps without a file from the + # collection (user_provided, external). Placed below in the builder's order. + packed_order: list[tuple[str, str, str | None]] = field(default_factory=list) + shipped_keys: set[str] = field(default_factory=set) + results_at: dict[str, list[dict]] = field(default_factory=dict) + + def judge(self, sys_id: str, file_entry: dict) -> None: + """Verify one declaration and add it to its destination's tally.""" + destination = sanitize_pack_path( + file_entry.get("destination", file_entry.get("name", "")) + ) + if self.region_drops and destination in self.region_drops: + return + local_path, resolve_status, held_by = _resolve_declaration( + file_entry, sys_id, self.resolver, + ) + result, local_path = self._verdict( + file_entry, sys_id, local_path, resolve_status, destination, + ) + result["system"] = sys_id + result["hle_fallback"] = self.hle_index.get(file_entry.get("name", ""), False) + result["ground_truth"] = build_ground_truth( + file_entry.get("name", ""), + self.validation_index, + ) + self.details.append(result) + config = self.run.config + # Occupied only where the builder ships the declaration: a hash + # the frontend refuses is left out, and the destination stays free + # for a core's file the pack does carry. + if ( + local_path + and result["status"] != Status.MISSING + and baseline_verdict( + file_entry, local_path, resolve_status, self.run.mode, + config.get("hash_rule", ""), + )[1] is None + ): + self.packed_order.append((sys_id, self.run.full(destination), local_path)) + self.shipped_keys.add(_dest_key(file_entry, sys_id)) + if _twin_unmet( + result, held_by, file_entry, sys_id, self.run.full(destination), + ): + return + self._aggregate(sys_id, file_entry, destination, result) + + def _verdict( + self, file_entry: dict, sys_id: str, local_path: str | None, + resolve_status: str, destination: str, + ) -> tuple[dict, str | None]: + """The declaration's result, and the local copy the pack writes for it.""" + config = self.run.config + mode = self.run.mode + stored = _storage_verdict(file_entry, emulator_pack=False) + if resolve_status == RELEASE_ASSET_PENDING: + # Counted as an online build counts it, which fetches the + # asset. Under --offline the builder cannot, and neither + # does this report (_resolve_for_platform). + result = { + "name": file_entry.get("name", ""), + "required": file_entry.get("required", True), + "status": Status.OK, + "release_asset": local_path, + "reason": "release asset, fetched when the pack is built", + } + # Written at its path like any held file: keyed to None, it + # stayed out of pack_destinations and step 5 read the pack's + # copy as a file only the pack holds. + self.packed_order.append((sys_id, self.run.full(destination), local_path)) + self.shipped_keys.add(_dest_key(file_entry, sys_id)) + return result, None + if stored is not None: + # The builder keeps the slot: instructions for a user_provided + # file, the download for an external one, whether it arrives + # or not. No core file goes there. + self.packed_order.append((sys_id, self.run.full(destination), None)) + return stored, None + if not reads_file_contents(mode): + return verify_entry_existence( + file_entry, + local_path, + self.validation_index, + self.run.db, + destination, + self.validation_owners, + resolve_status, + config.get("platform", ""), + ), local_path + if digest_algorithm(mode) == "sha1": + return verify_entry_sha1(file_entry, local_path), local_path + result = verify_entry_md5( + file_entry, local_path, resolve_status, config.get("hash_rule", "") + ) + # Emulator-level validation: informational for platform packs. + # Platform verification (MD5) is the authority. Emulator + # mismatches are reported as discrepancies, not failures. + if result["status"] == Status.OK: + _chosen, disagreement = validated_choice( + file_entry, local_path, self.run.db, self.validation_index, "bios", + digest_algorithm(mode), destination, self.validation_owners, + ) + if disagreement: + result["discrepancy"] = f"{self.platform} says OK but {disagreement}" + return result, local_path + + def _aggregate( + self, sys_id: str, file_entry: dict, destination: str, result: dict, + ) -> None: + # Aggregate by destination, keyed as the builder keys its pack. + # A declaration that finds nothing leaves the path to one that + # holds a file: the builder packs that file there, whatever the + # order the two are read in. + dest = _dest_key(file_entry, sys_id) + self.results_at.setdefault(dest, []).append(result) + required = file_entry.get("required", True) + cur = result["status"] + prev = self.file_status.get(dest) + hle = self.hle_index.get(file_entry.get("name", ""), False) + sev = compute_severity(cur, required, self.run.mode, hle) + explained = self.categories.explain(file_entry, destination, sys_id) + category = explained.pop("category") + result["category"] = category + result["category_evidence"] = explained + if cur != Status.MISSING: + # A held entry is firmware for the counts: its category only + # documents it. + category = BIOS + if self.file_category.get(dest, category) == BIOS: + category = BIOS + self.file_category[dest] = category + if prev is not None and (cur == Status.MISSING) != (prev == Status.MISSING): + if cur == Status.MISSING: + return + del self.file_status[dest], self.file_severity[dest] + prev = None + if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(prev, 0): + self.file_status[dest] = cur + self.file_required[dest] = required + prev_sev = self.file_severity.get(dest) + if prev_sev is None or _SEVERITY_ORDER.get(sev, 0) > _SEVERITY_ORDER.get( + prev_sev, 0 + ): + self.file_severity[dest] = sev + + def settle_groups(self) -> None: + """RetroBat's group: one file of it held is enough, and the others are + reported OPTIONAL (batocera-systems/Program.cs). None held, each stays + required.""" + members: dict[tuple[str, str], list[str]] = {} + for sys_id, system in self.run.config.get("systems", {}).items(): + for file_entry in system.get("files", []): + if file_entry.get("group"): + dest = _dest_key(file_entry, sys_id) + if dest in self.file_status: + members.setdefault((sys_id, file_entry["group"]), []).append(dest) + for dests in members.values(): + if not any(self.file_status[d] == Status.OK for d in dests): + continue + for dest in dests: + if self.file_status[dest] == Status.MISSING: + self.file_required[dest] = False + self.file_severity[dest] = compute_severity( + Status.MISSING, False, self.run.mode + ) + for result in self.results_at.get(dest, []): + result["required"] = False + + def credit_placed(self, placed: set[str]) -> None: + """An existence frontend is satisfied by any file at the path, and the + builder fills a free platform destination with a core's file.""" + for dest, status in self.file_status.items(): + if status == Status.MISSING and self.run.full(dest) in placed: + self.file_status[dest] = Status.OK + self.file_severity[dest] = Severity.OK + for result in self.results_at.get(dest, []): + result["status"] = Status.OK + + def severity_counts(self) -> tuple[dict[str, int], dict[str, list[str]]]: + """Destinations by severity, and the missing ones that are not firmware.""" + counts = { + Severity.OK: 0, + Severity.INFO: 0, + Severity.WARNING: 0, + Severity.CRITICAL: 0, + } + not_firmware: dict[str, list[str]] = {} + for dest, s in self.file_severity.items(): + category = self.file_category.get(dest, BIOS) + if category != BIOS and self.file_status.get(dest) == Status.MISSING: + not_firmware.setdefault(category, []).append(dest) + continue + counts[s] = counts.get(s, 0) + 1 + return counts, not_firmware + + +def _refuse_unknown_narrowings(narrowing: Mapping[str, object]) -> None: + unknown = [key for key in narrowing if key not in PackNarrowing.__annotations__] + if unknown: + raise TypeError( + f"verify_platform() got an unexpected keyword argument '{unknown[0]}'" + ) + + +def _cut_game_data( + config: dict, + emu_profiles: dict | None, + emulators_dir: str, + data_dir_registry: dict | None, + target_cores: set[str] | None, + system_filter: list[str] | None, +) -> tuple[dict, dict, list[str]]: + """The config and profiles of a --no-game-data pack, and what it leaves out.""" + from gamedata import without_game_data + + if emu_profiles is None: + emu_profiles = load_emulator_profiles(emulators_dir) + cut = without_game_data(config, emu_profiles, data_dir_registry, target_cores) + config, emu_profiles = cut.config, cut.profiles + systems = config.get("systems", {}) + in_scope = set(select_systems(systems, system_filter) if system_filter else systems) + cut.left_out = [ + item for item in cut.left_out + if item.layer == "core" or item.system in in_scope + ] + return config, emu_profiles, cut.report_lines() + + +def _required_declarations(verify_systems: dict) -> dict: + return { + sys_id: { + **system, + "files": [ + fe for fe in system.get("files", []) if fe.get("required") is not False + ], + } + for sys_id, system in verify_systems.items() + } + + +def _region_pass( + run: _PlatformRun, verify_systems: dict, pack_overrides: dict, regions: list[str], +) -> tuple[set[str], list[str], dict[tuple[str, str, str], str]]: + """The destinations a region run withdraws, the groups no file answers, + and the destination of each core extra.""" + import region as region_mod + + # The builder owns pack composition, so it owns the grouping the region + # pass reads. Grouping the platform files here and the core extras + # there let the two answer differently on one request: the report kept + # every core extra a region run withdraws from the pack. + from packextras import platform_region_groups + + config = run.config + held: set[str] = set() + region_groups, region_extra_dests = platform_region_groups( + config, + verify_systems, + run.emulators_dir, + run.db, + config.get("base_destination", ""), + run.profiles, + target_cores=run.target_cores, + required_only=run.required_only, + held_out=held, + zip_contents=run.zip_contents, + data_registry=run.data_dir_registry, + slot_overrides=pack_overrides, + ) + region_index = region_mod.platform_region_index(config, run.profiles, run.target_cores) + region_drops = region_mod.resolve_region_drops( + region_groups, region_index, regions, held, + ) + # The pack README names these: no file answers the request, so every + # candidate stays. Reported here too, or verify reads all OK for a + # system that has no BIOS for the region asked. + region_fallbacks = region_mod.fallback_groups( + region_groups, region_index, regions + ) + return region_drops, region_fallbacks, region_extra_dests + + +def _platform_gaps( + run: _PlatformRun, + occupied: dict[str, str | None], + region_drops: set[str], + region_extra_dests: dict[tuple[str, str, str], str], + validation_index: dict, + validation_owners: dict[str, list[tuple[str, str]]], +) -> tuple[list[dict], set[str], dict[str, str]]: + """The core files of the pack: the gap report as the builder narrows it, + the destinations it fills, and the category of each.""" + config = run.config + # Cross-reference undeclared files, called exactly as the builder calls + # it: its declarations, not the enriched ones (a core file the platform + # also declares under another name is packed at the core's own path, 21 + # such files in the RetroArch pack), and no names from inside archives + # or data trees (a loose file whose name exists only as a member of + # naomi2.zip was counted "in pack" while the builder shipped nothing). + undeclared = find_undeclared_files( + config, + run.emulators_dir, + run.db, + run.emu_profiles, + target_cores=run.target_cores, + declared_names=platform_declarations(config, run.db, enrich=False), + ) + # The builder's own pass reads the same report: computed once here and + # handed over as it stands now, before the markings below. + report_for_builder = [dict(u) for u in undeclared] + if run.system_filter: + # A system pack carries the extras its systems own. + from packextras import report_owned_by_systems + + undeclared = report_owned_by_systems(undeclared, run.system_filter) + if run.required_only: + undeclared = [u for u in undeclared if u.get("required") is not False] + if region_drops: + undeclared = [ + u + for u in undeclared + if region_extra_dests.get( + (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") + ) + not in region_drops + ] + if run.required_only: + # One member of a required set, as the builder keeps it. + spares = core_file_spares(undeclared) + undeclared = [u for u in undeclared if id(u) not in spares] + _mark_unplaced(config, undeclared, run.profiles) + from packextras import ExtraResolver + + placed_kind: dict[str, str] = {} + placed = _mark_hidden(config, undeclared, occupied, _BuilderPass( + run.emulators_dir, run.db, run.emu_profiles, run.target_cores, region_drops, + report_for_builder, + ExtraResolver( + run.db, DEFAULT_BIOS_DIR, run.zip_contents, run.data_dir_registry, + validation_index, validation_owners, profiles=run.profiles, + pending_assets=True, + ), + placed_kind, + run.system_filter, + run.required_only, + )) + return undeclared, placed, placed_kind + + +def _profile_coverage( + profiles: dict, verify_systems: dict, file_status: dict[str, str], + validation_index: dict, +) -> tuple[int, int]: + """Destinations whose file a core validates, and those a profile names.""" + gt_filenames = set(validation_index) + profiled_names: set[str] = set() + for profile in profiles.values(): + if profile.get("type") in ("launcher", "alias"): + continue + for f in profile.get("files", []): + name = f.get("name", "") + if name: + profiled_names.add(name) + profiled_names.update(f.get("aliases") or []) + dest_to_name: dict[str, str] = {} + for sys_id, system in verify_systems.items(): + for fe in system.get("files", []): + dest_to_name.setdefault(_dest_key(fe, sys_id), fe.get("name", "")) + with_validation = sum( + 1 for dest in file_status if dest_to_name.get(dest, "") in gt_filenames + ) + with_profile = sum( + 1 for dest in file_status if dest_to_name.get(dest, "") in profiled_names + ) + return with_validation, with_profile + + def verify_platform( config: dict, db: dict, @@ -1297,10 +1813,7 @@ def verify_platform( emu_profiles: dict | None = None, target_cores: set[str] | None = None, data_dir_registry: dict | None = None, - regions: list[str] | None = None, - system_filter: list[str] | None = None, - no_game_data: bool = False, - required_only: bool = False, + **narrowing: Unpack[PackNarrowing], ) -> dict: """Verify all BIOS files for a platform, including cross-reference gaps. @@ -1315,21 +1828,17 @@ def verify_platform( declarations, trees and core extras marked ``required: false`` are left out before any of them takes a path, as the builder leaves them out. """ + _refuse_unknown_narrowings(narrowing) + regions = narrowing.get("regions") + system_filter = narrowing.get("system_filter") + no_game_data = narrowing.get("no_game_data", False) + required_only = narrowing.get("required_only", False) left_out: list[str] = [] if no_game_data: - from gamedata import without_game_data - - if emu_profiles is None: - emu_profiles = load_emulator_profiles(emulators_dir) - cut = without_game_data(config, emu_profiles, data_dir_registry, target_cores) - config, emu_profiles = cut.config, cut.profiles - systems = config.get("systems", {}) - in_scope = set(select_systems(systems, system_filter) if system_filter else systems) - cut.left_out = [ - item for item in cut.left_out - if item.layer == "core" or item.system in in_scope - ] - left_out = cut.report_lines() + config, emu_profiles, left_out = _cut_game_data( + config, emu_profiles, emulators_dir, data_dir_registry, target_cores, + system_filter, + ) # Normalized once: a typo in a platform YAML must not verify with one # mode and be scored with another. mode = normalize_mode(config.get("verification_mode")) @@ -1381,291 +1890,48 @@ def verify_platform( verify_systems = platform_scope_systems(config, profiles, target_cores, system_filter) if required_only: - verify_systems = { - sys_id: { - **system, - "files": [ - fe for fe in system.get("files", []) if fe.get("required") is not False - ], - } - for sys_id, system in verify_systems.items() - } + verify_systems = _required_declarations(verify_systems) - details = [] - file_status: dict[str, str] = {} - file_required: dict[str, bool] = {} - file_severity: dict[str, str] = {} - # What each entry is: firmware, a game's data, or a name no core the - # platform runs opens. Only firmware gaps carry a severity. - file_category: dict[str, str] = {} categories = EntryCategories(config, profiles, data_dir_registry) + run = _PlatformRun( + config, db, emulators_dir, emu_profiles, profiles, target_cores, + data_dir_registry, zip_contents, system_filter, required_only, mode, base_dest, + ) region_drops: set[str] = set() region_fallbacks: list[str] = [] region_extra_dests: dict[tuple[str, str, str], str] = {} if regions: - import region as region_mod - - # The builder owns pack composition, so it owns the grouping the region - # pass reads. Grouping the platform files here and the core extras - # there let the two answer differently on one request: the report kept - # every core extra a region run withdraws from the pack. - from packextras import platform_region_groups - - held: set[str] = set() - region_groups, region_extra_dests = platform_region_groups( - config, - verify_systems, - emulators_dir, - db, - config.get("base_destination", ""), - profiles, - target_cores=target_cores, - required_only=required_only, - held_out=held, - zip_contents=zip_contents, - data_registry=data_dir_registry, - slot_overrides=pack_overrides, - ) - region_index = region_mod.platform_region_index(config, profiles, target_cores) - region_drops = region_mod.resolve_region_drops( - region_groups, region_index, regions, held, - ) - # The pack README names these: no file answers the request, so every - # candidate stays. Reported here too, or verify reads all OK for a - # system that has no BIOS for the region asked. - region_fallbacks = region_mod.fallback_groups( - region_groups, region_index, regions + region_drops, region_fallbacks, region_extra_dests = _region_pass( + run, verify_systems, pack_overrides, regions, ) # A destination two systems declare with two hashes ships one file, the # one the builder prefers. The other declaration is scored against that # file, as the frontend will score it after installation: RetroDECK's # xroar component hashes bios/disk.rom and finds the PC-88 ROM. - base_dest = config.get("base_destination", "") preferred_entries, winners = _twin_index( verify_systems, db, base_dest, zip_contents ) - - # (system, full destination, local copy) of each declaration the builder - # writes, and None for one whose slot it keeps without a file from the - # collection (user_provided, external). Placed below in the builder's order. - packed_order: list[tuple[str, str, str | None]] = [] - shipped_keys: set[str] = set() - results_at: dict[str, list[dict]] = {} + tally = _PlatformTally( + run, platform, + _DeclarationResolver( + db, zip_contents, data_dir_registry, slot_overrides, mode, + platform_profiles, preferred_entries, winners, base_dest, + ), + region_drops, validation_index, validation_owners, hle_index, categories, + ) for sys_id, system in verify_systems.items(): for file_entry in system.get("files", []): - if region_drops and ( - sanitize_pack_path( - file_entry.get("destination", file_entry.get("name", "")) - ) - in region_drops - ): - continue - local_path, resolve_status, held_by = _resolve_declaration( - file_entry, sys_id, (preferred_entries, winners, base_dest), - db, zip_contents, data_dir_registry, slot_overrides, mode, - platform_profiles, - ) - destination = sanitize_pack_path( - file_entry.get("destination", file_entry.get("name", "")) - ) - stored = _storage_verdict(file_entry, emulator_pack=False) - if resolve_status == RELEASE_ASSET_PENDING: - # Counted as an online build counts it, which fetches the - # asset. Under --offline the builder cannot, and neither - # does this report (_resolve_for_platform). - result = { - "name": file_entry.get("name", ""), - "required": file_entry.get("required", True), - "status": Status.OK, - "release_asset": local_path, - "reason": "release asset, fetched when the pack is built", - } - # Written at its path like any held file: keyed to None, it - # stayed out of pack_destinations and step 5 read the pack's - # copy as a file only the pack holds. - packed_order.append(( - sys_id, f"{base_dest}/{destination}" if base_dest else destination, - local_path, - )) - shipped_keys.add(_dest_key(file_entry, sys_id)) - local_path = None - elif stored is not None: - result = stored - local_path = None - # The builder keeps the slot: instructions for a user_provided - # file, the download for an external one, whether it arrives - # or not. No core file goes there. - packed_order.append(( - sys_id, f"{base_dest}/{destination}" if base_dest else destination, None, - )) - elif not reads_file_contents(mode): - result = verify_entry_existence( - file_entry, - local_path, - validation_index, - db, - destination, - validation_owners, - resolve_status, - config.get("platform", ""), - ) - elif digest_algorithm(mode) == "sha1": - result = verify_entry_sha1(file_entry, local_path) - else: - result = verify_entry_md5( - file_entry, local_path, resolve_status, config.get("hash_rule", "") - ) - # Emulator-level validation: informational for platform packs. - # Platform verification (MD5) is the authority. Emulator - # mismatches are reported as discrepancies, not failures. - if result["status"] == Status.OK: - _chosen, disagreement = validated_choice( - file_entry, local_path, db, validation_index, "bios", - digest_algorithm(mode), destination, validation_owners, - ) - if disagreement: - result["discrepancy"] = f"{platform} says OK but {disagreement}" - result["system"] = sys_id - result["hle_fallback"] = hle_index.get(file_entry.get("name", ""), False) - result["ground_truth"] = build_ground_truth( - file_entry.get("name", ""), - validation_index, - ) - details.append(result) - # Occupied only where the builder ships the declaration: a hash - # the frontend refuses is left out, and the destination stays free - # for a core's file the pack does carry. - if ( - local_path - and result["status"] != Status.MISSING - and baseline_verdict( - file_entry, local_path, resolve_status, mode, config.get("hash_rule", "") - )[1] is None - ): - packed_order.append(( - sys_id, - f"{base_dest}/{destination}" if base_dest else destination, - local_path, - )) - shipped_keys.add(_dest_key(file_entry, sys_id)) - if _twin_unmet( - result, held_by, file_entry, sys_id, - f"{base_dest}/{destination}" if base_dest else destination, - ): - continue - - # Aggregate by destination, keyed as the builder keys its pack. - # A declaration that finds nothing leaves the path to one that - # holds a file: the builder packs that file there, whatever the - # order the two are read in. - dest = _dest_key(file_entry, sys_id) - results_at.setdefault(dest, []).append(result) - required = file_entry.get("required", True) - cur = result["status"] - prev = file_status.get(dest) - hle = hle_index.get(file_entry.get("name", ""), False) - sev = compute_severity(cur, required, mode, hle) - explained = categories.explain(file_entry, destination, sys_id) - category = explained.pop("category") - result["category"] = category - result["category_evidence"] = explained - if cur != Status.MISSING: - # A held entry is firmware for the counts: its category only - # documents it. - category = BIOS - if file_category.get(dest, category) == BIOS: - category = BIOS - file_category[dest] = category - if prev is not None and (cur == Status.MISSING) != (prev == Status.MISSING): - if cur == Status.MISSING: - continue - del file_status[dest], file_severity[dest] - prev = None - if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(prev, 0): - file_status[dest] = cur - file_required[dest] = required - prev_sev = file_severity.get(dest) - if prev_sev is None or _SEVERITY_ORDER.get(sev, 0) > _SEVERITY_ORDER.get( - prev_sev, 0 - ): - file_severity[dest] = sev - - # RetroBat's group: one file of it held is enough, and the others are - # reported OPTIONAL (batocera-systems/Program.cs). None held, each stays - # required. - members: dict[tuple[str, str], list[str]] = {} - for sys_id, system in config.get("systems", {}).items(): - for file_entry in system.get("files", []): - if file_entry.get("group"): - dest = _dest_key(file_entry, sys_id) - if dest in file_status: - members.setdefault((sys_id, file_entry["group"]), []).append(dest) - for dests in members.values(): - if any(file_status[d] == Status.OK for d in dests): - for dest in dests: - if file_status[dest] == Status.MISSING: - file_required[dest] = False - file_severity[dest] = compute_severity(Status.MISSING, False, mode) - for result in results_at.get(dest, []): - result["required"] = False + tally.judge(sys_id, file_entry) + tally.settle_groups() shipped, occupied = _builder_placement( - packed_order, bool(config.get("case_insensitive_fs", False)) + tally.packed_order, bool(config.get("case_insensitive_fs", False)) ) - - # Cross-reference undeclared files, called exactly as the builder calls - # it: its declarations, not the enriched ones (a core file the platform - # also declares under another name is packed at the core's own path, 21 - # such files in the RetroArch pack), and no names from inside archives - # or data trees (a loose file whose name exists only as a member of - # naomi2.zip was counted "in pack" while the builder shipped nothing). - undeclared = find_undeclared_files( - config, - emulators_dir, - db, - emu_profiles, - target_cores=target_cores, - declared_names=platform_declarations(config, db, enrich=False), - ) - # The builder's own pass reads the same report: computed once here and - # handed over as it stands now, before the markings below. - report_for_builder = [dict(u) for u in undeclared] - if system_filter: - # A system pack carries the extras its systems own. - from packextras import report_owned_by_systems - - undeclared = report_owned_by_systems(undeclared, system_filter) - if required_only: - undeclared = [u for u in undeclared if u.get("required") is not False] - if region_drops: - undeclared = [ - u - for u in undeclared - if region_extra_dests.get( - (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") - ) - not in region_drops - ] - if required_only: - # One member of a required set, as the builder keeps it. - spares = core_file_spares(undeclared) - undeclared = [u for u in undeclared if id(u) not in spares] - _mark_unplaced(config, undeclared, profiles) - from packextras import ExtraResolver - - placed_kind: dict[str, str] = {} - placed = _mark_hidden( - config, undeclared, emulators_dir, db, emu_profiles, occupied, target_cores, - region_drops, report_for_builder, - ExtraResolver( - db, DEFAULT_BIOS_DIR, zip_contents, data_dir_registry, validation_index, - validation_owners, profiles=profiles, pending_assets=True, - ), - placed_kind, - system_filter, - required_only, + undeclared, placed, placed_kind = _platform_gaps( + run, occupied, region_drops, region_extra_dests, validation_index, + validation_owners, ) # What the builder places from the cores, one per pack path, by category: # several entries claim one path (rom.key from three Amiga cores) and the @@ -1675,36 +1941,17 @@ def verify_platform( for category in placed_kind.values(): packed_extras["game_data" if category == "game_data" else "bios"] += 1 if not reads_file_contents(mode): - # An existence frontend is satisfied by any file at the path, and the - # builder fills a free platform destination with a core's file. - for dest, status in file_status.items(): - full = f"{base_dest}/{dest}" if base_dest else dest - if status == Status.MISSING and full in placed: - file_status[dest] = Status.OK - file_severity[dest] = Severity.OK - for result in results_at.get(dest, []): - result["status"] = Status.OK + tally.credit_placed(placed) - counts = { - Severity.OK: 0, - Severity.INFO: 0, - Severity.WARNING: 0, - Severity.CRITICAL: 0, - } - not_firmware: dict[str, list[str]] = {} - for dest, s in file_severity.items(): - category = file_category.get(dest, BIOS) - if category != BIOS and file_status.get(dest) == Status.MISSING: - not_firmware.setdefault(category, []).append(dest) - continue - counts[s] = counts.get(s, 0) + 1 + counts, not_firmware = tally.severity_counts() + file_status = tally.file_status # Held but refused: on a hash platform the builder leaves out a file whose # declared hash the local copy contradicts. Counted apart, so a coverage # figure never calls present what the pack does not carry. excluded = sorted( dest for dest, status in file_status.items() - if status == Status.UNTESTED and dest not in shipped_keys + if status == Status.UNTESTED and dest not in tally.shipped_keys ) # Count by file status (ok/untested/missing) @@ -1716,25 +1963,8 @@ def verify_platform( config, emulators_dir, emu_profiles, target_cores=target_cores ) - gt_filenames = set(validation_index) - profiled_names: set[str] = set() - for profile in profiles.values(): - if profile.get("type") in ("launcher", "alias"): - continue - for f in profile.get("files", []): - name = f.get("name", "") - if name: - profiled_names.add(name) - profiled_names.update(f.get("aliases") or []) - dest_to_name: dict[str, str] = {} - for sys_id, system in verify_systems.items(): - for fe in system.get("files", []): - dest_to_name.setdefault(_dest_key(fe, sys_id), fe.get("name", "")) - with_validation = sum( - 1 for dest in file_status if dest_to_name.get(dest, "") in gt_filenames - ) - with_profile = sum( - 1 for dest in file_status if dest_to_name.get(dest, "") in profiled_names + with_validation, with_profile = _profile_coverage( + profiles, verify_systems, file_status, validation_index, ) total = len(file_status) @@ -1778,7 +2008,7 @@ def verify_platform( key for key, entry in (data_dir_registry or {}).items() if not os.path.isdir(entry.get("local_cache", "")) ), - "details": details, + "details": tally.details, "ground_truth_coverage": { "with_validation": with_validation, "with_profile": with_profile, @@ -1896,41 +2126,57 @@ def _print_category_evidence(detail: dict) -> None: def _print_detail_entries(details: list[dict], seen: set[str], verbose: bool) -> None: """Print UNTESTED, MISSING, and DISCREPANCY entries from verification details.""" + _print_untested_details(details, seen, verbose) + _print_missing_details(details, seen, verbose) + _print_discrepancy_details(details, seen, verbose) + if verbose: + _print_ok_details(details, seen) + + +def _print_untested_details(details: list[dict], seen: set[str], verbose: bool) -> None: for d in details: - if d["status"] == Status.UNTESTED: - if d.get("discrepancy"): - # Reported below with the ground for it: a declaration - # unmet at a path another declaration holds. - continue - key = f"{d['system']}/{d['name']}" - if key in seen: - continue - seen.add(key) - req = "required" if d.get("required", True) else "optional" - hle = ", HLE available" if d.get("hle_fallback") else "" - reason = d.get("reason", "") - print(f" UNTESTED ({req}{hle}): {key}: {reason}") - _print_ground_truth(d.get("ground_truth", []), verbose) + if d["status"] != Status.UNTESTED: + continue + if d.get("discrepancy"): + # Reported below with the ground for it: a declaration + # unmet at a path another declaration holds. + continue + key = f"{d['system']}/{d['name']}" + if key in seen: + continue + seen.add(key) + req = "required" if d.get("required", True) else "optional" + hle = ", HLE available" if d.get("hle_fallback") else "" + reason = d.get("reason", "") + print(f" UNTESTED ({req}{hle}): {key}: {reason}") + _print_ground_truth(d.get("ground_truth", []), verbose) + + +def _print_missing_details(details: list[dict], seen: set[str], verbose: bool) -> None: for d in details: - if d["status"] == Status.MISSING: - key = f"{d['system']}/{d['name']}" - if key in seen: - continue - label = _NOT_FIRMWARE.get(d.get("category", BIOS)) - if label: - # Counted on their own line, named on request. - if verbose: - seen.add(key) - print(f" MISSING ({label}): {key}") - _print_category_evidence(d) - continue - seen.add(key) - req = "required" if d.get("required", True) else "optional" - hle = ", HLE available" if d.get("hle_fallback") else "" - print(f" MISSING ({req}{hle}): {key}") + if d["status"] != Status.MISSING: + continue + key = f"{d['system']}/{d['name']}" + if key in seen: + continue + label = _NOT_FIRMWARE.get(d.get("category", BIOS)) + if label: + # Counted on their own line, named on request. if verbose: + seen.add(key) + print(f" MISSING ({label}): {key}") _print_category_evidence(d) - _print_ground_truth(d.get("ground_truth", []), verbose) + continue + seen.add(key) + req = "required" if d.get("required", True) else "optional" + hle = ", HLE available" if d.get("hle_fallback") else "" + print(f" MISSING ({req}{hle}): {key}") + if verbose: + _print_category_evidence(d) + _print_ground_truth(d.get("ground_truth", []), verbose) + + +def _print_discrepancy_details(details: list[dict], seen: set[str], verbose: bool) -> None: for d in details: disc = d.get("discrepancy") if disc: @@ -1941,19 +2187,21 @@ def _print_detail_entries(details: list[dict], seen: set[str], verbose: bool) -> print(f" DISCREPANCY: {key}: {disc}") _print_ground_truth(d.get("ground_truth", []), verbose) - if verbose: - for d in details: - if d["status"] == Status.OK: - key = f"{d['system']}/{d['name']}" - if key in seen: - continue - seen.add(key) - gt = d.get("ground_truth", []) - if gt: - req = "required" if d.get("required", True) else "optional" - print(f" OK ({req}): {key}") - for line in _format_ground_truth_verbose(gt): - print(f" {line}") + +def _print_ok_details(details: list[dict], seen: set[str]) -> None: + for d in details: + if d["status"] != Status.OK: + continue + key = f"{d['system']}/{d['name']}" + if key in seen: + continue + seen.add(key) + gt = d.get("ground_truth", []) + if gt: + req = "required" if d.get("required", True) else "optional" + print(f" OK ({req}): {key}") + for line in _format_ground_truth_verbose(gt): + print(f" {line}") def _print_undeclared_entry( @@ -2171,45 +2419,46 @@ def _print_launcher_reads(result: dict, verbose: bool) -> None: print(f" {reader['emulator']}: {reader['source_ref']}") -def print_platform_result( - result: dict, group: list[str], verbose: bool = False -) -> None: +def _platform_summary_parts(result: dict) -> list[str]: + """The counts of a platform's first report line, in its mode's terms.""" mode = result["verification_mode"] total = result["total_files"] c = result["severity_counts"] - label = " / ".join(group) - if result.get("systems"): - label += f" ({', '.join(result['systems'])})" ok_count = c[Severity.OK] problems = total - ok_count if not reads_file_contents(mode): + parts = [f"{ok_count}/{total} present"] if problems: missing = c.get(Severity.WARNING, 0) + c.get(Severity.CRITICAL, 0) optional_missing = c.get(Severity.INFO, 0) - parts = [f"{ok_count}/{total} present"] if missing: parts.append(f"{missing} missing") if optional_missing: parts.append(f"{optional_missing} optional missing") - else: - parts = [f"{ok_count}/{total} present"] - else: - sc = result.get("status_counts", {}) - untested = sc.get(Status.UNTESTED, 0) - missing = sc.get(Status.MISSING, 0) - parts = [f"{ok_count}/{total} OK"] - if untested: - parts.append(f"{untested} untested") - if missing: - parts.append(f"{missing} missing") - print(f"{label}: {', '.join(parts)} [{mode}]") - fetched = sorted({d["name"] for d in result["details"] if d.get("release_asset")}) + return parts + sc = result.get("status_counts", {}) + untested = sc.get(Status.UNTESTED, 0) + missing = sc.get(Status.MISSING, 0) + parts = [f"{ok_count}/{total} OK"] + if untested: + parts.append(f"{untested} untested") + if missing: + parts.append(f"{missing} missing") + return parts + + +def _print_release_assets(details: list[dict]) -> None: + fetched = sorted({d["name"] for d in details if d.get("release_asset")}) if fetched: # Counted present: an online build downloads them. --offline counts # them missing, as an offline build leaves them out. shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}") + + +def _print_platform_notices(result: dict, verbose: bool) -> None: + """What the counts leave unsaid: uncached trees, cuts, region and category gaps.""" uncached = result.get("data_dir_notices") or [] if uncached and result.get("status_counts", {}).get(Status.MISSING): shown = ", ".join(uncached[:10]) + (f" (+{len(uncached) - 10})" if len(uncached) > 10 else "") @@ -2235,12 +2484,8 @@ def print_platform_result( listed = "" if verbose else " (--verbose lists them)" print(f" Missing, not firmware: {counts}{listed}") - seen_details: set[str] = set() - _print_detail_entries(result["details"], seen_details, verbose) - _print_undeclared_section(result, verbose) - _print_launcher_reads(result, verbose) - _print_launcher_unproven(result, verbose) +def _print_platform_coverage(result: dict, verbose: bool) -> None: # The same notes come back for every platform running these cores and # filled 985 of the 1114 lines of verify --all: counted, listed on ask. exclusions = result.get("exclusion_notes", []) @@ -2268,6 +2513,25 @@ def print_platform_result( print(f" {no_profile} platform-only (no emulator profile)") +def print_platform_result( + result: dict, group: list[str], verbose: bool = False +) -> None: + mode = result["verification_mode"] + label = " / ".join(group) + if result.get("systems"): + label += f" ({', '.join(result['systems'])})" + print(f"{label}: {', '.join(_platform_summary_parts(result))} [{mode}]") + _print_release_assets(result["details"]) + _print_platform_notices(result, verbose) + + seen_details: set[str] = set() + _print_detail_entries(result["details"], seen_details, verbose) + _print_undeclared_section(result, verbose) + _print_launcher_reads(result, verbose) + _print_launcher_unproven(result, verbose) + _print_platform_coverage(result, verbose) + + # Emulator/system mode verification @@ -2305,6 +2569,538 @@ def _select_profiles( print(f"Error: {exc}", file=sys.stderr) sys.exit(1) + +_HASH_CONTRADICTED = "declared hash contradicted by the local file" + +# Reduced in the order generate_emulator_pack chooses, so the +# destination's status is the one the pack reports: a slot it +# fills with a contradicted copy, or counts as refused by the +# core, is not missing because another alternative is absent. +_SLOT_PREFERENCE: tuple[Callable[[tuple], bool], ...] = ( + lambda a: a[0]["status"] == Status.OK, + lambda a: a[0]["status"] == Status.UNTESTED + and a[0].get("reason") == _HASH_CONTRADICTED, + lambda a: a[0]["status"] != Status.MISSING, +) + + +def _emulator_files( + emu_name: str, + profile: dict, + db: dict, + standalone: bool, + all_profiles: dict, + system_ids: list[str] | None, + required_only: bool, + region_drops: set[str], +) -> list[dict]: + """The entries of a profile the emulator pack carries.""" + from packextras import expand_agnostic_entries + from packpaths import _resolve_destination + + files = expand_agnostic_entries( + expand_directory_entries( + deliverable(profile.get("files", []), standalone), + db, + standalone, + ), + emu_name, profile, db, standalone, all_profiles, + ) + if system_ids: + files = [fe for fe in files if entry_serves_systems(fe, profile, system_ids)] + if required_only: + optional_archives = { + fe["archive"] for fe in files + if fe.get("archive") + and archive_is_optional(archive_entry(fe["archive"], files), fe["archive"], files) + } + files = [ + fe for fe in files + if fe.get("archive") not in optional_archives + and (fe.get("archive") or fe.get("required") is not False) + ] + if region_drops: + # Loose files only, as the emulator pack: an archive ships whole, + # and dropping kronos' regional stvbios.zip members rebuilt the + # archive here from 4 of its 14 members and changed its required. + files = [ + fe + for fe in files + if fe.get("archive") + or _resolve_destination(fe, standalone) not in region_drops + ] + return files + + +def _loose_result( + file_entry: dict, name: str, required: bool, local_path: str | None, + resolve_status: str, chosen_check: Callable[[], tuple[str | None, str | None]], +) -> dict: + """The verdict on a loose profile entry, from its resolution.""" + stored = _storage_verdict(file_entry, emulator_pack=True) + if stored is not None: + return stored + if resolve_status == RELEASE_ASSET_PENDING: + return { + "name": name, + "status": Status.OK, + "required": required, + "path": local_path, + "release_asset": local_path, + "reason": "release asset, fetched when the pack is built", + } + if not local_path: + result = {"name": name, "status": Status.MISSING, "required": required} + # An entry the profile documents as unsourceable is absent by + # design: a per-user key, a slot the user fills, a dump nobody + # has made. Counting it beside a file somebody could still + # find invites the wrong repair: dropping the flag, or + # chasing a vendor's whole install tree. + unsourceable = file_entry.get("unsourceable") + if unsourceable: + result["unsourceable"] = ( + unsourceable if isinstance(unsourceable, str) else "" + ) + return result + # Apply emulator validation + # Judged by this emulator's own entries, as it runs its check, + # through the selection the emulator pack makes. + chosen, disagreement = chosen_check() + if disagreement: + return { + "name": name, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": disagreement.split(" says ", 1)[-1], + } + if chosen != local_path: + return { + "name": name, + "status": Status.OK, + "required": required, + "path": chosen, + } + if resolve_status == "hash_mismatch": + # Nothing in validation: caught it, but the name matched + # while the bytes contradict the hash the profile + # declares. That is a different file wearing the right + # name (config.ini and ROM collide across systems), so + # calling it covered reports the collection as holding + # something it does not. Validation runs first because it + # names the specific field that disagrees. + return { + "name": name, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": "declared hash contradicted by the local file", + } + return { + "name": name, + "status": Status.OK, + "required": required, + "path": local_path, + } + + +def _archive_result( + archive: str, required: bool, local_path: str | None, resolve_status: str, +) -> dict: + """The verdict on an archive unit, from its resolution.""" + if local_path and resolve_status == "hash_mismatch": + # Same policy as the loose-file branch below: the name + # matched while the bytes contradict the hash the profile + # declares on the container. Reporting it covered says the + # collection holds an archive it does not. + return { + "name": archive, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": "declared hash contradicted by the local file", + } + if local_path: + result = { + "name": archive, + "status": Status.OK, + "required": required, + "path": local_path, + } + if resolve_status == RELEASE_ASSET_PENDING: + result["release_asset"] = local_path + return result + return { + "name": archive, + "status": Status.MISSING, + "required": required, + } + + +PlacedResult = tuple[str, dict, bool, bool, list[dict]] + + +@dataclass +class _EmulatorPack: + """The emulator pack as verify_emulator retraces it, and its report.""" + + db: dict + standalone: bool + required_only: bool + validation_index: dict + zip_contents: dict + data_registry: dict | None + details: list[dict] = field(default_factory=list) + # Members of a set another member fills, or that the set's first member + # stands for: not missing, and out of every count. + set_members: list[dict] = field(default_factory=list) + file_status: dict[str, str] = field(default_factory=dict) + file_severity: dict[str, str] = field(default_factory=dict) + dest_to_name: dict[str, str] = field(default_factory=dict) + data_dir_notices: list[str] = field(default_factory=list) + # The paths the emulator pack writes a profile file to. A copy whose hash + # the profile contradicts is written too (UNTESTED here, a DISCREPANCY in + # the pack), so the status alone does not say what the pack holds. + packed_dests: set[str] = field(default_factory=set) + # The emulator pack walks profiles in name order and keeps the first + # file at a path, folding case: a later profile's different file there + # (zesarux pentagon.rom after speccy's PENTAGON.ROM) is not in the pack. + sha1_by_path: dict = field(init=False) + # Destination -> (file packed there, its profile, the path as written). + # Archives and data trees take paths too, before and after the loose + # files of their profile, as the pack writes them. + placed: dict[str, tuple[str | None, str, str]] = field(default_factory=dict) + placed_files: set[str] = field(default_factory=set) + placed_parents: set[str] = field(default_factory=set) + content_ids: dict[str, str | None] = field(default_factory=dict) + + def __post_init__(self) -> None: + self.sha1_by_path = { + entry.get("path"): sha1 for sha1, entry in self.db.get("files", {}).items() + } + + def pending(self, entry: dict, local_path: str | None, status: str) -> tuple[str | None, str]: + from packresolve import pending_release_asset, run_is_offline + + # Read from disk and the cache, as _resolve_for_platform does: a + # release asset the cache lacks is fetched by an online build + # (generate_emulator_pack resolves with offline=offline). + if status in ("not_found", "hash_mismatch") and not run_is_offline(): + asset = pending_release_asset(entry, self.db) + if asset: + return asset, RELEASE_ASSET_PENDING + return local_path, status + + def content_id(self, path: str | None) -> str | None: + if not path: + return None + if path not in self.content_ids: + self.content_ids[path] = self.sha1_by_path.get(path) or ( + compute_hashes(path)["sha1"] if os.path.isfile(path) else None + ) + return self.content_ids[path] + + def block(self, dest: str) -> str | None: + from packpaths import placement_block + + return placement_block( + dest, self.placed_files, set(self.placed), self.placed_parents, True + ) + + def occupy(self, dest: str, path: str | None, owner: str) -> None: + from packpaths import _register_path + + if self.block(dest): + return + self.placed[dest.lower()] = (path, owner, dest) + _register_path(dest, self.placed_files, self.placed_parents) + + def occupy_trees(self, emu_name: str, profile: dict) -> None: + """The profile's data trees follow its files in the pack, which + writes them even when the system filter leaves it no file: + bluemsx's Machines/ tree holds msx-emu's coleco.rom path in a + --system colecovision pack.""" + for dd in deliverable(profile.get("data_directories", []), self.standalone): + if self.required_only and dd.get("required") is False: + continue + cache = (self.data_registry or {}).get(dd.get("ref", ""), {}).get("local_cache", "") + if not cache or not os.path.isdir(cache): + continue + dd_dest = dd.get("destination", "") + structure = profile.get("pack_structure") + prefix = ( + structure.get("standalone" if self.standalone else "libretro", "") + if structure else "" + ) + if prefix: + dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix + for root, _dirs, names in os.walk(cache): + for fname in names: + src = os.path.join(root, fname) + rel = os.path.relpath(src, cache).replace(os.sep, "/") + self.occupy(f"{dd_dest}/{rel}" if dd_dest else rel, src, emu_name) + + def note_data_dirs(self, profile: dict) -> None: + # Check data directories (only notice if not cached) + for dd in deliverable( + profile.get("data_directories", []), self.standalone + ): + if self.required_only and dd.get("required") is False: + continue + ref = dd.get("ref", "") + if not ref: + continue + if self.data_registry and ref in self.data_registry: + cache_path = self.data_registry[ref].get("local_cache", "") + if cache_path and os.path.isdir(cache_path): + continue # cached, no notice needed + self.data_dir_notices.append(ref) + + def verify_profile( + self, emu_name: str, profile: dict, files: list[dict], spares: set[str], + ) -> None: + """Verify one profile's entries and add them to the report.""" + self.note_data_dirs(profile) + + if not files: + self.details.append( + { + "name": f"({emu_name})", + "status": Status.OK, + "required": False, + "system": "", + "note": f"No files needed for {profile.get('emulator', emu_name)}", + "ground_truth": [], + } + ) + self.occupy_trees(emu_name, profile) + return + + # Each destination's outcome, settled by set once the profile is + # read: an archive unit is a member like a loose file (Kronos reads + # kronos/stvbios.zip, else stvbios.zip). + placed_results = self._archive_results(emu_name, profile, files, spares) + self._place_loose(emu_name, self._loose_results(emu_name, files), placed_results) + self._settle(emu_name, profile, placed_results) + self.occupy_trees(emu_name, profile) + + def _archive_results( + self, emu_name: str, profile: dict, files: list[dict], spares: set[str], + ) -> list[PlacedResult]: + # Verify archives as units (e.g., neogeo.zip, aes.zip) + from packpaths import _archive_destination + from packresolve import resolve_file + + placed_results: list[PlacedResult] = [] + seen_archives: set[str] = set() + for file_entry in files: + archive = file_entry.get("archive") + if not archive or archive in seen_archives: + continue + seen_archives.add(archive) + own_entry = archive_entry(archive, files) + # Where the pack puts it: an archive_prefix or pack_structure + # moves it, and a loose same-named entry is another file. + dest = _archive_destination( + archive, profile.get("archive_prefix", ""), + profile.get("pack_structure"), self.standalone, + ) + if dest in spares: + continue + local_path, resolve_status = self.pending(own_entry, *resolve_file( + own_entry, + self.db, + DEFAULT_BIOS_DIR, + self.zip_contents, + data_dir_registry=self.data_registry, + offline=True, + )) + required = any( + f.get("archive") == archive and f.get("required", True) + for f in files + ) + result = _archive_result(archive, required, local_path, resolve_status) + result["system"] = file_entry.get("system", "") + result["hle_fallback"] = False + result["ground_truth"] = build_ground_truth(archive, self.validation_index) + result["destination"] = dest + block = self.block(dest) + if block and local_path and result["status"] != Status.MISSING: + other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", "")) + if block == "path_conflict" or self.content_id(local_path) != self.content_id(other_path): + # The pack serves the other profile's file here: this + # archive is not in it, whatever this profile resolves. + result["status"] = Status.MISSING + result["reason"] = ( + "a packed file occupies its directory" if block == "path_conflict" + else f"the pack holds {owner}'s {other_dest} at this path" + ) + elif local_path: + self.occupy(dest, local_path, emu_name) + self.packed_dests.add(dest) + placed_results.append((dest, result, required, False, [own_entry])) + return placed_results + + def _loose_results( + self, emu_name: str, files: list[dict], + ) -> dict[str, list[tuple[dict, bool, bool, dict]]]: + from packpaths import _resolve_destination + from packresolve import resolve_file + + # Results of this emulator, by destination. Several entries of one + # profile on one destination are the releases the code accepts + # there (a shareware and a retail HOG, each GRP in a size table): + # holding one of them fills the slot, and the others are not gaps. + emu_results: dict[str, list[tuple[dict, bool, bool, dict]]] = {} + + for file_entry in files: + # Skip archive members (verified as archive units above) + if file_entry.get("archive"): + continue + + dest_hint = file_entry.get("path", "") + # The emulator pack's resolution, release assets included. + local_path, resolve_status = self.pending(file_entry, *resolve_file( + {**with_archive_members(file_entry, files), "source_profile": emu_name}, + self.db, + DEFAULT_BIOS_DIR, + self.zip_contents, + dest_hint=dest_hint, + data_dir_registry=self.data_registry, + offline=True, + )) + if resolve_status in ("not_found", "user_provided", "external"): + local_path = None + name = file_entry.get("name", "") + required = file_entry.get("required", True) + hle = file_entry.get("hle_fallback", False) + + result = _loose_result( + file_entry, name, required, local_path, resolve_status, + functools.partial( + validated_choice, file_entry, local_path, self.db, + self.validation_index, DEFAULT_BIOS_DIR, None, + emulators={emu_name}, + ), + ) + result["system"] = file_entry.get("system", "") + result["hle_fallback"] = hle + result["ground_truth"] = build_ground_truth(name, self.validation_index) + # The slot the emulator pack places this entry in: standalone_path + # under --standalone, the sanitised path. + dest = _resolve_destination(file_entry, self.standalone) or name + emu_results.setdefault(dest, []).append((result, required, hle, file_entry)) + return emu_results + + def _place_loose( + self, emu_name: str, + emu_results: dict[str, list[tuple[dict, bool, bool, dict]]], + placed_results: list[PlacedResult], + ) -> None: + for dest, alternatives in emu_results.items(): + # What the emulator pack places here: an accepted file, else a + # file whose hash the profile contradicts. A refused copy is held + # but never packed. + slot_entries = [a[3] for a in alternatives] + kept = _preferred_alternatives(alternatives) + packed = next( + (a[0].get("path") for a in kept + if a[0]["status"] == Status.OK and a[0].get("path")), + None, + ) or next( + (a[0].get("path") for a in kept + if a[0]["status"] == Status.UNTESTED + and a[0].get("reason") == _HASH_CONTRADICTED and a[0].get("path")), + None, + ) + held = packed or next( + (a[0].get("path") for a in kept + if a[0]["status"] != Status.MISSING and a[0].get("path")), + None, + ) + block = self.block(dest) + block_reason = "" + if block and held is not None: + block_reason = self._block_reason(dest, block, held) + elif not block and packed is not None: + self.occupy(dest, packed, emu_name) + self.packed_dests.add(dest) + for result, required, hle, _file_entry in kept: + if block_reason and result["status"] != Status.MISSING: + result["status"] = Status.MISSING + result["reason"] = block_reason + result["destination"] = dest + placed_results.append((dest, result, required, hle, slot_entries)) + + def _block_reason(self, dest: str, block: str, held: str) -> str: + other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", "")) + same = self.content_id(held) is not None and self.content_id(held) == self.content_id( + other_path + ) + if block == "path_conflict": + return "a packed file occupies its directory" + if block == "case_twin": + return ( + f"packed only as {other_dest}, from {owner}" + if same + else f"the pack holds {owner}'s {other_dest} at this path" + ) + if not same: + return f"the pack holds {owner}'s {other_dest} at this path" + return "" + + def _settle(self, emu_name: str, profile: dict, placed_results: list[PlacedResult]) -> None: + # A set the code takes one member of is one need: once a member is + # in the pack the others are not missing, and a set nobody holds is + # one gap under its first member. Settled per profile, before the + # destinations of several profiles are merged. + excused, standing = settle_sets([ + ( + slot_set_keys(emu_name, entries), + entries[0], + result["status"] == Status.OK + or (result["status"] == Status.UNTESTED + and result.get("reason") == _HASH_CONTRADICTED), + ) + for _dest, result, _required, _hle, entries in placed_results + ], lambda key: set_requirements(profile).get(key[1], True)) + for position, (dest, result, required, hle, _fe) in enumerate(placed_results): + if position in excused and result["status"] == Status.MISSING: + self.set_members.append(result) + continue + if position in standing: + result["alternatives"] = standing[position].others + result["required"] = required = standing[position].required + self.details.append(result) + + # Aggregate by destination (path if available, else name) + self.dest_to_name[dest] = result["name"] + cur = result["status"] + prev = self.file_status.get(dest) + if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get( + prev, 0 + ): + self.file_status[dest] = cur + sev = _emulator_severity(cur, required, hle) + prev_sev = self.file_severity.get(dest) + if prev_sev is None or _SEVERITY_ORDER.get( + sev, 0 + ) > _SEVERITY_ORDER.get(prev_sev, 0): + self.file_severity[dest] = sev + + +def _preferred_alternatives( + alternatives: list[tuple[dict, bool, bool, dict]], +) -> list[tuple[dict, bool, bool, dict]]: + """The one alternative the emulator pack places at a destination.""" + if len(alternatives) > 1: + for keep in _SLOT_PREFERENCE: + chosen = [a for a in alternatives if keep(a)] + if chosen: + return chosen[:1] + return alternatives + + def verify_emulator( profile_names: list[str], emulators_dir: str, @@ -2324,14 +3120,7 @@ def verify_emulator( file or tree marked ``required: false`` is left out, and an archive when it and every member it carries are optional, as the builder leaves them. """ - from packextras import expand_agnostic_entries - from packresolve import pending_release_asset, resolve_file, run_is_offline - from packpaths import ( - _archive_destination, - _register_path, - _resolve_destination, - placement_block, - ) + from packpaths import _resolve_destination # Also load aliases for redirect messages all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) @@ -2347,32 +3136,13 @@ def verify_emulator( ) # Build validation index from selected profiles only - selected_profiles = {n: p for n, p in selected} + selected_profiles = dict(selected) validation_index = _build_validation_index(selected_profiles) data_registry = load_data_dir_registry(platforms_dir) - def pending(entry: dict, local_path: str | None, status: str) -> tuple[str | None, str]: - # Read from disk and the cache, as _resolve_for_platform does: a - # release asset the cache lacks is fetched by an online build - # (generate_emulator_pack resolves with offline=offline). - if status in ("not_found", "hash_mismatch") and not run_is_offline(): - asset = pending_release_asset(entry, db) - if asset: - return asset, RELEASE_ASSET_PENDING - return local_path, status - - details = [] - # Members of a set another member fills, or that the set's first member - # stands for: not missing, and out of every count. - set_members: list[dict] = [] - file_status: dict[str, str] = {} - file_severity: dict[str, str] = {} - dest_to_name: dict[str, str] = {} - data_dir_notices: list[str] = [] - # The paths the emulator pack writes a profile file to. A copy whose hash - # the profile contradicts is written too (UNTESTED here, a DISCREPANCY in - # the pack), so the status alone does not say what the pack holds. - packed_dests: set[str] = set() + pack = _EmulatorPack( + db, standalone, required_only, validation_index, zip_contents, data_registry, + ) # The emulator pack withdraws these, and the report withdraws the same. region_drops: set[str] = set() @@ -2384,428 +3154,24 @@ def verify_emulator( zip_contents=zip_contents, data_registry=data_registry, ) - # The emulator pack walks profiles in name order and keeps the first - # file at a path, folding case: a later profile's different file there - # (zesarux pentagon.rom after speccy's PENTAGON.ROM) is not in the pack. - sha1_by_path = { - entry.get("path"): sha1 for sha1, entry in db.get("files", {}).items() - } - # Destination -> (file packed there, its profile, the path as written). - # Archives and data trees take paths too, before and after the loose - # files of their profile, as the pack writes them. - placed: dict[str, tuple[str | None, str, str]] = {} - placed_files: set[str] = set() - placed_parents: set[str] = set() - content_ids: dict[str, str | None] = {} - - def content_id(path: str | None) -> str | None: - if not path: - return None - if path not in content_ids: - content_ids[path] = sha1_by_path.get(path) or ( - compute_hashes(path)["sha1"] if os.path.isfile(path) else None - ) - return content_ids[path] - - def occupy(dest: str, path: str | None, owner: str) -> None: - if placement_block(dest, placed_files, set(placed), placed_parents, True): - return - placed[dest.lower()] = (path, owner, dest) - _register_path(dest, placed_files, placed_parents) - - def occupy_trees(emu_name: str, profile: dict) -> None: - """The profile's data trees follow its files in the pack, which - writes them even when the system filter leaves it no file: - bluemsx's Machines/ tree holds msx-emu's coleco.rom path in a - --system colecovision pack.""" - for dd in deliverable(profile.get("data_directories", []), standalone): - if required_only and dd.get("required") is False: - continue - cache = (data_registry or {}).get(dd.get("ref", ""), {}).get("local_cache", "") - if not cache or not os.path.isdir(cache): - continue - dd_dest = dd.get("destination", "") - structure = profile.get("pack_structure") - prefix = ( - structure.get("standalone" if standalone else "libretro", "") - if structure else "" - ) - if prefix: - dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix - for root, _dirs, names in os.walk(cache): - for fname in names: - src = os.path.join(root, fname) - rel = os.path.relpath(src, cache).replace(os.sep, "/") - occupy(f"{dd_dest}/{rel}" if dd_dest else rel, src, emu_name) - for emu_name, profile in sorted(selected): - files = expand_agnostic_entries( - expand_directory_entries( - deliverable(profile.get("files", []), standalone), - db, - standalone, - ), - emu_name, profile, db, standalone, all_profiles, + files = _emulator_files( + emu_name, profile, db, standalone, all_profiles, system_ids, + required_only, region_drops, ) - if system_ids: - files = [fe for fe in files if entry_serves_systems(fe, profile, system_ids)] - if required_only: - optional_archives = { - fe["archive"] for fe in files - if fe.get("archive") - and archive_is_optional(archive_entry(fe["archive"], files), fe["archive"], files) - } - files = [ - fe for fe in files - if fe.get("archive") not in optional_archives - and (fe.get("archive") or fe.get("required") is not False) - ] - if region_drops: - # Loose files only, as the emulator pack: an archive ships whole, - # and dropping kronos' regional stvbios.zip members rebuilt the - # archive here from 4 of its 14 members and changed its required. - files = [ - fe - for fe in files - if fe.get("archive") - or _resolve_destination(fe, standalone) not in region_drops - ] spares: set[str] = set() if required_only: from packextras import emulator_required_spares spares = emulator_required_spares( emu_name, profile, files, standalone, region_drops, db, - validation_index, zip_contents, data_registry, + validation_index, zip_contents, data_registry=data_registry, ) files = [ fe for fe in files if fe.get("archive") or _resolve_destination(fe, standalone) not in spares ] - - # Check data directories (only notice if not cached) - for dd in deliverable( - profile.get("data_directories", []), standalone - ): - if required_only and dd.get("required") is False: - continue - ref = dd.get("ref", "") - if not ref: - continue - if data_registry and ref in data_registry: - cache_path = data_registry[ref].get("local_cache", "") - if cache_path and os.path.isdir(cache_path): - continue # cached, no notice needed - data_dir_notices.append(ref) - - if not files: - details.append( - { - "name": f"({emu_name})", - "status": Status.OK, - "required": False, - "system": "", - "note": f"No files needed for {profile.get('emulator', emu_name)}", - "ground_truth": [], - } - ) - occupy_trees(emu_name, profile) - continue - - # Each destination's outcome, settled by set once the profile is - # read: an archive unit is a member like a loose file (Kronos reads - # kronos/stvbios.zip, else stvbios.zip). - placed_results: list[tuple[str, dict, bool, bool, list[dict]]] = [] - fallback_reason = "declared hash contradicted by the local file" - - # Verify archives as units (e.g., neogeo.zip, aes.zip) - seen_archives: set[str] = set() - for file_entry in files: - archive = file_entry.get("archive") - if archive and archive not in seen_archives: - seen_archives.add(archive) - own_entry = archive_entry(archive, files) - if _archive_destination( - archive, profile.get("archive_prefix", ""), - profile.get("pack_structure"), standalone, - ) in spares: - continue - local_path, resolve_status = pending(own_entry, *resolve_file( - own_entry, - db, - DEFAULT_BIOS_DIR, - zip_contents, - data_dir_registry=data_registry, - offline=True, - )) - required = any( - f.get("archive") == archive and f.get("required", True) - for f in files - ) - if local_path and resolve_status == "hash_mismatch": - # Same policy as the loose-file branch below: the name - # matched while the bytes contradict the hash the profile - # declares on the container. Reporting it covered says the - # collection holds an archive it does not. - result = { - "name": archive, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": "declared hash contradicted by the local file", - } - elif local_path: - result = { - "name": archive, - "status": Status.OK, - "required": required, - "path": local_path, - } - if resolve_status == RELEASE_ASSET_PENDING: - result["release_asset"] = local_path - else: - result = { - "name": archive, - "status": Status.MISSING, - "required": required, - } - result["system"] = file_entry.get("system", "") - result["hle_fallback"] = False - result["ground_truth"] = build_ground_truth(archive, validation_index) - # Where the pack puts it: an archive_prefix or pack_structure - # moves it, and a loose same-named entry is another file. - dest = _archive_destination( - archive, profile.get("archive_prefix", ""), - profile.get("pack_structure"), standalone, - ) - result["destination"] = dest - block = placement_block( - dest, placed_files, set(placed), placed_parents, True - ) - if block and local_path and result["status"] != Status.MISSING: - other_path, owner, other_dest = placed.get(dest.lower(), (None, "", "")) - if block == "path_conflict" or content_id(local_path) != content_id(other_path): - # The pack serves the other profile's file here: this - # archive is not in it, whatever this profile resolves. - result["status"] = Status.MISSING - result["reason"] = ( - "a packed file occupies its directory" if block == "path_conflict" - else f"the pack holds {owner}'s {other_dest} at this path" - ) - elif local_path: - occupy(dest, local_path, emu_name) - packed_dests.add(dest) - placed_results.append((dest, result, required, False, [own_entry])) - - # Results of this emulator, by destination. Several entries of one - # profile on one destination are the releases the code accepts - # there (a shareware and a retail HOG, each GRP in a size table): - # holding one of them fills the slot, and the others are not gaps. - emu_results: dict[str, list[tuple[dict, bool, bool, dict]]] = {} - - for file_entry in files: - # Skip archive members (verified as archive units above) - if file_entry.get("archive"): - continue - - dest_hint = file_entry.get("path", "") - # The emulator pack's resolution, release assets included. - local_path, resolve_status = pending(file_entry, *resolve_file( - {**with_archive_members(file_entry, files), "source_profile": emu_name}, - db, - DEFAULT_BIOS_DIR, - zip_contents, - dest_hint=dest_hint, - data_dir_registry=data_registry, - offline=True, - )) - if resolve_status in ("not_found", "user_provided", "external"): - local_path = None - name = file_entry.get("name", "") - required = file_entry.get("required", True) - hle = file_entry.get("hle_fallback", False) - - stored = _storage_verdict(file_entry, emulator_pack=True) - if stored is not None: - result = stored - elif resolve_status == RELEASE_ASSET_PENDING: - result = { - "name": name, - "status": Status.OK, - "required": required, - "path": local_path, - "release_asset": local_path, - "reason": "release asset, fetched when the pack is built", - } - elif not local_path: - result = {"name": name, "status": Status.MISSING, "required": required} - # An entry the profile documents as unsourceable is absent by - # design: a per-user key, a slot the user fills, a dump nobody - # has made. Counting it beside a file somebody could still - # find invites the wrong repair: dropping the flag, or - # chasing a vendor's whole install tree. - unsourceable = file_entry.get("unsourceable") - if unsourceable: - result["unsourceable"] = ( - unsourceable if isinstance(unsourceable, str) else "" - ) - else: - # Apply emulator validation - # Judged by this emulator's own entries, as it runs its check, - # through the selection the emulator pack makes. - chosen, disagreement = validated_choice( - file_entry, local_path, db, validation_index, DEFAULT_BIOS_DIR, - None, emulators={emu_name}, - ) - if disagreement: - result = { - "name": name, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": disagreement.split(" says ", 1)[-1], - } - elif chosen != local_path: - result = { - "name": name, - "status": Status.OK, - "required": required, - "path": chosen, - } - elif resolve_status == "hash_mismatch": - # Nothing in validation: caught it, but the name matched - # while the bytes contradict the hash the profile - # declares. That is a different file wearing the right - # name (config.ini and ROM collide across systems), so - # calling it covered reports the collection as holding - # something it does not. Validation runs first because it - # names the specific field that disagrees. - result = { - "name": name, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": "declared hash contradicted by the local file", - } - else: - result = { - "name": name, - "status": Status.OK, - "required": required, - "path": local_path, - } - - result["system"] = file_entry.get("system", "") - result["hle_fallback"] = hle - result["ground_truth"] = build_ground_truth(name, validation_index) - # The slot the emulator pack places this entry in: standalone_path - # under --standalone, the sanitised path. - dest = _resolve_destination(file_entry, standalone) or name - emu_results.setdefault(dest, []).append((result, required, hle, file_entry)) - - for dest, alternatives in emu_results.items(): - # What the emulator pack places here: an accepted file, else a - # file whose hash the profile contradicts. A refused copy is held - # but never packed. - slot_entries = [a[3] for a in alternatives] - if len(alternatives) > 1: - # Reduced in the order generate_emulator_pack chooses, so the - # destination's status is the one the pack reports: a slot it - # fills with a contradicted copy, or counts as refused by the - # core, is not missing because another alternative is absent. - for keep in ( - lambda a: a[0]["status"] == Status.OK, - lambda a: a[0]["status"] == Status.UNTESTED - and a[0].get("reason") == fallback_reason, - lambda a: a[0]["status"] != Status.MISSING, - ): - chosen = [a for a in alternatives if keep(a)] - if chosen: - alternatives = chosen[:1] - break - packed = next( - (a[0].get("path") for a in alternatives - if a[0]["status"] == Status.OK and a[0].get("path")), - None, - ) or next( - (a[0].get("path") for a in alternatives - if a[0]["status"] == Status.UNTESTED - and a[0].get("reason") == fallback_reason and a[0].get("path")), - None, - ) - held = packed or next( - (a[0].get("path") for a in alternatives - if a[0]["status"] != Status.MISSING and a[0].get("path")), - None, - ) - block = placement_block( - dest, placed_files, set(placed), placed_parents, True - ) - block_reason = "" - if block and held is not None: - other_path, owner, other_dest = placed.get(dest.lower(), (None, "", "")) - same = content_id(held) is not None and content_id(held) == content_id( - other_path - ) - if block == "path_conflict": - block_reason = "a packed file occupies its directory" - elif block == "case_twin": - block_reason = ( - f"packed only as {other_dest}, from {owner}" - if same - else f"the pack holds {owner}'s {other_dest} at this path" - ) - elif not same: - block_reason = f"the pack holds {owner}'s {other_dest} at this path" - elif not block and packed is not None: - occupy(dest, packed, emu_name) - packed_dests.add(dest) - for result, required, hle, file_entry in alternatives: - if block_reason and result["status"] != Status.MISSING: - result["status"] = Status.MISSING - result["reason"] = block_reason - result["destination"] = dest - placed_results.append((dest, result, required, hle, slot_entries)) - - # A set the code takes one member of is one need: once a member is - # in the pack the others are not missing, and a set nobody holds is - # one gap under its first member. Settled per profile, before the - # destinations of several profiles are merged. - excused, standing = settle_sets([ - ( - slot_set_keys(emu_name, entries), - entries[0], - result["status"] == Status.OK - or (result["status"] == Status.UNTESTED - and result.get("reason") == fallback_reason), - ) - for _dest, result, _required, _hle, entries in placed_results - ], lambda key: set_requirements(profile).get(key[1], True)) - for position, (dest, result, required, hle, _fe) in enumerate(placed_results): - if position in excused and result["status"] == Status.MISSING: - set_members.append(result) - continue - if position in standing: - result["alternatives"] = standing[position].others - result["required"] = required = standing[position].required - details.append(result) - - # Aggregate by destination (path if available, else name) - dest_to_name[dest] = result["name"] - cur = result["status"] - prev = file_status.get(dest) - if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get( - prev, 0 - ): - file_status[dest] = cur - sev = _emulator_severity(cur, required, hle) - prev_sev = file_severity.get(dest) - if prev_sev is None or _SEVERITY_ORDER.get( - sev, 0 - ) > _SEVERITY_ORDER.get(prev_sev, 0): - file_severity[dest] = sev - - occupy_trees(emu_name, profile) + pack.verify_profile(emu_name, profile, files, spares) counts = { Severity.OK: 0, @@ -2813,18 +3179,18 @@ def verify_emulator( Severity.WARNING: 0, Severity.CRITICAL: 0, } - for s in file_severity.values(): + for s in pack.file_severity.values(): counts[s] = counts.get(s, 0) + 1 status_counts: dict[str, int] = {} - for s in file_status.values(): + for s in pack.file_status.values(): status_counts[s] = status_counts.get(s, 0) + 1 - label = _effective_validation_label(details, validation_index) + label = _effective_validation_label(pack.details, validation_index) gt_filenames = set(validation_index) - total = len(file_status) + total = len(pack.file_status) with_validation = sum( - 1 for dest in file_status if dest_to_name.get(dest, "") in gt_filenames + 1 for dest in pack.file_status if pack.dest_to_name.get(dest, "") in gt_filenames ) return { @@ -2833,12 +3199,12 @@ def verify_emulator( "total_files": total, # The paths the emulator pack fills with the profile's files, for the # pipeline's comparison with the pack built in memory. - "pack_destinations": sorted(packed_dests), + "pack_destinations": sorted(pack.packed_dests), "severity_counts": counts, "status_counts": status_counts, - "details": details, - "set_members": set_members, - "data_dir_notices": sorted(set(data_dir_notices)), + "details": pack.details, + "set_members": pack.set_members, + "data_dir_notices": sorted(set(pack.data_dir_notices)), "ground_truth_coverage": { "with_validation": with_validation, "platform_only": total - with_validation, @@ -2887,14 +3253,9 @@ def verify_system( ) -def print_emulator_result(result: dict, verbose: bool = False) -> None: - """Print verification result for emulator/system mode.""" - label = " + ".join(result["emulators"]) - mode = result["verification_mode"] +def _emulator_summary_parts(result: dict) -> list[str]: total = result["total_files"] - c = result["severity_counts"] - ok_count = c[Severity.OK] - + ok_count = result["severity_counts"][Severity.OK] sc = result.get("status_counts", {}) untested = sc.get(Status.UNTESTED, 0) missing = sc.get(Status.MISSING, 0) @@ -2913,14 +3274,21 @@ def print_emulator_result(result: dict, verbose: bool = False) -> None: parts.append(f"{missing - unsourceable} missing") if unsourceable: parts.append(f"{unsourceable} unsourceable") - print(f"{label}: {', '.join(parts)} [{mode}]") - fetched = sorted({d["name"] for d in result["details"] if d.get("release_asset")}) - if fetched: - shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") - print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}") + return parts - seen = set() - for d in result["details"]: + +def _print_emulator_ground_truth(gt: list[dict], verbose: bool) -> None: + if gt: + if verbose: + for line in _format_ground_truth_verbose(gt): + print(f" {line}") + else: + print(f" {_format_ground_truth_aggregate(gt)}") + + +def _print_emulator_problems(details: list[dict], seen: set[str], verbose: bool) -> None: + """The UNTESTED, MISSING and UNSOURCEABLE lines of an emulator report.""" + for d in details: if d["status"] == Status.UNTESTED: if d["name"] in seen: continue @@ -2929,14 +3297,8 @@ def print_emulator_result(result: dict, verbose: bool = False) -> None: hle = ", HLE available" if d.get("hle_fallback") else "" reason = d.get("reason", "") print(f" UNTESTED ({req}{hle}): {d['name']}: {reason}") - gt = d.get("ground_truth", []) - if gt: - if verbose: - for line in _format_ground_truth_verbose(gt): - print(f" {line}") - else: - print(f" {_format_ground_truth_aggregate(gt)}") - for d in result["details"]: + _print_emulator_ground_truth(d.get("ground_truth", []), verbose) + for d in details: if d["status"] == Status.MISSING and "unsourceable" not in d: if d["name"] in seen: continue @@ -2946,14 +3308,8 @@ def print_emulator_result(result: dict, verbose: bool = False) -> None: others = d.get("alternatives") either = f" (or {', '.join(others)})" if others else "" print(f" MISSING ({req}{hle}): {d['name']}{either}") - gt = d.get("ground_truth", []) - if gt: - if verbose: - for line in _format_ground_truth_verbose(gt): - print(f" {line}") - else: - print(f" {_format_ground_truth_aggregate(gt)}") - for d in result["details"]: + _print_emulator_ground_truth(d.get("ground_truth", []), verbose) + for d in details: if d["status"] == Status.MISSING and "unsourceable" in d: if d["name"] in seen: continue @@ -2961,22 +3317,40 @@ def print_emulator_result(result: dict, verbose: bool = False) -> None: why = d.get("unsourceable") or "documented as unobtainable" print(f" UNSOURCEABLE: {d['name']}: {why}") + +def _print_emulator_ok(details: list[dict], seen: set[str]) -> None: + for d in details: + if d["status"] == Status.OK: + if d["name"] in seen: + continue + seen.add(d["name"]) + gt = d.get("ground_truth", []) + if gt: + req = "required" if d.get("required", True) else "optional" + print(f" OK ({req}): {d['name']}") + for line in _format_ground_truth_verbose(gt): + print(f" {line}") + + +def print_emulator_result(result: dict, verbose: bool = False) -> None: + """Print verification result for emulator/system mode.""" + label = " + ".join(result["emulators"]) + mode = result["verification_mode"] + print(f"{label}: {', '.join(_emulator_summary_parts(result))} [{mode}]") + fetched = sorted({d["name"] for d in result["details"] if d.get("release_asset")}) + if fetched: + shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") + print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}") + + seen: set[str] = set() + _print_emulator_problems(result["details"], seen, verbose) + for d in result["details"]: if d.get("note"): print(f" {d['note']}") if verbose: - for d in result["details"]: - if d["status"] == Status.OK: - if d["name"] in seen: - continue - seen.add(d["name"]) - gt = d.get("ground_truth", []) - if gt: - req = "required" if d.get("required", True) else "optional" - print(f" OK ({req}): {d['name']}") - for line in _format_ground_truth_verbose(gt): - print(f" {line}") + _print_emulator_ok(result["details"], seen) for ref in result.get("data_dir_notices", []): print( @@ -3085,7 +3459,7 @@ def main() -> None: _main(held) -def _main(held: contextlib.ExitStack) -> None: +def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description="Platform-native BIOS verification") parser.add_argument("--platform", "-p", type=platform_arg, help="Platform name") parser.add_argument( @@ -3160,15 +3534,10 @@ def _main(held: contextlib.ExitStack) -> None: "hashes for a platform, without HLE for --emulator and --system. A file " "present with an unconfirmed hash is a warning, not a failure", ) - args = parser.parse_args() - work_from_repo_root(args, parser, ["db", "platforms_dir", "emulators_dir"]) - if args.platform: - require_platform(args.platform, args.platforms_dir) - if args.offline: - import packresolve + return parser - packresolve.set_offline(True) +def _requested_regions(args: argparse.Namespace, parser: argparse.ArgumentParser) -> list[str]: requested_regions: list[str] = [] if getattr(args, "region", None): import region as region_mod @@ -3177,12 +3546,11 @@ def _main(held: contextlib.ExitStack) -> None: requested_regions = region_mod.parse_requested(args.region) except ValueError as exc: parser.error(str(exc)) + return requested_regions - _refuse_listing_narrowings(args, parser) - if args.list_platforms or args.list_emulators or args.list_systems or args.list_targets: - _run_listing(args, parser) - return +def _check_mode(args: argparse.Namespace, parser: argparse.ArgumentParser) -> bool: + """Refuse a request naming no mode or several; returns the system mode.""" # --system beside --platform narrows that platform, as in generate_pack. system_mode = bool(args.system) and not args.platform modes = sum(1 for x in (args.platform, args.all, args.emulator, system_mode) if x) @@ -3193,54 +3561,125 @@ def _main(held: contextlib.ExitStack) -> None: "--platform, --all, --emulator, and --system are mutually exclusive" ) _refuse_mode_flags(args, parser) - platform_systems: list[str] | None = None - if args.platform and args.system: + return system_mode + + +def _platform_system_filter( + args: argparse.Namespace, parser: argparse.ArgumentParser, +) -> list[str] | None: + if not (args.platform and args.system): + return None + config = load_platform_config(args.platform, args.platforms_dir) + try: + return resolve_system_arg( + args.system, list(config.get("systems", {})), config, + f"--platform {args.platform} --list-systems", + ) + except ValueError as exc: + parser.error(f"--system {args.system}: {exc}") + return None + + +def _run_emulator_mode(args: argparse.Namespace, db: dict, requested_regions: list[str]) -> None: + names = [n.strip() for n in args.emulator.split(",") if n.strip()] + result = verify_emulator( + names, args.emulators_dir, db, args.standalone, + regions=requested_regions, platforms_dir=args.platforms_dir, + required_only=args.required_only, + ) + if args.json: + result["details"] = _json_details(result["details"], args.verbose) + print(json.dumps(result, indent=2)) + else: + print_emulator_result(result, verbose=args.verbose) + _exit_if_strict_emulator(args.strict, result) + + +def _run_system_mode(args: argparse.Namespace, db: dict, requested_regions: list[str]) -> None: + system_ids = [s.strip() for s in args.system.split(",") if s.strip()] + result = verify_system( + system_ids, args.emulators_dir, db, args.standalone, + regions=requested_regions, platforms_dir=args.platforms_dir, + required_only=args.required_only, + ) + if args.json: + result["details"] = _json_details(result["details"], args.verbose) + print(json.dumps(result, indent=2)) + else: + print_emulator_result(result, verbose=args.verbose) + _exit_if_strict_emulator(args.strict, result) + + +def _target_scope( + args: argparse.Namespace, + platforms: list[str], + emu_profiles: dict, + platform_systems: list[str] | None, +) -> tuple[dict[str, set[str] | None], list[str]]: + """The cores of each platform on --target, and the platforms that have it.""" + target_cores_cache: dict[str, set[str] | None] = {} + if not args.target: + return target_cores_cache, platforms + try: + target_cores_cache, platforms = build_target_cores_cache( + platforms, + args.target, + args.platforms_dir, + is_all=args.all, + ) + except (FileNotFoundError, ValueError) as e: + print(f"ERROR: {e}", file=sys.stderr) + sys.exit(1) + # A system the target leaves no core for was reported 0/0 with exit 0, + # where generate_pack refuses the same request. + if platform_systems: config = load_platform_config(args.platform, args.platforms_dir) - try: - platform_systems = resolve_system_arg( - args.system, list(config.get("systems", {})), config, - f"--platform {args.platform} --list-systems", + if not platform_scope_systems( + config, emu_profiles, target_cores_cache.get(args.platform), platform_systems + ): + reason = system_scope_error( + config, args.platform, platform_systems, args.target ) - except ValueError as exc: - parser.error(f"--system {args.system}: {exc}") - # The trees stay put while names resolve against them and files are read. - from refresh_data_dirs import hold_data_dirs + print(f"ERROR: {reason}", file=sys.stderr) + sys.exit(1) + return target_cores_cache, platforms - hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) - db = load_database(args.db) +def _print_platform_results( + args: argparse.Namespace, + groups: list[tuple[list[str], str]], + group_results: list[tuple[dict, list[str]]], + all_results: dict[str, dict], +) -> None: + if not args.json: + for result, group in group_results: + print_platform_result(result, group, verbose=args.verbose) + print() + if len(group_results) > 1: + print(_overall_summary(group_results)) - if args.emulator: - names = [n.strip() for n in args.emulator.split(",") if n.strip()] - result = verify_emulator( - names, args.emulators_dir, db, args.standalone, - regions=requested_regions, platforms_dir=args.platforms_dir, - required_only=args.required_only, - ) - if args.json: - result["details"] = _json_details(result["details"], args.verbose) - print(json.dumps(result, indent=2)) - else: - print_emulator_result(result, verbose=args.verbose) - _exit_if_strict_emulator(args.strict, result) - return + if args.destinations: + destinations = {} + for (result, names), (group, _rep) in zip(group_results, groups): + for name, key in zip(names, group): + destinations[name] = { + "platform": key, "pack_destinations": result["pack_destinations"], + } + Path(args.destinations).write_text(json.dumps(destinations, indent=1, sort_keys=True)) - if system_mode: - system_ids = [s.strip() for s in args.system.split(",") if s.strip()] - result = verify_system( - system_ids, args.emulators_dir, db, args.standalone, - regions=requested_regions, platforms_dir=args.platforms_dir, - required_only=args.required_only, - ) - if args.json: - result["details"] = _json_details(result["details"], args.verbose) - print(json.dumps(result, indent=2)) - else: - print_emulator_result(result, verbose=args.verbose) - _exit_if_strict_emulator(args.strict, result) - return + if args.json: + for r in all_results.values(): + r["details"] = _json_details(r["details"], args.verbose) + print(json.dumps(all_results, indent=2)) - # Platform mode (existing) + +def _run_platform_mode( + args: argparse.Namespace, + parser: argparse.ArgumentParser, + db: dict, + requested_regions: list[str], + platform_systems: list[str] | None, +) -> None: if args.all: platforms = list_registered_platforms(args.platforms_dir) elif args.platform: @@ -3253,30 +3692,9 @@ def _main(held: contextlib.ExitStack) -> None: emu_profiles = load_emulator_profiles(args.emulators_dir) data_registry = load_data_dir_registry(args.platforms_dir) - target_cores_cache: dict[str, set[str] | None] = {} - if args.target: - try: - target_cores_cache, platforms = build_target_cores_cache( - platforms, - args.target, - args.platforms_dir, - is_all=args.all, - ) - except (FileNotFoundError, ValueError) as e: - print(f"ERROR: {e}", file=sys.stderr) - sys.exit(1) - # A system the target leaves no core for was reported 0/0 with exit 0, - # where generate_pack refuses the same request. - if platform_systems: - config = load_platform_config(args.platform, args.platforms_dir) - if not platform_scope_systems( - config, emu_profiles, target_cores_cache.get(args.platform), platform_systems - ): - reason = system_scope_error( - config, args.platform, platform_systems, args.target - ) - print(f"ERROR: {reason}", file=sys.stderr) - sys.exit(1) + target_cores_cache, platforms = _target_scope( + args, platforms, emu_profiles, platform_systems, + ) # generate_pack refuses these on a platform whose cores no profile # describes, and the report answers the same request the same way. @@ -3329,30 +3747,49 @@ def _main(held: contextlib.ExitStack) -> None: for p in group_platforms: all_results[p] = result - if not args.json: - for result, group in group_results: - print_platform_result(result, group, verbose=args.verbose) - print() - if len(group_results) > 1: - print(_overall_summary(group_results)) - - if args.destinations: - destinations = {} - for (result, names), (group, _rep) in zip(group_results, groups): - for name, key in zip(names, group): - destinations[name] = { - "platform": key, "pack_destinations": result["pack_destinations"], - } - Path(args.destinations).write_text(json.dumps(destinations, indent=1, sort_keys=True)) - - if args.json: - for r in all_results.values(): - r["details"] = _json_details(r["details"], args.verbose) - print(json.dumps(all_results, indent=2)) - + _print_platform_results(args, groups, group_results, all_results) _exit_if_strict(args.strict, [r for r, _ in group_results]) +def _main(held: contextlib.ExitStack) -> None: + parser = _build_parser() + args = parser.parse_args() + work_from_repo_root(args, parser, ["db", "platforms_dir", "emulators_dir"]) + if args.platform: + require_platform(args.platform, args.platforms_dir) + if args.offline: + import packresolve + + packresolve.set_offline(True) + + requested_regions = _requested_regions(args, parser) + + _refuse_listing_narrowings(args, parser) + if args.list_platforms or args.list_emulators or args.list_systems or args.list_targets: + _run_listing(args, parser) + return + + system_mode = _check_mode(args, parser) + platform_systems = _platform_system_filter(args, parser) + # The trees stay put while names resolve against them and files are read. + from refresh_data_dirs import hold_data_dirs + + hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) + + db = load_database(args.db) + + if args.emulator: + _run_emulator_mode(args, db, requested_regions) + return + + if system_mode: + _run_system_mode(args, db, requested_regions) + return + + # Platform mode (existing) + _run_platform_mode(args, parser, db, requested_regions, platform_systems) + + def _json_details(details: list[dict], verbose: bool) -> list[dict]: """The entries a JSON report lists: what needs attention, or every one. From f36cc0d3a7a28c4e34b9cee8f76f1795f9b12208 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:53:58 +0100 Subject: [PATCH 2/9] refactor: split the validation index and checks --- scripts/validation.py | 536 +++++++++++++++++++++++++----------------- 1 file changed, 315 insertions(+), 221 deletions(-) diff --git a/scripts/validation.py b/scripts/validation.py index 34920be01..c1a0bbdf7 100644 --- a/scripts/validation.py +++ b/scripts/validation.py @@ -10,7 +10,8 @@ from __future__ import annotations import os import re import zipfile -from collections.abc import Callable, Iterator, Mapping, Sequence +from collections.abc import Callable, Collection, Iterator, Mapping, Sequence +from typing import TYPE_CHECKING, TypedDict from common import ( adler32_of, @@ -28,6 +29,9 @@ from hashing import md5_composite, parse_hash_list, parse_md5_list from nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file from ziptools import check_inside_zip +if TYPE_CHECKING: + from typing_extensions import Unpack + # Validation types that require console-specific cryptographic keys. # verify.py cannot reproduce these: size checks still apply if combined. _CRYPTO_CHECKS = frozenset({"signature", "crypto"}) @@ -62,7 +66,7 @@ def _parse_validation(validation: list | dict | None) -> list[str]: return [] -def _entry_rule(emu_name: str, f: dict, checks: set[str]) -> dict: +def _entry_rule(emu_name: str, f: dict, checks: Collection[str]) -> dict: """One profile entry's own checks, kept apart from the merged view. Merged by name, Azahar's crypto check on the 3DS otp.bin judged Cemu's @@ -101,7 +105,7 @@ def _entry_rule(emu_name: str, f: dict, checks: set[str]) -> dict: } -def warned_checks(f: dict, checks: set[str]) -> set[str]: +def warned_checks(f: dict, checks: Collection[str]) -> set[str]: """The checks of an entry the code warns about instead of refusing. `on_mismatch: warn` covers every check, while a map names them one by one, as @@ -116,6 +120,21 @@ def warned_checks(f: dict, checks: set[str]) -> set[str]: return set() +def _rule_size_failure(rule: dict, local_path: str) -> str | None: + """Why one entry's size check rejects a file, or None.""" + actual_size = os.path.getsize(local_path) + if rule["sizes"] and actual_size not in rule["sizes"]: + accepted = ",".join(str(s) for s in sorted(rule["sizes"])) + return f"size mismatch: got {actual_size}, accepted [{accepted}]" + if rule["min_size"] is not None and actual_size < rule["min_size"]: + return f"size too small: min {rule['min_size']}, got {actual_size}" + if rule["max_size"] is not None and actual_size > rule["max_size"]: + return f"size too large: max {rule['max_size']}, got {actual_size}" + if rule.get("size_multiple") and actual_size % int(rule["size_multiple"]): + return f"size mismatch: got {actual_size}, accepted multiples of {rule['size_multiple']}" + return None + + def _rule_failure( rule: dict, local_path: str, filename: str, bios_dir: str, hashes: dict, strict: bool = False, @@ -126,16 +145,9 @@ def _rule_failure( """ skip = set() if strict else rule["warn"] if "size" not in skip: - actual_size = os.path.getsize(local_path) - if rule["sizes"] and actual_size not in rule["sizes"]: - accepted = ",".join(str(s) for s in sorted(rule["sizes"])) - return f"size mismatch: got {actual_size}, accepted [{accepted}]" - if rule["min_size"] is not None and actual_size < rule["min_size"]: - return f"size too small: min {rule['min_size']}, got {actual_size}" - if rule["max_size"] is not None and actual_size > rule["max_size"]: - return f"size too large: max {rule['max_size']}, got {actual_size}" - if rule.get("size_multiple") and actual_size % int(rule["size_multiple"]): - return f"size mismatch: got {actual_size}, accepted multiples of {rule['size_multiple']}" + refused = _rule_size_failure(rule, local_path) + if refused: + return refused for hash_type in ("crc32", "md5", "sha1", "sha256"): if rule[hash_type] and hash_type not in skip: if not hashes: @@ -229,6 +241,144 @@ def _labels_widened(profile: dict) -> list[dict]: return widened +def _new_index_entry() -> dict: + return { + "checks": set(), + "sizes": set(), + "min_size": None, + "max_size": None, + "size_multiples": set(), + "crc32": set(), + "md5": set(), + "sha1": set(), + "sha256": set(), + "adler32": set(), + "adler32_byteswap": False, + "crypto_only": set(), + "emulators": set(), + "per_emulator": {}, + "rules": [], + } + + +def _merge_sizes(item: dict, f: dict) -> None: + raw_size = f.get("size") + if raw_size is not None: + if isinstance(raw_size, list): + item["sizes"].update(raw_size) + else: + item["sizes"].add(raw_size) + if f.get("min_size") is not None: + cur = item["min_size"] + item["min_size"] = ( + min(cur, f["min_size"]) if cur is not None else f["min_size"] + ) + if f.get("size_multiple"): + item["size_multiples"].add(int(f["size_multiple"])) + if f.get("max_size") is not None: + cur = item["max_size"] + item["max_size"] = ( + max(cur, f["max_size"]) if cur is not None else f["max_size"] + ) + + +def _hex_values(value: object) -> list[str]: + """Hash values without their 0x prefix, lowercased.""" + values = value if isinstance(value, list) else [value] if value else [] + out = [] + for item in values: + norm = str(item).lower() + if norm.startswith("0x"): + norm = norm[2:] + out.append(norm) + return out + + +def _merge_hashes(item: dict, f: dict, checks: list[str]) -> None: + # Hash checks: collect all accepted hashes as sets (multiple valid + # versions of the same file, e.g. MT-32 ROM versions) + if "crc32" in checks and f.get("crc32"): + item["crc32"].update(_hex_values(f["crc32"])) + # A hash field may carry several accepted values, as a list or as + # the comma-separated string the schema spells out + for hash_type in ("md5", "sha1", "sha256"): + if hash_type in checks and f.get(hash_type): + val = f[hash_type] + values = val if isinstance(val, list) else str(val).split(",") + item[hash_type].update( + str(h).strip().lower() for h in values if str(h).strip() + ) + # Adler32: stored as known_hash_adler32 field (not in validation: list + # for Dolphin, but support it in both forms for future profiles) + item["adler32"].update(_hex_values(f.get("known_hash_adler32") or f.get("adler32"))) + if f.get("adler32_byteswap"): + item["adler32_byteswap"] = True + + +def _expected_values(f: dict, checks: list[str]) -> dict: + """The values an entry's checks compare, for ground truth reporting.""" + expected: dict = {} + if "size" in checks: + for key in ("size", "min_size", "max_size", "size_multiple"): + if f.get(key) is not None: + expected[key] = f[key] + for hash_type in ("crc32", "md5", "sha1", "sha256"): + if hash_type in checks and f.get(hash_type): + expected[hash_type] = f[hash_type] + adler_val_pe = f.get("known_hash_adler32") or f.get("adler32") + if adler_val_pe: + expected["adler32"] = adler_val_pe + for check in sorted(CONTENT_CHECKS & set(checks)): + expected[check] = f.get(check) or {} + return expected + + +def _merge_per_emulator(item: dict, emu_name: str, f: dict, checks: list[str]) -> None: + # Per-emulator ground truth detail + pe = item["per_emulator"] + expected = _expected_values(f, checks) + if emu_name in pe: + # Merge checks from multiple file entries for same emulator + existing = pe[emu_name] + merged_checks = sorted( + set(existing["checks"]) | set(checks) + ) + existing["checks"] = merged_checks + existing["expected"].update(expected) + if f.get("source_ref") and not existing["source_ref"]: + existing["source_ref"] = f.get("source_ref") + else: + pe[emu_name] = { + "checks": sorted(checks), + "source_ref": f.get("source_ref"), + "expected": expected, + } + + +def _index_entry(index: dict[str, dict], emu_name: str, f: dict, checks: list[str]) -> None: + """Merge one checked profile entry into the index.""" + fname = f.get("name", "") + if fname not in index: + index[fname] = _new_index_entry() + item = index[fname] + item["rules"].append(_entry_rule(emu_name, f, checks)) + item["emulators"].add(emu_name) + # A warned check is never a rejection, so it stays out of the + # merged rejection rules. + warned = warned_checks(f, set(checks)) + checks = [check for check in checks if check not in warned] + if not checks: + return + item["checks"].update(checks) + # Track non-reproducible crypto checks + item["crypto_only"].update(c for c in checks if c in _CRYPTO_CHECKS) + # Size checks + if "size" in checks: + _merge_sizes(item, f) + _merge_hashes(item, f, checks) + _merge_per_emulator(item, emu_name, f, checks) + + def _build_validation_index(profiles: dict) -> dict[str, dict]: """Build per-filename validation rules from emulator profiles. @@ -264,116 +414,7 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]: unchecked.add(slot) continue checked.add(slot) - if fname not in index: - index[fname] = { - "checks": set(), - "sizes": set(), - "min_size": None, - "max_size": None, - "size_multiples": set(), - "crc32": set(), - "md5": set(), - "sha1": set(), - "sha256": set(), - "adler32": set(), - "adler32_byteswap": False, - "crypto_only": set(), - "emulators": set(), - "per_emulator": {}, - "rules": [], - } - index[fname]["rules"].append(_entry_rule(emu_name, f, checks)) - index[fname]["emulators"].add(emu_name) - # A warned check is never a rejection, so it stays out of the - # merged rejection rules. - warned = warned_checks(f, set(checks)) - checks = [check for check in checks if check not in warned] - if not checks: - continue - index[fname]["checks"].update(checks) - # Track non-reproducible crypto checks - index[fname]["crypto_only"].update(c for c in checks if c in _CRYPTO_CHECKS) - # Size checks - if "size" in checks: - raw_size = f.get("size") - if raw_size is not None: - if isinstance(raw_size, list): - index[fname]["sizes"].update(raw_size) - else: - index[fname]["sizes"].add(raw_size) - if f.get("min_size") is not None: - cur = index[fname]["min_size"] - index[fname]["min_size"] = ( - min(cur, f["min_size"]) if cur is not None else f["min_size"] - ) - if f.get("size_multiple"): - index[fname]["size_multiples"].add(int(f["size_multiple"])) - if f.get("max_size") is not None: - cur = index[fname]["max_size"] - index[fname]["max_size"] = ( - max(cur, f["max_size"]) if cur is not None else f["max_size"] - ) - # Hash checks: collect all accepted hashes as sets (multiple valid - # versions of the same file, e.g. MT-32 ROM versions) - if "crc32" in checks and f.get("crc32"): - crc_val = f["crc32"] - crc_list = crc_val if isinstance(crc_val, list) else [crc_val] - for cv in crc_list: - norm = str(cv).lower() - if norm.startswith("0x"): - norm = norm[2:] - index[fname]["crc32"].add(norm) - # A hash field may carry several accepted values, as a list or as - # the comma-separated string the schema spells out - for hash_type in ("md5", "sha1", "sha256"): - if hash_type in checks and f.get(hash_type): - val = f[hash_type] - values = val if isinstance(val, list) else str(val).split(",") - for h in values: - if str(h).strip(): - index[fname][hash_type].add(str(h).strip().lower()) - # Adler32: stored as known_hash_adler32 field (not in validation: list - # for Dolphin, but support it in both forms for future profiles) - adler_val = f.get("known_hash_adler32") or f.get("adler32") - for value in adler_val if isinstance(adler_val, list) else [adler_val] if adler_val else []: - norm = str(value).lower() - if norm.startswith("0x"): - norm = norm[2:] - index[fname]["adler32"].add(norm) - if f.get("adler32_byteswap"): - index[fname]["adler32_byteswap"] = True - # Per-emulator ground truth detail - expected: dict = {} - if "size" in checks: - for key in ("size", "min_size", "max_size", "size_multiple"): - if f.get(key) is not None: - expected[key] = f[key] - for hash_type in ("crc32", "md5", "sha1", "sha256"): - if hash_type in checks and f.get(hash_type): - expected[hash_type] = f[hash_type] - adler_val_pe = f.get("known_hash_adler32") or f.get("adler32") - if adler_val_pe: - expected["adler32"] = adler_val_pe - for check in sorted(CONTENT_CHECKS & set(checks)): - expected[check] = f.get(check) or {} - pe_entry = { - "checks": sorted(checks), - "source_ref": f.get("source_ref"), - "expected": expected, - } - pe = index[fname]["per_emulator"] - if emu_name in pe: - # Merge checks from multiple file entries for same emulator - existing = pe[emu_name] - merged_checks = sorted( - set(existing["checks"]) | set(pe_entry["checks"]) - ) - existing["checks"] = merged_checks - existing["expected"].update(pe_entry["expected"]) - if pe_entry["source_ref"] and not existing["source_ref"]: - existing["source_ref"] = pe_entry["source_ref"] - else: - pe[emu_name] = pe_entry + _index_entry(index, emu_name, f, checks) for fname, emu_name, _path in sorted(checked & unchecked): index[fname]["rules"].append(_entry_rule(emu_name, {}, set())) # Convert sets to sorted tuples/lists for determinism @@ -418,9 +459,11 @@ def _emulators_for_check( if check_type in emu_checks: result.append(emu) # adler32 is stored as known_hash, not always in validation list - if check_type == "adler32" and detail.get("expected", {}).get("adler32"): - if emu not in result: - result.append(emu) + if ( + check_type == "adler32" and detail.get("expected", {}).get("adler32") + and emu not in result + ): + result.append(emu) return sorted(result) @@ -433,8 +476,8 @@ def _merged_reason(reasons: list[str]) -> str: Raze lists three BLOOD.RFF sizes and the message named the first one alone. Reasons of one kind are merged into a single accepted list. """ - parsed = [_REASON.match(reason) for reason in reasons] - if all(parsed) and len({(m.group(1), m.group(2)) for m in parsed}) == 1: + parsed = [m for m in (_REASON.match(reason) for reason in reasons) if m] + if len(parsed) == len(reasons) and len({(m.group(1), m.group(2)) for m in parsed}) == 1: accepted = sorted({v for m in parsed for v in m.group(3).split(",") if v}, key=lambda v: (len(v), v)) return f"{parsed[0].group(1)}: got {parsed[0].group(2)}, accepted [{','.join(accepted)}]" @@ -469,43 +512,17 @@ def check_file_validation( if not entry: return None if emulators is not None: - hashes: dict = {} - failures: dict[str, str] = {} - for emu in sorted(emulators): - rules = [r for r in entry.get("rules", []) if r["emulator"] == emu] - if not rules: - continue - reasons = [ - _rule_failure(rule, local_path, filename, bios_dir, hashes, strict) - for rule in rules - ] - if all(reasons): - failures[emu] = _merged_reason(reasons) - if not failures: - return None - first = sorted(failures)[0] - return failures[first], sorted(failures) + return _per_emulator_failure( + entry, local_path, filename, bios_dir, emulators, strict, + ) checks = entry["checks"] pe = entry.get("per_emulator", {}) # Size checks: sizes is a set of accepted values if "size" in checks: - actual_size = os.path.getsize(local_path) - if entry["sizes"] and actual_size not in entry["sizes"]: - expected = ",".join(str(s) for s in sorted(entry["sizes"])) - emus = _emulators_for_check("size", pe) - return f"size mismatch: got {actual_size}, accepted [{expected}]", emus - if entry["min_size"] is not None and actual_size < entry["min_size"]: - emus = _emulators_for_check("size", pe) - return f"size too small: min {entry['min_size']}, got {actual_size}", emus - if entry["max_size"] is not None and actual_size > entry["max_size"]: - emus = _emulators_for_check("size", pe) - return f"size too large: max {entry['max_size']}, got {actual_size}", emus - multiples = entry.get("size_multiples") or set() - if multiples and all(actual_size % m for m in multiples): - emus = _emulators_for_check("size", pe) - accepted = ",".join(str(m) for m in sorted(multiples)) - return f"size mismatch: got {actual_size}, accepted multiples of [{accepted}]", emus + refused = _merged_size_failure(entry, local_path, pe) + if refused: + return refused # A content test passes when one of the entries declaring it accepts # the file, each read as its own code reads it. @@ -516,34 +533,9 @@ def check_file_validation( ): return _CONTENT_REASONS[check], _emulators_for_check(check, pe) - # Hash checks: compute once, reuse for all hash types. - # Each hash field is a set of accepted values (multiple valid ROM versions). - need_hashes = any( - h in checks and entry.get(h) for h in ("crc32", "md5", "sha1", "sha256") - ) or entry.get("adler32") - if need_hashes: - hashes = compute_hashes(local_path) - for hash_type in ("crc32", "md5", "sha1", "sha256"): - if hash_type in checks and entry[hash_type]: - if hashes[hash_type].lower() not in entry[hash_type]: - expected = ",".join(sorted(entry[hash_type])) - emus = _emulators_for_check(hash_type, pe) - return ( - f"{hash_type} mismatch: got {hashes[hash_type]}, " - f"accepted [{expected}]", - emus, - ) - if entry["adler32"]: - actual_adler = hashes["adler32"].lower() - if entry.get("adler32_byteswap"): - actual_adler = _adler32_byteswapped(local_path) - if actual_adler not in entry["adler32"]: - expected = ",".join(sorted(entry["adler32"])) - emus = _emulators_for_check("adler32", pe) - return ( - f"adler32 mismatch: got 0x{actual_adler}, accepted [{expected}]", - emus, - ) + refused = _merged_hash_failure(entry, local_path, checks, pe) + if refused: + return refused # Signature/crypto checks (3DS RSA, AES) if entry["crypto_only"]: @@ -557,6 +549,89 @@ def check_file_validation( return None +def _per_emulator_failure( + entry: dict, local_path: str, filename: str, bios_dir: str, + emulators: set[str], strict: bool, +) -> tuple[str, list[str]] | None: + """Each core judges the file by its own entries for the name.""" + hashes: dict = {} + failures: dict[str, str] = {} + for emu in sorted(emulators): + rules = [r for r in entry.get("rules", []) if r["emulator"] == emu] + if not rules: + continue + reasons = [ + _rule_failure(rule, local_path, filename, bios_dir, hashes, strict) + for rule in rules + ] + refused = [reason for reason in reasons if reason] + if len(refused) == len(reasons): + failures[emu] = _merged_reason(refused) + if not failures: + return None + first = sorted(failures)[0] + return failures[first], sorted(failures) + + +def _merged_size_failure( + entry: dict, local_path: str, pe: dict[str, dict], +) -> tuple[str, list[str]] | None: + actual_size = os.path.getsize(local_path) + if entry["sizes"] and actual_size not in entry["sizes"]: + expected = ",".join(str(s) for s in sorted(entry["sizes"])) + emus = _emulators_for_check("size", pe) + return f"size mismatch: got {actual_size}, accepted [{expected}]", emus + if entry["min_size"] is not None and actual_size < entry["min_size"]: + emus = _emulators_for_check("size", pe) + return f"size too small: min {entry['min_size']}, got {actual_size}", emus + if entry["max_size"] is not None and actual_size > entry["max_size"]: + emus = _emulators_for_check("size", pe) + return f"size too large: max {entry['max_size']}, got {actual_size}", emus + multiples = entry.get("size_multiples") or set() + if multiples and all(actual_size % m for m in multiples): + emus = _emulators_for_check("size", pe) + accepted = ",".join(str(m) for m in sorted(multiples)) + return f"size mismatch: got {actual_size}, accepted multiples of [{accepted}]", emus + return None + + +def _merged_hash_failure( + entry: dict, local_path: str, checks: list[str], pe: dict[str, dict], +) -> tuple[str, list[str]] | None: + # Hash checks: compute once, reuse for all hash types. + # Each hash field is a set of accepted values (multiple valid ROM versions). + need_hashes = any( + h in checks and entry.get(h) for h in ("crc32", "md5", "sha1", "sha256") + ) or entry.get("adler32") + if not need_hashes: + return None + hashes = compute_hashes(local_path) + for hash_type in ("crc32", "md5", "sha1", "sha256"): + if ( + hash_type in checks and entry[hash_type] + and hashes[hash_type].lower() not in entry[hash_type] + ): + expected = ",".join(sorted(entry[hash_type])) + emus = _emulators_for_check(hash_type, pe) + return ( + f"{hash_type} mismatch: got {hashes[hash_type]}, " + f"accepted [{expected}]", + emus, + ) + if entry["adler32"]: + actual_adler = hashes["adler32"].lower() + if entry.get("adler32_byteswap"): + actual_adler = _adler32_byteswapped(local_path) + if actual_adler not in entry["adler32"]: + expected = ",".join(sorted(entry["adler32"])) + emus = _emulators_for_check("adler32", pe) + return ( + f"adler32 mismatch: got 0x{actual_adler}, accepted [{expected}]", + emus, + ) + return None + + def read_from_system_dir(file_entry: dict, standalone: bool = False) -> bool: """Whether the emulator reads this entry from the system directory. @@ -784,6 +859,37 @@ def deliverable(entries: list[dict], standalone: bool, platform: str = "") -> li ] +def _platform_accepted(file_entry: dict, platform_digest: str) -> set[str]: + """The values of the digest the frontend compares that the entry declares.""" + declared = file_entry.get(platform_digest) or "" + if platform_digest == "md5": + return set(parse_md5_list(declared)) + if isinstance(declared, str) and declared: + return {declared.lower()} + if isinstance(declared, list): + return {str(value).lower() for value in declared} + return set() + + +def _variant_candidates(expected: dict, indexes: dict, fname: str) -> Iterator[str]: + """The sha1 of each held file that may stand for a name, best evidence first.""" + # Sorted: the index holds sets, whose order follows the per-process + # string hash, and the first passing candidate is the one shipped. + for hash_type, index_key in ( + ("sha1", None), ("md5", "by_md5"), ("crc32", "by_crc32"), ("sha256", "by_sha256"), + ): + for value in sorted(expected.get(hash_type) or []): + if index_key is None: + yield value + continue + found = indexes.get(index_key, {}).get(value) + if isinstance(found, str): + yield found + elif isinstance(found, list): + yield from found + yield from indexes.get("by_name", {}).get(fname, []) + + def find_validated_variant( file_entry: dict, db: dict, @@ -811,38 +917,14 @@ def find_validated_variant( if platform_digest: if file_entry.get("zipped_file"): return None - declared = file_entry.get(platform_digest) or "" - if platform_digest == "md5": - accepted = set(parse_md5_list(declared)) - elif isinstance(declared, str) and declared: - accepted = {declared.lower()} - elif isinstance(declared, list): - accepted = {str(value).lower() for value in declared} + accepted = _platform_accepted(file_entry, platform_digest) files_db = db.get("files", {}) indexes = db.get("indexes", {}) current_real = os.path.realpath(current_path) seen: set[str] = set() - def candidates() -> Iterator[str]: - # Sorted: the index holds sets, whose order follows the per-process - # string hash, and the first passing candidate is the one shipped. - expected = validation_index[fname] - for hash_type, index_key in ( - ("sha1", None), ("md5", "by_md5"), ("crc32", "by_crc32"), ("sha256", "by_sha256"), - ): - for value in sorted(expected.get(hash_type) or []): - if index_key is None: - yield value - continue - found = indexes.get(index_key, {}).get(value) - if isinstance(found, str): - yield found - elif isinstance(found, list): - yield from found - yield from indexes.get("by_name", {}).get(fname, []) - - for sha1 in candidates(): + for sha1 in _variant_candidates(validation_index[fname], indexes, fname): entry = files_db.get(sha1) or {} path = entry.get("path", "") if not path or not os.path.exists(path): @@ -900,7 +982,7 @@ def agnostic_substitute( def frontend_digest_matches( - file_entry: dict, local_path: str, algorithm: str, rule: str = "" + file_entry: dict, local_path: str | None, algorithm: str, rule: str = "" ) -> bool: """Whether the frontend's own digest accepts the file. @@ -947,9 +1029,9 @@ def digest_verdict( # RomM reads an absent size as 0: such an entry never verifies. if size != int(file_entry.get("size") or 0): return False - actual = hashes() + digests = hashes() return any( - actual[field].lower() == str(file_entry[field]).strip().lower() + digests[field].lower() == str(file_entry[field]).strip().lower() for field in ("md5", "sha1", "crc32") if file_entry.get(field) ) @@ -970,7 +1052,9 @@ def digest_verdict( if not composite_only and actual in declared: return True member_digest = composite() - return bool(member_digest) and member_digest.lower() in declared + if not member_digest: + return False + return member_digest.lower() in declared def inner_rom_check(file_entry: dict, local_path: str) -> str: @@ -1060,6 +1144,10 @@ def _owners_of(destination: str, name: str, owners: dict) -> set[str]: return {emu for tail, emu in matching if len(tail) == longest} +class _Judging(TypedDict, total=False): + emulators: set[str] | None + + def validated_choice( file_entry: dict, local_path: str | None, @@ -1069,7 +1157,7 @@ def validated_choice( platform_digest: str | None, destination: str = "", owners: dict | None = None, - emulators: set[str] | None = None, + **judging: Unpack[_Judging], ) -> tuple[str | None, str | None]: """The file a platform destination ships, and the disagreement if any. @@ -1078,7 +1166,12 @@ def validated_choice( manifest both read this, so they name the same file. A destination another emulator declares more precisely is that emulator's: ZEsarUX's 48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom. + ``emulators`` names the cores that judge the file, each by its own entries. """ + unknown = [key for key in judging if key not in _Judging.__annotations__] + if unknown: + raise TypeError(f"validated_choice() got an unexpected keyword argument '{unknown[0]}'") + emulators = judging.get("emulators") if not local_path or not validation_index: return local_path, None name = file_entry.get("name", "") @@ -1093,6 +1186,7 @@ def validated_choice( # The cores that read this destination judge it, each by its own # entries. judges = owning & set(rules["emulators"]) + def check(path: str, strict: bool) -> tuple[str, list[str]] | None: return check_file_validation(path, name, validation_index, bios_dir, judges, strict) @@ -1151,8 +1245,8 @@ def slot_index(files: list) -> dict[tuple[str, str], list[dict]]: matches them: one pass, then one lookup per extra.""" index: dict[tuple[str, str], list[dict]] = {} for entry in files or []: - if isinstance(entry, dict): - name = entry.get("name") + if isinstance(entry, dict) and isinstance(entry.get("name"), str): + name = entry["name"] index.setdefault((name, entry.get("path") or name), []).append(entry) return index From a557102f4a4b2ae18b757c09ff5a205ce5bb7180 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:53:58 +0100 Subject: [PATCH 3/9] refactor: split the cross reference profile pass --- scripts/cross_reference.py | 757 ++++++++++++++++++++++--------------- 1 file changed, 446 insertions(+), 311 deletions(-) diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index 40991523c..cd37b85f5 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -20,7 +20,10 @@ import sys import zipfile import zlib from collections import Counter +import dataclasses +from dataclasses import dataclass from pathlib import Path +from typing import TYPE_CHECKING, TypedDict sys.path.insert(0, os.path.dirname(__file__)) from alternatives import set_keys, set_requirements, settle_sets @@ -79,6 +82,9 @@ from validation import ( with_archive_members, ) +if TYPE_CHECKING: + from typing_extensions import Unpack + yaml = require_yaml() DEFAULT_EMULATORS_DIR = "emulators" @@ -97,8 +103,8 @@ def load_platform_files( RetroArch writes `sega-mega-cd`, and an exact match called 924 declared files undeclared. """ - declared = {} - platform_data_dirs = {} + declared: dict[str, set[str]] = {} + platform_data_dirs: dict[str, set[str]] = {} for platform_name in platforms or list_registered_platforms( platforms_dir ): @@ -277,11 +283,10 @@ def _resolve_source( key = fname.lower() if key in by_name_lower and _folded_hit(by_name_lower[key]): return "bios" - if basename: - if basename.lower() in by_name_lower and _folded_hit( - by_name_lower[basename.lower()] - ): - return "bios" + if basename and basename.lower() in by_name_lower and _folded_hit( + by_name_lower[basename.lower()] + ): + return "bios" # bios/ via by_path_suffix (regional variants) if by_path_suffix and fname in by_path_suffix and _can_be(by_path_suffix[fname]): return "bios" @@ -749,129 +754,89 @@ def profile_breakdown(data: dict) -> str: return ", ".join(parts) -def _cross_reference_profile( - emu_name: str, - profile: dict, - declared: dict[str, set[str]], - report: dict, - index: dict, - standalone_cores: set[str] | None = None, - platform: str = "", -) -> None: - """Compare one emulator profile against what the platforms declare. +def _effective_path(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: + # The destination the running build reads, as find_undeclared_files + # takes it: Batocera's standalone Cemu reads keys.txt at + # standalone_path, and the libretro Cemu/keys.txt reported here + # settled the declaration on a slot the platform never fills. + if is_standalone: + return f.get("standalone_path") or f.get("path") or fname + if save_root: + return f.get("path") or fname + return system_dir_path(f, f.get("path") or fname) - *platform* is the platform key under --platform, empty for the whole - tree. It decides, through the functions verify reads, which entries the - platform's launcher never opens and which ones its emulator package - already installs. - Split out of cross_reference, where it was a 200-line loop body that - carried the whole function's branching: every file is resolved by name, - by path, by hash and by archive membership before it can be called a - gap. *index* carries the database lookups those steps share. - """ - by_name = index["by_name"] - by_name_lower = index["by_name_lower"] - by_path_suffix = index["by_path_suffix"] - data_names = index["data_names"] - all_declared = index["all_declared"] - emu_files = profile.get("files", []) - systems = profile.get("systems", []) +@dataclass +class _ProfileComparison: + """One profile's entries against the platforms' declarations.""" - # Skip filename-agnostic profiles (BIOS detected without fixed names) - if profile.get("bios_mode") == "agnostic": - return - - if all_declared is not None: - platform_names = all_declared - else: - platform_names = set() - for sys_id in systems: - platform_names.update(declared.get(_norm_system_id(sys_id), set())) - - # The build a platform runs decides which entries it reads, as in - # find_undeclared_files: without a platform, the libretro build. - layouts = platform_layouts(emu_name, profile, standalone_cores or set()) - # Each file under each layout the platform gives the emulator: both, for - # one it launches as a libretro core and standalone. - layout_files = [(f, standalone) for view, standalone in layouts for f in view.get("files", [])] - gaps = [] - covered = [] - unsourceable_list: list[dict] = [] - archive_gaps: dict[tuple, dict] = {} - seen_files: set[tuple] = set() - - # The entries of one profile on one slot are the versions its code - # accepts there (raze's ten DUKE3D.GRP): holding any of them fills the - # slot, as verify --emulator credits it. - versions: dict[tuple, list[dict]] = {} - for f, is_standalone in layout_files: - versions.setdefault(slot_key(f, is_standalone), []).append(f) - - # What became of each entry, so the heading adds up: a file a platform - # declares, one it does not, or one set aside and why. An entry read by - # two builds keeps the first answer that compares it. Each layout lists - # the profile's entries in their order, so a position names one entry. - position = {id(f): i for view, _ in layouts for i, f in enumerate(view.get("files", []))} - fates: dict[int, str] = {} + emu_name: str + profile: dict + index: dict + platform_names: set[str] + platform: str + layouts: list + versions: dict[tuple, list[dict]] = dataclasses.field(default_factory=dict) + position: dict[int, int] = dataclasses.field(default_factory=dict) + gaps: list[dict] = dataclasses.field(default_factory=list) + covered: list[dict] = dataclasses.field(default_factory=list) + unsourceable_list: list[dict] = dataclasses.field(default_factory=list) + archive_gaps: dict[tuple, dict] = dataclasses.field(default_factory=dict) + seen_files: set[tuple] = dataclasses.field(default_factory=set) + fates: dict[int, str] = dataclasses.field(default_factory=dict) # Grouped entries met, as (set keys, entry, fills, the list holding # its row, the row): settled once the profile is read. - set_records: list[tuple[tuple, dict, bool, list | None, dict | None]] = [] - archive_rows: list[dict] = [] + set_records: list[tuple[tuple, dict, bool, list | None, dict | None]] = dataclasses.field( + default_factory=list + ) + archive_rows: list[dict] = dataclasses.field(default_factory=list) - def fate(f: dict, what: str) -> None: - key = position[id(f)] - current = fates.get(key) + def fate(self, f: dict, what: str) -> None: + key = self.position[id(f)] + current = self.fates.get(key) if current is None or (current in SET_ASIDE and what not in SET_ASIDE): - fates[key] = what + self.fates[key] = what - for f, is_standalone in layout_files: + def compare(self, f: dict, is_standalone: bool) -> None: + """File one entry of one build: declared, a gap, or set aside.""" fname = f.get("name", "") - # The destination the running build reads, as find_undeclared_files - # takes it: Batocera's standalone Cemu reads keys.txt at - # standalone_path, and the libretro Cemu/keys.txt reported here - # settled the declaration on a slot the platform never fills. + platform = self.platform save_root = read_from_save_dir(f, is_standalone) - if is_standalone: - effective_path = f.get("standalone_path") or f.get("path") or fname - elif save_root: - effective_path = f.get("path") or fname - else: - effective_path = system_dir_path(f, f.get("path") or fname) + effective_path = _effective_path(f, fname, is_standalone, save_root) slot = slot_key(f, is_standalone) seen_key = slot - if len(layouts) > 1: + if len(self.layouts) > 1: # One file read at one path by both builds counts once. seen_key = (effective_path.casefold(), seen_key) if not fname: - fate(f, "outside_scope") - continue - if seen_key in seen_files: - fate(f, "other_versions") - continue + self.fate(f, "outside_scope") + return + if seen_key in self.seen_files: + self.fate(f, "other_versions") + return if unread_on(f, platform): - fate(f, "not_read") - continue + self.fate(f, "not_read") + return # Collect unsourceable files separately (documented, not a gap) unsourceable_reason = f.get("unsourceable", "") - keys = set_keys((emu_name, is_standalone), f) + keys = set_keys((self.emu_name, is_standalone), f) if unsourceable_reason: - seen_files.add(seen_key) - fate(f, "unsourceable") + self.seen_files.add(seen_key) + self.fate(f, "unsourceable") row = { "name": fname, "required": f.get("required", False), "reason": unsourceable_reason, "source_ref": f.get("source_ref", ""), } - unsourceable_list.append(row) - set_records.append((keys, f, False, unsourceable_list, row)) - continue + self.unsourceable_list.append(row) + self.set_records.append((keys, f, False, self.unsourceable_list, row)) + return if outside_gap_scope(f, is_standalone): - fate(f, "outside_scope") - continue + self.fate(f, "outside_scope") + return archive = f.get("archive") @@ -881,77 +846,88 @@ def _cross_reference_profile( # A platform declares files of its BIOS tree: none answers for one # the core reads below the save directory. in_platform = not save_root and f.get("root") not in OUTER_ROOTS and declaration_settles( - f, fname, platform_names, effective_path, index.get("folded_slots", frozenset()), - index.get("declared_contents"), + f, fname, self.platform_names, effective_path, + self.index.get("folded_slots", frozenset()), + self.index.get("declared_contents"), ) if in_platform: - seen_files.add(seen_key) - fate(f, "declared") - set_records.append((keys, f, True, None, None)) - covered.append({ + self.seen_files.add(seen_key) + self.fate(f, "declared") + self.set_records.append((keys, f, True, None, None)) + self.covered.append({ "name": fname, "path": effective_path, "required": f.get("required", False), "in_platform": True, }) - continue + return - seen_files.add(seen_key) - fate(f, "undeclared") + self.seen_files.add(seen_key) + self.fate(f, "undeclared") if archive: - archive_key = ( - archive, - f.get("system"), - f.get("selection_slot"), - f.get("mode", "both"), - ) - if archive_key not in archive_gaps: - source = _resolve_archive_source( - archive, by_name, by_name_lower, data_names, - by_path_suffix, - ) - archive_gaps[archive_key] = { - "name": archive, - "path": archive, - "required": False, - "note": "", - "source_ref": "", - "in_platform": False, - "in_repo": source != "missing", - "source": source, - "archive": archive, - "archive_file_count": 0, - "archive_required_count": 0, - } - entry = archive_gaps[archive_key] - if entry["archive_file_count"] == 0: - # The archive's own declaration names its sets: an archive - # is a member like a loose file (Kronos' stvbios.zip). - own = archive_entry(archive, emu_files) - set_records.append(( - set_keys((emu_name, is_standalone), own), own, - entry["in_repo"], archive_rows, entry, - )) - archive_rows.append(entry) - entry["archive_file_count"] += 1 - if f.get("required", False): - entry["archive_required_count"] += 1 - entry["required"] = True - if not entry["source_ref"] and f.get("source_ref"): - entry["source_ref"] = f["source_ref"] - continue + self._archive_gap(f, archive, is_standalone) + return + self._loose_gap(f, fname, is_standalone, save_root, effective_path, slot, keys) + def _archive_gap(self, f: dict, archive: str, is_standalone: bool) -> None: + archive_key = ( + archive, + f.get("system"), + f.get("selection_slot"), + f.get("mode", "both"), + ) + if archive_key not in self.archive_gaps: + source = _resolve_archive_source( + archive, self.index["by_name"], self.index["by_name_lower"], + self.index["data_names"], self.index["by_path_suffix"], + ) + self.archive_gaps[archive_key] = { + "name": archive, + "path": archive, + "required": False, + "note": "", + "source_ref": "", + "in_platform": False, + "in_repo": source != "missing", + "source": source, + "archive": archive, + "archive_file_count": 0, + "archive_required_count": 0, + } + entry = self.archive_gaps[archive_key] + if entry["archive_file_count"] == 0: + # The archive's own declaration names its sets: an archive + # is a member like a loose file (Kronos' stvbios.zip). + own = archive_entry(archive, self.profile.get("files", [])) + self.set_records.append(( + set_keys((self.emu_name, is_standalone), own), own, + entry["in_repo"], self.archive_rows, entry, + )) + self.archive_rows.append(entry) + entry["archive_file_count"] += 1 + if f.get("required", False): + entry["archive_required_count"] += 1 + entry["required"] = True + if not entry["source_ref"] and f.get("source_ref"): + entry["source_ref"] = f["source_ref"] + + def _loose_gap( + self, f: dict, fname: str, is_standalone: bool, save_root: bool, + effective_path: str, slot: tuple, keys: tuple, + ) -> None: + emu_name = self.emu_name + platform = self.platform # --- resolve source provenance --- # A release asset is held when the database records it, as any other # file: storage says where the bytes are served from, not that the # collection has them (kenji-nx's user-picked firmware package). source = next( ( - found for version in versions[slot] + found for version in self.versions[slot] if (found := entry_source( - {**version, "source_profile": emu_name}, index, + {**version, "source_profile": emu_name}, self.index, )) is not None ), "missing", @@ -980,65 +956,131 @@ def _cross_reference_profile( entry["unplaced"] = f["unplaced"] elif f.get("root") in OUTER_ROOTS: entry["root"] = f["root"] - elif index.get("launcher_candidates") is not None: + elif self.index.get("launcher_candidates") is not None: # What verify hands the launcher layer for the same entry. probe = { **f, "profile": emu_name, - "emulator": profile.get("emulator", emu_name), + "emulator": self.profile.get("emulator", emu_name), "path": effective_path, "in_repo": in_repo, "bundled": entry["bundled"], } - index["launcher_candidates"].append( + self.index["launcher_candidates"].append( (emu_name, is_standalone, f, probe, entry) ) - gaps.append(entry) - set_records.append((keys, f, in_repo, gaps, entry)) + self.gaps.append(entry) + self.set_records.append((keys, f, in_repo, self.gaps, entry)) - # One need per set: a member another one fills is not a gap, and a set - # nobody holds is one gap under its first member (alternatives.py), as - # verify and the packs count it. - # Archive units rank first among equals, as the builder orders them. - grouped = sorted( - (r for r in set_records if r[0]), key=lambda r: r[3] is not archive_rows - ) - requirements = set_requirements(profile) - excused, standing = settle_sets( - [(keys, f, fills) for keys, f, fills, _l, _r in grouped], - lambda key: requirements.get(key[1], True), - ) - for at, (_keys, member, _fills, rows, set_row) in enumerate(grouped): - if set_row is None or rows is None: - continue - if at in standing: - set_row["alternatives"] = standing[at].others - set_row["required"] = standing[at].required - if at in excused: - rows.remove(set_row) - if id(member) in position: - fates[position[id(member)]] = "other_versions" + def settle(self) -> None: + # One need per set: a member another one fills is not a gap, and a set + # nobody holds is one gap under its first member (alternatives.py), as + # verify and the packs count it. + # Archive units rank first among equals, as the builder orders them. + grouped = sorted( + (r for r in self.set_records if r[0]), key=lambda r: r[3] is not self.archive_rows + ) + requirements = set_requirements(self.profile) + excused, standing = settle_sets( + [(keys, f, fills) for keys, f, fills, _l, _r in grouped], + lambda key: requirements.get(key[1], True), + ) + for at, (_keys, member, _fills, rows, set_row) in enumerate(grouped): + if set_row is None or rows is None: + continue + if at in standing: + set_row["alternatives"] = standing[at].others + set_row["required"] = standing[at].required + if at in excused: + rows.remove(set_row) + if id(member) in self.position: + self.fates[self.position[id(member)]] = "other_versions" - for ag in sorted(archive_gaps.values(), key=lambda e: e["name"]): - if any(ag is row for row in archive_rows): - gaps.append(ag) + for ag in sorted(self.archive_gaps.values(), key=lambda e: e["name"]): + if any(ag is row for row in self.archive_rows): + self.gaps.append(ag) - tally = Counter(fates.values()) - report[emu_name] = { - "emulator": profile.get("emulator", emu_name), - "systems": systems, - "total_files": len(emu_files), - "platform_covered": len(covered), - **_gap_counts(gaps), - "gap_details": gaps, - "unsourceable": unsourceable_list, - # Entries, not rows: an archive's members are one gap row. - "declared_files": tally["declared"], - "undeclared_files": tally["undeclared"], - "unsourceable_files": tally["unsourceable"], - "set_aside": {key: tally[key] for key in SET_ASIDE}, + def summary(self) -> dict: + tally = Counter(self.fates.values()) + profile = self.profile + return { + "emulator": profile.get("emulator", self.emu_name), + "systems": profile.get("systems", []), + "total_files": len(profile.get("files", [])), + "platform_covered": len(self.covered), + **_gap_counts(self.gaps), + "gap_details": self.gaps, + "unsourceable": self.unsourceable_list, + # Entries, not rows: an archive's members are one gap row. + "declared_files": tally["declared"], + "undeclared_files": tally["undeclared"], + "unsourceable_files": tally["unsourceable"], + "set_aside": {key: tally[key] for key in SET_ASIDE}, + } + + +def _cross_reference_profile( + emu_name: str, + profile: dict, + declared: dict[str, set[str]], + report: dict, + index: dict, + standalone_cores: set[str] | None = None, + platform: str = "", +) -> None: + """Compare one emulator profile against what the platforms declare. + + *platform* is the platform key under --platform, empty for the whole + tree. It decides, through the functions verify reads, which entries the + platform's launcher never opens and which ones its emulator package + already installs. + + Split out of cross_reference, where it was a 200-line loop body that + carried the whole function's branching: every file is resolved by name, + by path, by hash and by archive membership before it can be called a + gap. *index* carries the database lookups those steps share. + """ + all_declared = index["all_declared"] + systems = profile.get("systems", []) + + # Skip filename-agnostic profiles (BIOS detected without fixed names) + if profile.get("bios_mode") == "agnostic": + return + + if all_declared is not None: + platform_names = all_declared + else: + platform_names = set() + for sys_id in systems: + platform_names.update(declared.get(_norm_system_id(sys_id), set())) + + # The build a platform runs decides which entries it reads, as in + # find_undeclared_files: without a platform, the libretro build. + layouts = platform_layouts(emu_name, profile, standalone_cores or set()) + comparison = _ProfileComparison(emu_name, profile, index, platform_names, platform, layouts) + # Each file under each layout the platform gives the emulator: both, for + # one it launches as a libretro core and standalone. + layout_files = [(f, standalone) for view, standalone in layouts for f in view.get("files", [])] + + # The entries of one profile on one slot are the versions its code + # accepts there (raze's ten DUKE3D.GRP): holding any of them fills the + # slot, as verify --emulator credits it. + for f, is_standalone in layout_files: + comparison.versions.setdefault(slot_key(f, is_standalone), []).append(f) + + # What became of each entry, so the heading adds up: a file a platform + # declares, one it does not, or one set aside and why. An entry read by + # two builds keeps the first answer that compares it. Each layout lists + # the profile's entries in their order, so a position names one entry. + comparison.position = { + id(f): i for view, _ in layouts for i, f in enumerate(view.get("files", [])) } + for f, is_standalone in layout_files: + comparison.compare(f, is_standalone) + comparison.settle() + report[emu_name] = comparison.summary() + def _gap_counts(gaps: list[dict]) -> dict[str, int]: """The per-source tallies of a profile's gap rows.""" @@ -1208,6 +1250,76 @@ class _NameHolder: return found +def _held_by_setting( + name: str, + settings: dict, + readers: list[str], + profiles: dict[str, dict], + holder: _NameHolder, + db: dict, +) -> bool: + """Whether the setting the name is written to reads a held file. + + A placeholder read from the setting takes the held dump the + catalogues name after the model the launcher's name spells. + """ + entries = [ + entry + for key in readers + for entry in profiles[key].get("files") or [] + if settings[name] and set_by(entry, settings[name]) + ] + return any(holder._entry_held(entry) for entry in entries) or any( + "<" in str(entry.get("name", "")) + and any( + name_match_size_ok(entry, found.get("size")) + for found in catalogued_model_files(name, db) + ) + for entry in entries + ) + + +def _unsourceable_names(readers: list[str], profiles: dict[str, dict]) -> dict[str, str]: + return { + str(n).rsplit("/", 1)[-1]: str(entry["unsourceable"]) + for key in readers + for entry in profiles[key].get("files") or [] + if entry.get("unsourceable") + for n in (entry.get("name"), *(entry.get("aliases") or [])) + if n + } + + +def _add_name_row( + by_key: dict[str, dict], + platform: str, + name: str, + found: tuple[str, bool] | None, + folds: bool, + reader: dict, + unsourceable: dict[str, str], +) -> None: + """Add a launcher record to the row of a name the collection lacks.""" + key = name.casefold() if folds else name + row = by_key.get(key) + if row is None: + row = by_key[key] = { + "platform": platform, + "name": name, + "emulators": [], + "readers": [], + } + if found: + row["held_as"] = found[0] + reason = unsourceable.get(name.rsplit("/", 1)[-1]) + if reason and "unsourceable" not in row: + row["unsourceable"] = reason + if reader["emulator"] not in row["emulators"]: + row["emulators"].append(reader["emulator"]) + if reader not in row["readers"]: + row["readers"].append(reader) + + def launcher_reads_not_held( configs: dict[str, dict], db: dict, @@ -1265,29 +1377,10 @@ def launcher_reads_not_held( if str(record.get("search_dir") or "") in PLATFORM_OWN_FOLDERS: continue settings = name_settings(record, names) - - def by_setting(name: str) -> bool: - """Whether the setting the name is written to reads a held file. - - A placeholder read from the setting takes the held dump the - catalogues name after the model the launcher's name spells. - """ - entries = [ - entry - for key in readers - for entry in profiles[key].get("files") or [] - if settings[name] and set_by(entry, settings[name]) - ] - return any(holder._entry_held(entry) for entry in entries) or any( - "<" in str(entry.get("name", "")) - and any( - name_match_size_ok(entry, found.get("size")) - for found in catalogued_model_files(name, db) - ) - for entry in entries - ) - - by_model = {name for name in names if by_setting(name)} + by_model = { + name for name in names + if _held_by_setting(name, settings, readers, profiles, holder, db) + } if record.get("kind") == "names_searched" and any( (found := holder.held(name)) and (found[1] or folds) for name in names ): @@ -1301,36 +1394,12 @@ def launcher_reads_not_held( } # A name a reader's entry declares unsourceable is no gap: its # row carries the reason and is counted apart. - unsourceable = { - str(n).rsplit("/", 1)[-1]: str(entry["unsourceable"]) - for key in readers - for entry in profiles[key].get("files") or [] - if entry.get("unsourceable") - for n in (entry.get("name"), *(entry.get("aliases") or [])) - if n - } + unsourceable = _unsourceable_names(readers, profiles) for name in names: found = holder.held(name) if found and (found[1] or folds) or name in by_model: continue - key = name.casefold() if folds else name - row = by_key.get(key) - if row is None: - row = by_key[key] = { - "platform": platform, - "name": name, - "emulators": [], - "readers": [], - } - if found: - row["held_as"] = found[0] - reason = unsourceable.get(name.rsplit("/", 1)[-1]) - if reason and "unsourceable" not in row: - row["unsourceable"] = reason - if reader["emulator"] not in row["emulators"]: - row["emulators"].append(reader["emulator"]) - if reader not in row["readers"]: - row["readers"].append(reader) + _add_name_row(by_key, platform, name, found, folds, reader, unsourceable) rows.extend(by_key[key] for key in sorted(by_key, key=str.casefold)) return rows @@ -1390,18 +1459,25 @@ def print_launcher_reads(rows: list[dict]) -> None: ) +class ReportScope(TypedDict, total=False): + """What narrows a cross_reference run: the declarations it compares + against and the platform it answers for.""" + + all_declared: dict[str, list[tuple[int | None, str]]] | None + standalone_cores: set[str] | None + folded_slots: frozenset[str] + platform: str + launcher_layer: LauncherLayer | None + declared_contents: dict[str, set[str]] | None + + def cross_reference( profiles: dict[str, dict], declared: dict[str, set[str]], db: dict, platform_data_dirs: dict[str, set[str]] | None = None, data_names: set[str] | None = None, - all_declared: dict[str, list[tuple[int | None, str]]] | None = None, - standalone_cores: set[str] | None = None, - folded_slots: frozenset[str] = frozenset(), - platform: str = "", - launcher_layer: LauncherLayer | None = None, - declared_contents: dict[str, set[str]] | None = None, + **scope: Unpack[ReportScope], ) -> dict: """Compare emulator profiles against platform declarations. @@ -1418,6 +1494,15 @@ def cross_reference( instead of the per-system lookup. This is appropriate for the global gap analysis page where "undeclared" means "no platform declares it at all". """ + unknown = [key for key in scope if key not in ReportScope.__annotations__] + if unknown: + raise TypeError(f"cross_reference() got an unexpected keyword argument '{unknown[0]}'") + all_declared = scope.get("all_declared") + standalone_cores = scope.get("standalone_cores") + folded_slots = scope.get("folded_slots", frozenset()) + platform = scope.get("platform", "") + launcher_layer = scope.get("launcher_layer") + declared_contents = scope.get("declared_contents") platform_data_dirs = platform_data_dirs or {} by_name = db.get("indexes", {}).get("by_name", {}) by_name_lower = {k.lower(): k for k in by_name} @@ -1426,7 +1511,7 @@ def cross_reference( by_sha256 = db.get("indexes", {}).get("by_sha256", {}) by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {}) db_files = db.get("files", {}) - report = {} + report: dict[str, dict] = {} index = { "by_name": by_name, @@ -1474,7 +1559,7 @@ def print_report( # collection by design, as verify and the gaps page say: not a file to find. bundled = 0 - for emu_name, data in sorted(report.items()): + for _emu_name, data in sorted(report.items()): gaps = data["gaps"] if gaps == 0 and not show_clean: continue @@ -1528,7 +1613,7 @@ def print_report( print(f" {bundled} bundled with their emulator, not packed") -def main() -> None: +def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description="Emulator vs platform gap analysis") parser.add_argument( "--emulators-dir", default=DEFAULT_EMULATORS_DIR, @@ -1551,6 +1636,87 @@ def main() -> None: parser.add_argument( "--list-emulators", action="store_true", help="List available emulators" ) + return parser + + +@dataclass(frozen=True) +class _PlatformScope: + """The profiles a --platform run compares, and how the platform runs them.""" + + profiles: dict[str, dict] + standalone_cores: set[str] + config: dict + relevant: set[str] + run_anywhere: set[str] + + +def _platform_scope( + args: argparse.Namespace, parser: argparse.ArgumentParser, profiles: dict[str, dict], +) -> _PlatformScope: + from common import load_target_config, resolve_platform_cores + + try: + target_cores = ( + load_target_config(args.platform, args.target, args.platforms_dir) + if args.target + else None + ) + except (FileNotFoundError, ValueError) as exc: + # A typo ended in a traceback where verify and slots name the + # closest target. + parser.error(str(exc)) + config = load_platform_config(args.platform, args.platforms_dir) + relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) + run_anywhere = ( + set(resolve_platform_cores(config, profiles)) if args.target else relevant + ) + return _PlatformScope( + {k: v for k, v in profiles.items() if k in relevant}, + standalone_set(config), + config, + relevant, + run_anywhere, + ) + + +def _launcher_rows( + args: argparse.Namespace, + selected: list[str] | None, + db: dict, + all_profiles: dict[str, dict], + registry: dict, + emulator: str | None, +) -> tuple[list[dict], list[dict]]: + """The names a launcher reads that the collection lacks, and the + launcher records nothing proves.""" + # Counted apart from the profile gaps: a name only a launcher reads is + # reported, not yet judged. + launcher_reads = launcher_reads_not_held( + { + name: load_platform_config(name, args.platforms_dir) + for name in (selected or list_registered_platforms(args.platforms_dir)) + }, + db, all_profiles, registry, emulator or "", + ) + + unproven = [ + row for row in launcher_unproven( + { + name: load_platform_config(name, args.platforms_dir) + for name in (selected or list_registered_platforms(args.platforms_dir)) + }, + all_profiles, + ) + if not emulator or any( + emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles)) + for part in row["emulator"].split(", ") + ) + ] + return launcher_reads, unproven + + +def main() -> None: + parser = _build_parser() args = parser.parse_args() from common import work_from_repo_root @@ -1595,32 +1761,17 @@ def main() -> None: if args.target and not args.platform: parser.error("--target requires --platform") + platform_scope: _PlatformScope | None = None standalone_cores: set[str] = set() if args.platform: - from common import load_target_config, resolve_platform_cores - - try: - target_cores = ( - load_target_config(args.platform, args.target, args.platforms_dir) - if args.target - else None - ) - except (FileNotFoundError, ValueError) as exc: - # A typo ended in a traceback where verify and slots name the - # closest target. - parser.error(str(exc)) - config = load_platform_config(args.platform, args.platforms_dir) - relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) - run_anywhere = ( - set(resolve_platform_cores(config, profiles)) if args.target else relevant - ) - profiles = {k: v for k, v in profiles.items() if k in relevant} - standalone_cores = standalone_set(config) + platform_scope = _platform_scope(args, parser, profiles) + profiles = platform_scope.profiles + standalone_cores = platform_scope.standalone_cores else: # The tree as every platform runs it: a profile some platform runs # standalone keeps its standalone entries. Laid out as libretro only, # eka2l1, dolphin and xenia-edge lost 133 files no platform declares. - from common import list_registered_platforms, merged_standalone_set + from common import merged_standalone_set standalone_cores = merged_standalone_set( load_platform_config(name, args.platforms_dir) @@ -1628,7 +1779,8 @@ def main() -> None: ) if not profiles: - if emulator and args.target and emulator in run_anywhere: + if (emulator and args.target and platform_scope is not None + and emulator in platform_scope.run_anywhere): raise SystemExit( f"ERROR: {emulator} is not built for {args.platform}'s " f"{args.target} target; {args.platform} runs it elsewhere " @@ -1655,52 +1807,35 @@ def main() -> None: ], db, ), - platform=config.get("_key", args.platform) if args.platform else "", + platform=( + platform_scope.config.get("_key", args.platform) if platform_scope else "" + ), # What the platform's launchers open, as verify and the builder read it. launcher_layer=LauncherLayer( - config, profiles, relevant, db, declared_destinations(config) - ) if args.platform else None, + platform_scope.config, profiles, platform_scope.relevant, db, + declared_destinations(platform_scope.config), + ) if platform_scope else None, ) - # Counted apart from the profile gaps: a name only a launcher reads is - # reported, not yet judged. - launcher_reads = launcher_reads_not_held( - { - name: load_platform_config(name, args.platforms_dir) - for name in (selected or list_registered_platforms(args.platforms_dir)) - }, - db, all_profiles, registry, emulator or "", + launcher_reads, unproven = _launcher_rows( + args, selected, db, all_profiles, registry, emulator, ) - unproven = [ - row for row in launcher_unproven( - { - name: load_platform_config(name, args.platforms_dir) - for name in (selected or list_registered_platforms(args.platforms_dir)) - }, - all_profiles, - ) - if not emulator or any( - emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles)) - for part in row["emulator"].split(", ") - ) - ] - if args.json: print(json.dumps( {**report, LAUNCHER_READS_KEY: launcher_reads, LAUNCHER_UNPROVEN_KEY: unproven}, indent=2, )) + return + if emulator: + scope = emulator + elif args.platform: + scope = f"the emulators {args.platform} runs" else: - if emulator: - scope = emulator - elif args.platform: - scope = f"the emulators {args.platform} runs" - else: - scope = "all emulators" - print_report(report, scope, show_clean=bool(args.emulator)) - print_launcher_reads(launcher_reads) - print_launcher_unproven(unproven) + scope = "all emulators" + print_report(report, scope, show_clean=bool(args.emulator)) + print_launcher_reads(launcher_reads) + print_launcher_unproven(unproven) if __name__ == "__main__": From e27a808f1b877665d28451d90e4340171148a33c Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:54:04 +0100 Subject: [PATCH 4/9] refactor: split truth generation by stage --- scripts/diff_truth.py | 153 +++++++++--------- scripts/truth.py | 353 ++++++++++++++++++++++-------------------- 2 files changed, 269 insertions(+), 237 deletions(-) diff --git a/scripts/diff_truth.py b/scripts/diff_truth.py index 4fbcc9026..f4971f320 100644 --- a/scripts/diff_truth.py +++ b/scripts/diff_truth.py @@ -44,6 +44,50 @@ def _where(entry: dict) -> str: return entry.get("destination") or entry["name"] +_TOTAL_LABELS = ( + ("total_missing", "missing"), + ("total_extra_phantom", "unpaired"), + ("total_extra_unprofiled", "unprofiled"), + ("total_hash_mismatch", "hash"), + ("total_required_mismatch", "required"), +) + +_DIVERGENCE_LABELS = ( + ("missing", "MISSING"), + ("extra_phantom", "UNPAIRED"), + ("extra_unprofiled", "UNPROF"), + ("hash_mismatch", "HASH"), + ("required_mismatch", "REQ"), +) + + +def _terminal_divergence(sys_id: str, div: dict) -> list[str]: + labels = [f"{label}:{len(div[key])}" for key, label in _DIVERGENCE_LABELS if div.get(key)] + lines = [f" {sys_id}: {' '.join(labels)}"] + lines.extend( + f" + {_where(m)} [{', '.join(m.get('cores', []))}]" + for m in div.get("missing", []) + ) + lines.extend( + f" ~ {_where(h)} {h['hash_type']}: " + f"{h['truth_' + h['hash_type']]} != {h['scraped_' + h['hash_type']]}" + for h in div.get("hash_mismatch", []) + ) + lines.extend( + f" - {_where(p)} (no profile entry of this system matches it)" + for p in div.get("extra_phantom", []) + ) + lines.extend( + f" ? {_where(u)} (unprofiled cores)" + for u in div.get("extra_unprofiled", []) + ) + lines.extend( + f" ! {_where(r)} required: {r['truth_required']} != {r['scraped_required']}" + for r in div.get("required_mismatch", []) + ) + return lines + + def _format_terminal(report: dict) -> str: lines: list[str] = [] platform = report.get("platform", "unknown") @@ -57,52 +101,14 @@ def _format_terminal(report: dict) -> str: f"{s['systems_uncovered']} uncovered" ) - totals = [] - if s["total_missing"]: - totals.append(f"{s['total_missing']} missing") - if s["total_extra_phantom"]: - totals.append(f"{s['total_extra_phantom']} unpaired") - if s["total_extra_unprofiled"]: - totals.append(f"{s['total_extra_unprofiled']} unprofiled") - if s["total_hash_mismatch"]: - totals.append(f"{s['total_hash_mismatch']} hash") - if s["total_required_mismatch"]: - totals.append(f"{s['total_required_mismatch']} required") + totals = [f"{s[key]} {label}" for key, label in _TOTAL_LABELS if s[key]] if totals: lines.append(f" divergences: {', '.join(totals)}") else: lines.append(" no divergences") for sys_id, div in sorted(report.get("divergences", {}).items()): - labels: list[str] = [] - if div.get("missing"): - labels.append(f"MISSING:{len(div['missing'])}") - if div.get("extra_phantom"): - labels.append(f"UNPAIRED:{len(div['extra_phantom'])}") - if div.get("extra_unprofiled"): - labels.append(f"UNPROF:{len(div['extra_unprofiled'])}") - if div.get("hash_mismatch"): - labels.append(f"HASH:{len(div['hash_mismatch'])}") - if div.get("required_mismatch"): - labels.append(f"REQ:{len(div['required_mismatch'])}") - lines.append(f" {sys_id}: {' '.join(labels)}") - - for m in div.get("missing", []): - cores = ", ".join(m.get("cores", [])) - lines.append(f" + {_where(m)} [{cores}]") - for h in div.get("hash_mismatch", []): - ht = h["hash_type"] - lines.append( - f" ~ {_where(h)} {ht}: {h[f'truth_{ht}']} != {h[f'scraped_{ht}']}" - ) - for p in div.get("extra_phantom", []): - lines.append(f" - {_where(p)} (no profile entry of this system matches it)") - for u in div.get("extra_unprofiled", []): - lines.append(f" ? {_where(u)} (unprofiled cores)") - for r in div.get("required_mismatch", []): - lines.append( - f" ! {_where(r)} required: {r['truth_required']} != {r['scraped_required']}" - ) + lines.extend(_terminal_divergence(sys_id, div)) uncovered = report.get("uncovered_systems", []) if uncovered: @@ -111,6 +117,39 @@ def _format_terminal(report: dict) -> str: return "\n".join(lines) +def _markdown_divergence(sys_id: str, div: dict) -> list[str]: + lines = [f"## {sys_id}", ""] + for m in div.get("missing", []): + refs = "" + if m.get("source_refs"): + refs = " " + " ".join(f"`{r}`" for r in m["source_refs"]) + lines.append(f"- **Add** `{_where(m)}`{refs}") + lines.extend( + f"- **Fix hash** `{_where(h)}` {h['hash_type']}: " + f"`{h['truth_' + h['hash_type']]}` != `{h['scraped_' + h['hash_type']]}`" + for h in div.get("hash_mismatch", []) + ) + # Evidence, not a request: an entry leaves a platform's file only on + # proof (export_native's removal_candidates). A core can read a + # file its profile does not pair with this declaration. + lines.extend( + f"- **Unpaired** `{_where(p)}`: no profile entry of this system matches it " + "by path, name or hash" + for p in div.get("extra_phantom", []) + ) + lines.extend( + f"- **Unpaired** `{_where(u)}`: some cores of this platform " + "have no profile yet" + for u in div.get("extra_unprofiled", []) + ) + lines.extend( + f"- **Fix required** `{_where(r)}`: truth={r['truth_required']}, scraped={r['scraped_required']}" + for r in div.get("required_mismatch", []) + ) + lines.append("") + return lines + + def _format_markdown(report: dict) -> str: lines: list[str] = [] platform = report.get("platform", "unknown") @@ -134,43 +173,13 @@ def _format_markdown(report: dict) -> str: lines.append("") for sys_id, div in sorted(report.get("divergences", {}).items()): - lines.append(f"## {sys_id}") - lines.append("") - for m in div.get("missing", []): - refs = "" - if m.get("source_refs"): - refs = " " + " ".join(f"`{r}`" for r in m["source_refs"]) - lines.append(f"- **Add** `{_where(m)}`{refs}") - for h in div.get("hash_mismatch", []): - ht = h["hash_type"] - lines.append( - f"- **Fix hash** `{_where(h)}` {ht}: `{h[f'truth_{ht}']}` != `{h[f'scraped_{ht}']}`" - ) - # Evidence, not a request: an entry leaves a platform's file only on - # proof (export_native's removal_candidates). A core can read a - # file its profile does not pair with this declaration. - for p in div.get("extra_phantom", []): - lines.append( - f"- **Unpaired** `{_where(p)}`: no profile entry of this system matches it " - "by path, name or hash" - ) - for u in div.get("extra_unprofiled", []): - lines.append( - f"- **Unpaired** `{_where(u)}`: some cores of this platform " - "have no profile yet" - ) - for r in div.get("required_mismatch", []): - lines.append( - f"- **Fix required** `{_where(r)}`: truth={r['truth_required']}, scraped={r['scraped_required']}" - ) - lines.append("") + lines.extend(_markdown_divergence(sys_id, div)) uncovered = report.get("uncovered_systems", []) if uncovered: lines.append("## Uncovered systems") lines.append("") - for u in uncovered: - lines.append(f"- {u}") + lines.extend(f"- {u}" for u in uncovered) lines.append("") return "\n".join(lines) diff --git a/scripts/truth.py b/scripts/truth.py index b9741bbc9..de1bf8e80 100644 --- a/scripts/truth.py +++ b/scripts/truth.py @@ -9,6 +9,7 @@ from __future__ import annotations import copy import os import sys +from dataclasses import dataclass from pathlib import Path from common import ( @@ -30,9 +31,9 @@ from validation import ( ) - _CONFLICTS_SHOWN: set[tuple[str, ...]] = set() + def _serialize_source_ref(sr: object) -> str: """Convert a source_ref value to a clean string for serialization.""" if isinstance(sr, str): @@ -43,6 +44,19 @@ def _serialize_source_ref(sr: object) -> str: return str(sr) +def _indexed_record(value: object, index: dict, files_db: dict) -> dict | None: + """The database record a hash index points a single hash value to.""" + if not (value and isinstance(value, str)): + return None + ref = index.get(value.lower()) + if not ref: + return None + ref_sha1 = ref if isinstance(ref, str) else (ref[0] if ref else None) + if not ref_sha1: + return None + return files_db.get(ref_sha1) + + def _enrich_hashes(entry: dict, db: dict) -> None: """Fill the hashes a profile omits from the record its own hash names. @@ -67,30 +81,18 @@ def _enrich_hashes(entry: dict, db: dict) -> None: # Anchor 2: MD5 (strong) if record is None: - md5 = entry.get("md5") - if md5 and isinstance(md5, str): - by_md5 = indexes.get("by_md5", {}) - ref = by_md5.get(md5.lower()) - if ref: - ref_sha1 = ref if isinstance(ref, str) else (ref[0] if ref else None) - if ref_sha1: - record = files_db.get(ref_sha1) + record = _indexed_record(entry.get("md5"), indexes.get("by_md5", {}), files_db) # Anchor 3: CRC32 (32-bit, collisions theoretically possible). # Require size match when profile has a size to guard against collisions. if record is None: - crc = entry.get("crc32") - if crc and isinstance(crc, str): - by_crc32 = indexes.get("by_crc32", {}) - ref = by_crc32.get(crc.lower()) - if ref: - ref_sha1 = ref if isinstance(ref, str) else (ref[0] if ref else None) - if ref_sha1: - candidate = files_db.get(ref_sha1) - if candidate is not None: - profile_size = entry.get("size") - if not profile_size or candidate.get("size") == profile_size: - record = candidate + candidate = _indexed_record( + entry.get("crc32"), indexes.get("by_crc32", {}), files_db, + ) + if candidate is not None: + profile_size = entry.get("size") + if not profile_size or candidate.get("size") == profile_size: + record = candidate if record is None: return @@ -653,6 +655,160 @@ def _fold_data_directory_readers( _fold_into(entry, dict(declaration), emu_name) +@dataclass(frozen=True) +class _SystemMap: + """How a profile's systems and entries map onto a platform's systems.""" + + platform_sys_ids: set[str] + # Every platform declaration of a name, in the platform's order. The + # last one used to win, whatever the content. + declared_by_name: dict[str, list[tuple[str, dict]]] + # Normalized ID -> platform system ID. Walked in the platform's order, + # not the set's: two IDs normalizing alike went to whichever the hash + # seed put last. + norm_to_platform: dict[str, str] + db: dict | None + + @classmethod + def of(cls, config: dict, db: dict | None) -> _SystemMap: + declared_by_name: dict[str, list[tuple[str, dict]]] = {} + for psid, sys_data in config.get("systems", {}).items(): + for fe in sys_data.get("files", []): + fname = fe.get("name", "").lower() + if fname: + declared_by_name.setdefault(fname, []).append((psid, fe)) + norm_to_platform: dict[str, str] = {} + for psid in config.get("systems", {}): + norm_to_platform.setdefault(_norm_system_id(psid), psid) + return cls( + set(config.get("systems", {}).keys()), declared_by_name, norm_to_platform, db, + ) + + def map_sys_id(self, profile_sid: str) -> str: + """Map a profile system ID to the platform's system ID.""" + if profile_sid in self.platform_sys_ids: + return profile_sid + return self.norm_to_platform.get(_norm_system_id(profile_sid), profile_sid) + + def attribute(self, fe: dict, own: str | None, on_platform: set[str]) -> list[str]: + """The platform systems an entry belongs to, [] when nothing decides. + + A declaration of the same name settles the system only when it can + be the same file: a shared hash, or no contradicting size. fmsx's + 16 KB DISK.ROM is not quasi88's 2 KB disk.rom, and dosbox's SC-55 + ROM1.BIN is not galaksija's. The same content declared under two + systems is filed under both. + """ + verdicts = [ + (psid, _declaration_verdict(fe, decl, self.db)) + for psid, decl in self.declared_by_name.get(fe.get("name", "").lower(), []) + ] + same = sorted({psid for psid, v in verdicts if v == "same"}) + undecided = sorted({psid for psid, v in verdicts if v == "undecided"}) + if own is not None: + mapped = self.map_sys_id(own) + if any(psid == mapped and v != "other" for psid, v in verdicts): + return [mapped] + if same: + return same + if len(undecided) == 1: + return undecided + return [mapped] + if same: + return same + if len(undecided) == 1: + return undecided + if undecided: + ours = [psid for psid in undecided if psid in on_platform] + return ours if len(ours) == 1 else [] + return [next(iter(on_platform))] if len(on_platform) == 1 else [] + + def targets(self, fe: dict, profile: dict, on_platform: set[str]) -> list[str]: + """The platform systems an entry is filed under.""" + profile_sid = fe.get("system", "") + sys_ids = profile.get("systems", []) + if profile_sid: + own: str | None = profile_sid + elif len(sys_ids) == 1: + own = sys_ids[0] + elif not sys_ids: + # A profile that names no system: a platform declaration of + # the same file files it, and the placeholder takes only a + # name the platform does not declare. mess2015's hiscore.dat + # beside the arcade one put an "unknown" section in System.dat. + own = None + else: + # A multi-system profile's entry without a system is filed by + # the platform's own declaration of the same file, or the one + # profile system the platform has. Otherwise it is not filed: + # the first system was a guess, and CLK's Apple, Mac, ZX and + # Amiga ROMs went to RomM as Amstrad CPC firmware. + own = None + sys_targets = self.attribute(fe, own, on_platform) + if not sys_ids and not profile_sid and not sys_targets \ + and fe.get("name", "").lower() not in self.declared_by_name: + sys_targets = [self.map_sys_id("unknown")] + return sys_targets + + +def _cover( + system_cores: dict[str, dict[str, set[str]]], sys_id: str, kind: str, emu_name: str, +) -> None: + sys_cov = system_cores.setdefault( + sys_id, + { + "profiled": set(), + "unprofiled": set(), + }, + ) + sys_cov[kind].add(emu_name) + + +def _platform_entries( + emu_name: str, profile: dict, standalone_set: set[str], platform_name: str, +) -> list[dict]: + # The pack's rule (validation.deliverable), per build: a file the + # emulator installs is kept and marked, one the launcher never opens + # is left out. + return _archives_not_members([ + { + **fe, + "_opens_by_name": opens_by_name(fe, profile, standalone), + "_brought": None if installed_with_emulator(fe, platform_name) + else f"{emu_name}:{'standalone' if standalone else 'libretro'}", + } + for view, standalone in platform_layouts(emu_name, profile, standalone_set) + for fe in _system_dir_files(view, standalone) + if not unread_on(fe, platform_name) + ]) + + +def _serialize_systems( + systems: dict[str, dict], system_cores: dict[str, dict[str, set[str]]], +) -> None: + # Convert sets to sorted lists for serialization + for sys_id, sys_data in systems.items(): + for fe in sys_data.get("files", []): + fe.pop("_hash_by", None) + fe.pop("_region_void", None) + fe["_cores"] = sorted(fe.get("_cores", set())) + fe["_required_by"] = sorted(fe.get("_required_by", set())) + one_of = fe.pop("_one_of", None) + if one_of: + fe["one_of"] = sorted(one_of) + fe["_named_by"] = sorted(fe.get("_named_by", set())) + fe["_brought_by"] = sorted(fe.get("_brought_by", set())) + if not fe["_brought_by"]: + fe["bundled"] = True + fe["_source_refs"] = sorted(fe.get("_source_refs", set())) + # Add per-system coverage + cov = system_cores.get(sys_id, {}) + sys_data["_coverage"] = { + "cores_profiled": sorted(cov.get("profiled", set())), + "cores_unprofiled": sorted(cov.get("unprofiled", set())), + } + + def generate_platform_truth( platform_name: str, config: dict, @@ -690,62 +846,7 @@ def generate_platform_truth( # 1. File-based: if the scraped platform already has this file, use its system # 2. Exact match: profile system ID == platform system ID # 3. Normalized match: strip manufacturer prefix + separators - platform_sys_ids = set(config.get("systems", {}).keys()) - - # Every platform declaration of a name, in the platform's order. The - # last one used to win, whatever the content. - declared_by_name: dict[str, list[tuple[str, dict]]] = {} - for psid, sys_data in config.get("systems", {}).items(): - for fe in sys_data.get("files", []): - fname = fe.get("name", "").lower() - if fname: - declared_by_name.setdefault(fname, []).append((psid, fe)) - - # Normalized ID -> platform system ID. Walked in the platform's order, - # not the set's: two IDs normalizing alike went to whichever the hash - # seed put last. - norm_to_platform: dict[str, str] = {} - for psid in config.get("systems", {}): - norm_to_platform.setdefault(_norm_system_id(psid), psid) - - def _map_sys_id(profile_sid: str) -> str: - """Map a profile system ID to the platform's system ID.""" - if profile_sid in platform_sys_ids: - return profile_sid - return norm_to_platform.get(_norm_system_id(profile_sid), profile_sid) - - def _attribute(fe: dict, own: str | None, on_platform: set[str]) -> list[str]: - """The platform systems an entry belongs to, [] when nothing decides. - - A declaration of the same name settles the system only when it can - be the same file: a shared hash, or no contradicting size. fmsx's - 16 KB DISK.ROM is not quasi88's 2 KB disk.rom, and dosbox's SC-55 - ROM1.BIN is not galaksija's. The same content declared under two - systems is filed under both. - """ - verdicts = [ - (psid, _declaration_verdict(fe, decl, db)) - for psid, decl in declared_by_name.get(fe.get("name", "").lower(), []) - ] - same = sorted({psid for psid, v in verdicts if v == "same"}) - undecided = sorted({psid for psid, v in verdicts if v == "undecided"}) - if own is not None: - mapped = _map_sys_id(own) - if any(psid == mapped and v != "other" for psid, v in verdicts): - return [mapped] - if same: - return same - if len(undecided) == 1: - return undecided - return [mapped] - if same: - return same - if len(undecided) == 1: - return undecided - if undecided: - ours = [psid for psid in undecided if psid in on_platform] - return ours if len(ours) == 1 else [] - return [next(iter(on_platform))] if len(on_platform) == 1 else [] + mapping = _SystemMap.of(config, db) systems: dict[str, dict] = {} unattributed: dict[str, int] = {} @@ -761,48 +862,11 @@ def generate_platform_truth( continue cores_profiled.add(emu_name) - # The pack's rule (validation.deliverable), per build: a file the - # emulator installs is kept and marked, one the launcher never opens - # is left out. - filtered = _archives_not_members([ - { - **fe, - "_opens_by_name": opens_by_name(fe, profile, standalone), - "_brought": None if installed_with_emulator(fe, platform_name) - else f"{emu_name}:{'standalone' if standalone else 'libretro'}", - } - for view, standalone in platform_layouts(emu_name, profile, standalone_set) - for fe in _system_dir_files(view, standalone) - if not unread_on(fe, platform_name) - ]) - on_platform = { - _map_sys_id(sid) for sid in profile.get("systems", []) - } & platform_sys_ids - for fe in filtered: - profile_sid = fe.get("system", "") - sys_ids = profile.get("systems", []) - if profile_sid: - own: str | None = profile_sid - elif len(sys_ids) == 1: - own = sys_ids[0] - elif not sys_ids: - # A profile that names no system: a platform declaration of - # the same file files it, and the placeholder takes only a - # name the platform does not declare. mess2015's hiscore.dat - # beside the arcade one put an "unknown" section in System.dat. - own = None - else: - # A multi-system profile's entry without a system is filed by - # the platform's own declaration of the same file, or the one - # profile system the platform has. Otherwise it is not filed: - # the first system was a guess, and CLK's Apple, Mac, ZX and - # Amiga ROMs went to RomM as Amstrad CPC firmware. - own = None - sys_targets = _attribute(fe, own, on_platform) - if not sys_ids and not profile_sid and not sys_targets \ - and fe.get("name", "").lower() not in declared_by_name: - sys_targets = [_map_sys_id("unknown")] + mapping.map_sys_id(sid) for sid in profile.get("systems", []) + } & mapping.platform_sys_ids + for fe in _platform_entries(emu_name, profile, standalone_set, platform_name): + sys_targets = mapping.targets(fe, profile, on_platform) if not sys_targets: unattributed[emu_name] = unattributed.get(emu_name, 0) + 1 continue @@ -811,14 +875,7 @@ def generate_platform_truth( _merge_file_into_system( system, fe if position == 0 else copy.deepcopy(fe), emu_name, db ) - sys_cov = system_cores.setdefault( - sys_id, - { - "profiled": set(), - "unprofiled": set(), - }, - ) - sys_cov["profiled"].add(emu_name) + _cover(system_cores, sys_id, "profiled", emu_name) # Ensure all systems of resolved cores have entries (even with 0 files). # This documents that the system is covered: the core was analyzed and @@ -827,28 +884,14 @@ def generate_platform_truth( for emu_name in sorted(cores_profiled): profile = profiles[emu_name] for prof_sid in profile.get("systems", []): - sys_id = _map_sys_id(prof_sid) + sys_id = mapping.map_sys_id(prof_sid) systems.setdefault(sys_id, {}) - sys_cov = system_cores.setdefault( - sys_id, - { - "profiled": set(), - "unprofiled": set(), - }, - ) - sys_cov["profiled"].add(emu_name) + _cover(system_cores, sys_id, "profiled", emu_name) # Track unprofiled cores per system based on profile system lists for emu_name in cores_unprofiled: for sys_id in systems: - sys_cov = system_cores.setdefault( - sys_id, - { - "profiled": set(), - "unprofiled": set(), - }, - ) - sys_cov["unprofiled"].add(emu_name) + _cover(system_cores, sys_id, "unprofiled", emu_name) _fold_data_directory_readers( systems, profiles, sorted(cores_profiled), standalone_set, platform_name, @@ -868,27 +911,7 @@ def generate_platform_truth( if files_list: sys_data["files"] = [fe for fe in files_list if _has_exploitable_data(fe)] - # Convert sets to sorted lists for serialization - for sys_id, sys_data in systems.items(): - for fe in sys_data.get("files", []): - fe.pop("_hash_by", None) - fe.pop("_region_void", None) - fe["_cores"] = sorted(fe.get("_cores", set())) - fe["_required_by"] = sorted(fe.get("_required_by", set())) - one_of = fe.pop("_one_of", None) - if one_of: - fe["one_of"] = sorted(one_of) - fe["_named_by"] = sorted(fe.get("_named_by", set())) - fe["_brought_by"] = sorted(fe.get("_brought_by", set())) - if not fe["_brought_by"]: - fe["bundled"] = True - fe["_source_refs"] = sorted(fe.get("_source_refs", set())) - # Add per-system coverage - cov = system_cores.get(sys_id, {}) - sys_data["_coverage"] = { - "cores_profiled": sorted(cov.get("profiled", set())), - "cores_unprofiled": sorted(cov.get("unprofiled", set())), - } + _serialize_systems(systems, system_cores) return { "platform": platform_name, @@ -1007,7 +1030,7 @@ def _diff_system(truth_sys: dict, scraped_sys: dict) -> dict: # An archive declared once per ROM it holds (zipped_file) is still one # file. seen_extra: set[tuple[str, str]] = set() - for s_key, s_entry in unmatched_scraped.items(): + for s_entry in unmatched_scraped.values(): key = (s_entry["name"].lower(), _path_tail(s_entry.get("destination"))) if key in seen_extra: continue From fd60b10de67aca2da5c29c0e9dce9908e5d5a0ff Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:54:04 +0100 Subject: [PATCH 5/9] refactor: split export_native and the exporters --- scripts/export_native.py | 292 +++++++++++++---------- scripts/exporter/base_exporter.py | 11 +- scripts/exporter/baseline.py | 304 +++++++++++++----------- scripts/exporter/batocera_exporter.py | 84 ++++--- scripts/exporter/bizhawk_exporter.py | 2 +- scripts/exporter/candidates.py | 12 +- scripts/exporter/emudeck_exporter.py | 6 +- scripts/exporter/misterfpga_exporter.py | 9 +- scripts/exporter/recalbox_exporter.py | 154 +++++++----- scripts/exporter/retrobat_exporter.py | 29 ++- scripts/exporter/retrodeck_exporter.py | 76 +++--- scripts/exporter/retropie_exporter.py | 184 +++++++------- scripts/exporter/romm_exporter.py | 2 +- scripts/exporter/systemdat_exporter.py | 34 +-- 14 files changed, 685 insertions(+), 514 deletions(-) diff --git a/scripts/export_native.py b/scripts/export_native.py index 8b9266bc8..61e9c236c 100644 --- a/scripts/export_native.py +++ b/scripts/export_native.py @@ -50,7 +50,15 @@ from common import ( yaml_load, ) from exporter import discover_exporters -from exporter.baseline import HASH_FIELDS, _hash_values, _single_size, build_native_model +from exporter.base_exporter import BaseExporter +from exporter.baseline import ( + HASH_FIELDS, + NativeFile, + Report, + _hash_values, + _single_size, + build_native_model, +) from exporter.candidates import removal_candidates from exporter.doubled import doubled_destinations from truth import generate_platform_truth @@ -252,14 +260,15 @@ def _raw_url(url: str) -> str: def wanted_sources( - exporter: object, systems: dict, scraped: dict | None = None + exporter: BaseExporter, systems: dict, scraped: dict | None = None ) -> dict[str, str]: """Cache-relative name -> URL of every file the exporter patches.""" wanted = dict(exporter.native_sources()) components = getattr(exporter, "components", None) - if callable(components): + component_url = getattr(exporter, "component_url", None) + if callable(components) and callable(component_url): for component in components(systems): - wanted[f"{component}/component_manifest.json"] = exporter.component_url( + wanted[f"{component}/component_manifest.json"] = component_url( component ) @@ -343,7 +352,7 @@ def _at_revision(url: str, base: str) -> str: def collect_originals( - exporter: object, + exporter: BaseExporter, systems: dict, upstream_dir: Path, allow_fetch: bool, @@ -364,8 +373,12 @@ def collect_originals( unpack = getattr(exporter, "unpack", None) for relative, url in wanted.items(): path = root / relative - archive = callable(unpack) and relative.endswith((".zip", ".tar.gz")) - check = (lambda raw: _read_archive(unpack, raw)) if archive else _read_text + reader: Callable[[bytes], dict[str, str]] | None = ( + unpack if callable(unpack) and relative.endswith((".zip", ".tar.gz")) else None + ) + check: Callable[[bytes], object] = ( + functools.partial(_read_archive, reader) if reader is not None else _read_text + ) try: if allow_fetch: payload = fetch(url, path, index, refresh, check) @@ -376,8 +389,8 @@ def collect_originals( f"{relative}: not in {root}; rerun with --fetch to download it" ) continue - if archive: - originals.update(_read_archive(unpack, payload)) + if reader is not None: + originals.update(_read_archive(reader, payload)) keep = getattr(exporter, "keep_archive", None) if callable(keep): keep(relative, payload) @@ -459,7 +472,7 @@ def refresh_cache( except StaleTruth as exc: return False, [str(exc)] systems, _ = build_native_model(truth or {}, scraped) - exporter = exporter_class() + exporter: BaseExporter = exporter_class() wanted = wanted_sources(exporter, systems, scraped) off_pin = unpinned(wanted, scraped) if off_pin: @@ -548,7 +561,7 @@ class LandedChanges: def _change( - kind: str, entry: object, field_name: str | None, old: object, new: object + kind: str, entry: NativeFile, field_name: str | None, old: object, new: object ) -> dict: return { "kind": kind, @@ -561,21 +574,21 @@ def _change( } -def _platform_value(entry: object, field_name: str) -> str | list[str]: +def _platform_value(entry: NativeFile, field_name: str) -> str | list[str]: values = _hash_values(entry.platform or {}, field_name) if (entry.platform or {}).get(f"{field_name}_list"): return values return ",".join(values) -def _written_value(exporter: object, entry: object, field_name: str) -> str | list[str]: +def _written_value(exporter: BaseExporter, entry: NativeFile, field_name: str) -> str | list[str]: """A hash field as the render writes it: a list where the checker reads one, so the report never shows several values as one.""" listed = exporter.written_list(entry, field_name) return listed if listed is not None else exporter.written(entry, field_name) -def _added_fields(exporter: object, entry: object) -> dict: +def _added_fields(exporter: BaseExporter, entry: NativeFile) -> dict: """The fields an addition is written with, as the render chooses them.""" carried = exporter.carries() written: dict[str, object] = { @@ -590,7 +603,7 @@ def _added_fields(exporter: object, entry: object) -> dict: return written -def landed_changes(exporter: object, systems: dict) -> LandedChanges: +def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges: """The changes the written file carries, with their values. Only what the format states: a correction to a field the file has no @@ -706,8 +719,6 @@ def export_platform( allow_fetch: bool, ) -> tuple[bool, list[str]]: """Write one platform's corrected file. Returns (ok, messages).""" - messages: list[str] = [] - try: truth, scraped = load_inputs(platform, truth_dir, platforms_dir) except StaleTruth as exc: @@ -724,34 +735,12 @@ def export_platform( if not systems: return False, ["nothing to write: neither the platform nor the truth has data"] - exporter = exporter_class() - off_pin = unpinned(wanted_sources(exporter, systems, scraped), scraped) - if off_pin: - return False, off_pin - originals, missing = collect_originals( - exporter, systems, upstream_dir, allow_fetch, scraped + exporter: BaseExporter = exporter_class() + produced, issues, stopped = _produce( + exporter, systems, report, scraped, upstream_dir, allow_fetch, ) - if missing: - return False, [f"the platform's own file is required: {m}" for m in missing] - if exporter.needs_original() and not originals: - return False, ["the platform's own file is required and none was read"] - - try: - produced = exporter.render(systems, report, originals, scraped) - except ValueError as exc: - return False, [str(exc)] - - if not produced and not exporter.may_write_nothing(): - return False, ["the exporter produced no file"] - - issues = exporter.validate(systems, produced) - if issues: - # Written first, a file its own validator refused replaced the - # published export and only the exit code said so. - invalid = [f"INVALID: {issue}" for issue in issues[:10]] - if len(issues) > 10: - invalid.append(f"and {len(issues) - 10} more validation failures") - return False, invalid + if stopped: + return False, stopped platform_dir = output_dir / platform _remove_stale(platform_dir, set(produced)) @@ -762,61 +751,15 @@ def export_platform( resized, cleared = changes.resized, changes.cleared unsized = changes.unsized requirements = changes.requirements - lists = changes.lists - landed = 0 - refused = 0 - lost = 0 - for system in systems.values(): - for entry in system.files: - if not entry.name: - continue - if exporter.lands(entry): - landed += entry.platform is None - elif entry.platform is None: - refused += 1 - else: - # The platform declares it and the format still cannot state - # it, so their own file loses a line. Worth saying out loud. - lost += 1 + landed, refused, lost = _entry_outcomes(exporter, systems) own_summary = exporter.outcome(systems, produced) summary = own_summary if summary is None: - # What the written file carries, in the terms the exports page uses. - # What it does not carry is counted on a line of its own below. - parts = [f"{report.files_kept} kept"] - landed_counts = ( - (landed, "file", "", "added"), - (len(applied), "hash", "", "updated to the emulator source"), - (requirements, "required flag", "", "aligned with the code"), - (len(filled), "hash", "", "added to an existing entry"), - (len(resized), "size", "", "updated to the emulator source"), - (len(unsized), "size", "", "removed"), - (len(cleared), "hash", "", "removed"), - (lost, "entry", "entries", "removed, the format cannot state them"), - (lists, "md5 list", "", "written, any listed value passes"), - ) - parts += [ - f"{_count(number, noun, plural)} {verb}" - for number, noun, plural, verb in landed_counts - if number - ] - summary = ", ".join(parts) + summary = _landed_summary(report, changes, landed, lost) withheld = exporter.withheld() - unwritten = [ - f"{_count(number, noun, plural)} {what}" - for number, noun, plural, what in ( - (refused, "file", "", "the format or its checker cannot carry"), - (len(withheld), "update", "", "withheld"), - # A content-scanning core's names are labels: a list checked - # by path cannot hold them. - (report.labels, "entry", "entries", "found by content"), - (len(report.unattributed), "file", "", - "no single native system of the platform takes"), - ) - if number - ] + unwritten = _unwritten(refused, withheld, report) # Reported, never removed: the platform's file keeps every entry. candidates = removal_candidates( systems, scraped, load_emulator_profiles("emulators"), @@ -824,32 +767,7 @@ def export_platform( ) # Reported, never rewritten: both declarations stay as the platform wrote them. doubled = doubled_in(scraped, platforms_dir) - messages.append(summary) - if unwritten: - messages.append("not in the file: " + ", ".join(unwritten)) - if candidates: - open_question = sum(c["verdict"] == "undetermined" for c in candidates) - messages.append( - f"{_count(len(candidates), 'entry', 'entries')} no examined core is known to open" - + (f" ({open_question} undetermined)" if open_question else "") - + ", listed in the report" - ) - if doubled: - messages.append( - f"{_count(len(doubled), 'destination')} declared twice for two files" - ", listed in the report" - ) - messages.extend(f"withheld: {reason}" for reason in withheld) - for heading, labels in ( - ("hash updated", applied), - ("hash added", filled), - ("size updated", resized), - ("size removed", unsized), - ("hash removed", cleared), - ): - messages.extend(f"{heading}: {label}" for label in labels[:5]) - if len(labels) > 5: - messages.append(f"and {len(labels) - 5} more") + messages = _export_messages(summary, unwritten, candidates, doubled, withheld, changes) write_report(output_dir / f"{platform}.json", { "platform": platform, @@ -879,6 +797,142 @@ def export_platform( return True, messages +def _produce( + exporter: BaseExporter, + systems: dict, + report: Report, + scraped: dict | None, + upstream_dir: Path, + allow_fetch: bool, +) -> tuple[dict, list[str], list[str]]: + """The files the exporter renders, its validator's issues, and why the + export stops before writing (empty when it goes on).""" + off_pin = unpinned(wanted_sources(exporter, systems, scraped), scraped) + if off_pin: + return {}, [], off_pin + originals, missing = collect_originals( + exporter, systems, upstream_dir, allow_fetch, scraped + ) + if missing: + return {}, [], [f"the platform's own file is required: {m}" for m in missing] + if exporter.needs_original() and not originals: + return {}, [], ["the platform's own file is required and none was read"] + + try: + produced = exporter.render(systems, report, originals, scraped) + except ValueError as exc: + return {}, [], [str(exc)] + + if not produced and not exporter.may_write_nothing(): + return {}, [], ["the exporter produced no file"] + + issues = exporter.validate(systems, produced) + if issues: + # Written first, a file its own validator refused replaced the + # published export and only the exit code said so. + invalid = [f"INVALID: {issue}" for issue in issues[:10]] + if len(issues) > 10: + invalid.append(f"and {len(issues) - 10} more validation failures") + return {}, issues, invalid + return produced, issues, [] + + +def _entry_outcomes(exporter: BaseExporter, systems: dict) -> tuple[int, int, int]: + """Additions written, additions refused, and platform entries lost.""" + landed = 0 + refused = 0 + lost = 0 + for system in systems.values(): + for entry in system.files: + if not entry.name: + continue + if exporter.lands(entry): + landed += entry.platform is None + elif entry.platform is None: + refused += 1 + else: + # The platform declares it and the format still cannot state + # it, so their own file loses a line. Worth saying out loud. + lost += 1 + return landed, refused, lost + + +def _landed_summary(report: Report, changes: LandedChanges, landed: int, lost: int) -> str: + # What the written file carries, in the terms the exports page uses. + # What it does not carry is counted on a line of its own below. + parts = [f"{report.files_kept} kept"] + landed_counts = ( + (landed, "file", "", "added"), + (len(changes.applied), "hash", "", "updated to the emulator source"), + (changes.requirements, "required flag", "", "aligned with the code"), + (len(changes.filled), "hash", "", "added to an existing entry"), + (len(changes.resized), "size", "", "updated to the emulator source"), + (len(changes.unsized), "size", "", "removed"), + (len(changes.cleared), "hash", "", "removed"), + (lost, "entry", "entries", "removed, the format cannot state them"), + (changes.lists, "md5 list", "", "written, any listed value passes"), + ) + parts += [ + f"{_count(number, noun, plural)} {verb}" + for number, noun, plural, verb in landed_counts + if number + ] + return ", ".join(parts) + + +def _unwritten(refused: int, withheld: list[str], report: Report) -> list[str]: + return [ + f"{_count(number, noun, plural)} {what}" + for number, noun, plural, what in ( + (refused, "file", "", "the format or its checker cannot carry"), + (len(withheld), "update", "", "withheld"), + # A content-scanning core's names are labels: a list checked + # by path cannot hold them. + (report.labels, "entry", "entries", "found by content"), + (len(report.unattributed), "file", "", + "no single native system of the platform takes"), + ) + if number + ] + + +def _export_messages( + summary: str, + unwritten: list[str], + candidates: list[dict], + doubled: list[dict], + withheld: list[str], + changes: LandedChanges, +) -> list[str]: + messages = [summary] + if unwritten: + messages.append("not in the file: " + ", ".join(unwritten)) + if candidates: + open_question = sum(c["verdict"] == "undetermined" for c in candidates) + messages.append( + f"{_count(len(candidates), 'entry', 'entries')} no examined core is known to open" + + (f" ({open_question} undetermined)" if open_question else "") + + ", listed in the report" + ) + if doubled: + messages.append( + f"{_count(len(doubled), 'destination')} declared twice for two files" + ", listed in the report" + ) + messages.extend(f"withheld: {reason}" for reason in withheld) + for heading, labels in ( + ("hash updated", changes.applied), + ("hash added", changes.filled), + ("size updated", changes.resized), + ("size removed", changes.unsized), + ("hash removed", changes.cleared), + ): + messages.extend(f"{heading}: {label}" for label in labels[:5]) + if len(labels) > 5: + messages.append(f"and {len(labels) - 5} more") + return messages + + def _write_produced( root: Path, produced: dict[str, str | bytes], modes: dict[str, int] ) -> None: diff --git a/scripts/exporter/base_exporter.py b/scripts/exporter/base_exporter.py index e2e3534af..c3bc14244 100644 --- a/scripts/exporter/base_exporter.py +++ b/scripts/exporter/base_exporter.py @@ -9,11 +9,16 @@ the data block hands the maintainer something that no longer runs. from __future__ import annotations from abc import ABC, abstractmethod +from typing import Generic, TypeVar, Union from .baseline import NativeFile, NativeSystem, Report +# What a produced file holds: text for every format, bytes besides for one +# that also hands back an archive (MiSTer's bios_db.json.zip). +Content = TypeVar("Content", bound=Union[str, bytes]) -class BaseExporter(ABC): + +class BaseExporter(ABC, Generic[Content]): """Base class for writing a platform's own BIOS file, corrected.""" # A hash field the checker compares to one value: an addition the @@ -77,14 +82,14 @@ class BaseExporter(ABC): report: Report, originals: dict[str, str], scraped: dict | None = None, - ) -> dict[str, str]: + ) -> dict[str, Content]: """Return {relative output path: file content}.""" @abstractmethod def validate( self, systems: dict[str, NativeSystem], - produced: dict[str, str], + produced: dict[str, Content], ) -> list[str]: """Check the produced files against what was asked of them.""" diff --git a/scripts/exporter/baseline.py b/scripts/exporter/baseline.py index 66f5a3b82..19f12096c 100644 --- a/scripts/exporter/baseline.py +++ b/scripts/exporter/baseline.py @@ -121,7 +121,7 @@ def _field_sets(entry: dict | None) -> dict[str, set[str]]: return {f: set(_hash_values(entry or {}, f)) for f in HASH_FIELDS} -def _single_size(value: object) -> int | None: +def _single_size(value: int | str | list[int | str]) -> int | None: """One size, or None: a list names several accepted revisions, which a single size field cannot state (int() on it stopped the whole export).""" if isinstance(value, list): @@ -499,22 +499,9 @@ def platform_declares(truth_entry: dict, candidates: list[dict]) -> bool: ) -def build_native_model( - truth: dict, - scraped: dict | None, -) -> tuple[dict[str, NativeSystem], Report]: - """Rebuild the platform's systems, corrected by the truth. - - Returns the systems keyed by native id, in the platform's own order - first and truth-only additions after, plus what changed. - """ - report = Report() +def _platform_systems(scraped_systems: dict, report: Report) -> dict[str, NativeSystem]: + """Pass 1: the platform's own file, grouped as the platform groups it.""" systems: dict[str, NativeSystem] = {} - - scraped_systems = (scraped or {}).get("systems", {}) - composite_zips = (scraped or {}).get("zip_digest") == "composite" - - # Pass 1: the platform's own file, grouped as the platform groups it. for sys_key, sys_data in scraped_systems.items(): for file_entry in sys_data.get("files", []): native_id = _native_id_of(sys_key, sys_data, file_entry) @@ -540,31 +527,83 @@ def build_native_model( ) ) report.files_kept += 1 + return systems + +def _correct_matched(matched: NativeFile, truth_entry: dict, report: Report) -> None: + """Record what the truth corrects or fills on the platform's own entry.""" + matched.truth = truth_entry + checked = checked_hashes(truth_entry) or {} + contradicted = contradicted_hashes(truth_entry, matched.platform) + for field_name in HASH_FIELDS: + if field_name == "md5" and matched.composite_md5: + continue + if field_name in contradicted: + matched.corrections.append(field_name) + report.hashes_corrected.append( + f"{matched.native_system}/{matched.name} {field_name}" + ) + elif _hash_values(checked, field_name) and not _hash_values( + comparable(matched.platform), field_name + ): + matched.filled.append(field_name) + t_req = truth_entry.get("required") + p_req = (matched.platform or {}).get("required") + # A file a core takes as one of a set has no requirement of + # its own: a platform line cannot say "one of these", so + # truth leaves its value as written rather than claim + # every member optional or every member needed. + if ( + t_req is not None + and p_req is not None + and bool(t_req) != bool(p_req) + and not (truth_entry.get("one_of_required") and not t_req) + ): + matched.corrections.append("required") + report.required_corrected.append( + f"{matched.native_system}/{matched.name}" + ) + + +@dataclass +class _TruthPass: + """Pass 2: the truth applied onto the platform's grouping.""" + + systems: dict[str, NativeSystem] + report: Report + scraped_systems: dict + composite_zips: bool # Which native ids a truth system may contribute to. - norm_to_scraped: dict[str, str] = { - _norm_system_id(key): key for key in scraped_systems - } + norm_to_scraped: dict[str, str] = field(init=False) # Every system the platform names, files or none: an addition elsewhere # is filed under our own slug. - platform_ids = { - native_id - for key, sys_data in scraped_systems.items() - for native_id in ( - sys_data.get("native_id") or key, - *(_native_id_of(key, sys_data, fe) for fe in sys_data.get("files", [])), - ) - } - native_by_norm: dict[str, str] = {} - for system in systems.values(): - native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id) + platform_ids: set[str] = field(init=False) + native_by_norm: dict[str, str] = field(init=False) - def _target_native_ids(truth_sid: str) -> tuple[list[str], bool]: + def __post_init__(self) -> None: + scraped_systems = self.scraped_systems + self.norm_to_scraped = { + _norm_system_id(key): key for key in scraped_systems + } + self.platform_ids = { + native_id + for key, sys_data in scraped_systems.items() + for native_id in ( + sys_data.get("native_id") or key, + *(_native_id_of(key, sys_data, fe) for fe in sys_data.get("files", [])), + ) + } + self.native_by_norm = {} + for system in self.systems.values(): + self.native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id) + + def target_native_ids(self, truth_sid: str) -> tuple[list[str], bool]: """The native ids a truth system spans, and whether the first one is where an addition belongs without asking which core reads it.""" + scraped_systems = self.scraped_systems scraped_key = truth_sid if truth_sid in scraped_systems else None if scraped_key is None: - scraped_key = norm_to_scraped.get(_norm_system_id(truth_sid)) + scraped_key = self.norm_to_scraped.get(_norm_system_id(truth_sid)) if scraped_key is not None: sys_data = scraped_systems[scraped_key] ids = { @@ -583,28 +622,28 @@ def build_native_model( ordered.remove(primary) ordered.insert(0, primary) return ordered, primary in ids or len(ordered) == 1 - direct = native_by_norm.get(_norm_system_id(truth_sid)) + direct = self.native_by_norm.get(_norm_system_id(truth_sid)) return ([direct] if direct else [truth_sid]), True - # Pass 2: apply the truth onto that grouping. - for truth_sid in sorted(truth.get("systems", {})): - truth_sys = truth["systems"][truth_sid] + def _files_of(self, target_ids: list[str]) -> list[NativeFile]: + return [ + candidate + for native_id in target_ids + for candidate in self.systems.get(native_id, NativeSystem(native_id)).files + ] + + def apply(self, truth_sid: str, truth_sys: dict) -> None: truth_files = truth_sys.get("files", []) if not truth_files: - continue + return - target_ids, settled_id = _target_native_ids(truth_sid) + target_ids, settled_id = self.target_native_ids(truth_sid) truth_files = [ entry for entry in truth_files if (name := str(entry.get("name", ""))) and not name.startswith("_") and not _is_placeholder(name) ] - candidates = [ - candidate - for native_id in target_ids - for candidate in systems.get(native_id, NativeSystem(native_id)).files - if candidate.truth is None - ] + candidates = [c for c in self._files_of(target_ids) if c.truth is None] pairs = pair_entries(truth_files, [c.platform or {} for c in candidates]) # The cores that read what the platform files under each native id, # from the truth entries its declarations pair with. @@ -613,109 +652,102 @@ def build_native_model( readers.setdefault(candidates[index].native_system, set()).update( truth_files[t_index].get("_cores") or () ) - for candidate in ( - c - for native_id in target_ids - for c in systems.get(native_id, NativeSystem(native_id)).files - if c.platform is not None - ): + for candidate in (c for c in self._files_of(target_ids) if c.platform is not None): own = str(candidate.name).casefold() candidate.namesakes.extend( entry for entry in truth_files if own in _names(entry) ) for t_index, truth_entry in enumerate(truth_files): - name = str(truth_entry["name"]) - index = pairs.get(t_index) - matched = candidates[index] if index is not None else None - - if matched is not None: - matched.truth = truth_entry - checked = checked_hashes(truth_entry) or {} - contradicted = contradicted_hashes(truth_entry, matched.platform) - for field_name in HASH_FIELDS: - if field_name == "md5" and matched.composite_md5: - continue - if field_name in contradicted: - matched.corrections.append(field_name) - report.hashes_corrected.append( - f"{matched.native_system}/{matched.name} {field_name}" - ) - elif _hash_values(checked, field_name) and not _hash_values( - comparable(matched.platform), field_name - ): - matched.filled.append(field_name) - t_req = truth_entry.get("required") - p_req = (matched.platform or {}).get("required") - # A file a core takes as one of a set has no requirement of - # its own: a platform line cannot say "one of these", so - # truth leaves its value as written rather than claim - # every member optional or every member needed. - if ( - t_req is not None - and p_req is not None - and bool(t_req) != bool(p_req) - and not (truth_entry.get("one_of_required") and not t_req) - ): - matched.corrections.append("required") - report.required_corrected.append( - f"{matched.native_system}/{matched.name}" - ) + paired = pairs.get(t_index) + if paired is not None: + _correct_matched(candidates[paired], truth_entry, self.report) continue + self._add(truth_sid, truth_entry, target_ids, settled_id, readers) - if is_label(truth_entry): - report.labels += 1 - continue - # The emulator installs it: no user is asked to bring it. - if truth_entry.get("bundled"): - continue + def _add( + self, + truth_sid: str, + truth_entry: dict, + target_ids: list[str], + settled_id: bool, + readers: dict[str, set[str]], + ) -> None: + """File a truth entry the platform does not declare, when it can be.""" + name = str(truth_entry["name"]) + if is_label(truth_entry): + self.report.labels += 1 + return + # The emulator installs it: no user is asked to bring it. + if truth_entry.get("bundled"): + return - # A file another core's entry already claimed is still the - # platform's file, not a new one: scph101.bin, declared by two - # PSX cores, was written into RetroDECK's manifest a second time. - declared = [ - candidate.platform - for native_id in target_ids - for candidate in systems.get(native_id, NativeSystem(native_id)).files - if candidate.platform is not None - ] - if platform_declares(truth_entry, declared): - continue + # A file another core's entry already claimed is still the + # platform's file, not a new one: scph101.bin, declared by two + # PSX cores, was written into RetroDECK's manifest a second time. + declared = [ + candidate.platform + for candidate in self._files_of(target_ids) + if candidate.platform is not None + ] + if platform_declares(truth_entry, declared): + return - # The truth knows a file the platform does not declare. Across - # several native ids and no primary, it joins the one whose files - # its cores read: RetroDECK's arcade spans mame and fbneo, and - # MAME device archives were filed as FBNeo BIOS because fbneo - # sorts first. With no single answer it is not written. - native_id = target_ids[0] - if not settled_id: - wanted = set(truth_entry.get("_cores") or ()) - shared = {nid: len(readers.get(nid, set()) & wanted) for nid in target_ids} - best = max(shared.values()) - winners = [nid for nid, count in shared.items() if count == best] - if not best or len(winners) > 1: - report.unattributed.append(f"{truth_sid}/{name}") - continue - native_id = winners[0] - system = systems.get(native_id) - if system is None: - system = NativeSystem(native_id=native_id, from_platform=False) - systems[native_id] = system - report.systems_added += 1 - destination = str( - truth_entry.get("path") or truth_entry.get("destination") or name + # The truth knows a file the platform does not declare. Across + # several native ids and no primary, it joins the one whose files + # its cores read: RetroDECK's arcade spans mame and fbneo, and + # MAME device archives were filed as FBNeo BIOS because fbneo + # sorts first. With no single answer it is not written. + native_id = target_ids[0] + if not settled_id: + wanted = set(truth_entry.get("_cores") or ()) + shared = {nid: len(readers.get(nid, set()) & wanted) for nid in target_ids} + best = max(shared.values()) + winners = [nid for nid, count in shared.items() if count == best] + if not best or len(winners) > 1: + self.report.unattributed.append(f"{truth_sid}/{name}") + return + native_id = winners[0] + system = self.systems.get(native_id) + if system is None: + system = NativeSystem(native_id=native_id, from_platform=False) + self.systems[native_id] = system + self.report.systems_added += 1 + destination = str( + truth_entry.get("path") or truth_entry.get("destination") or name + ) + system.files.append( + NativeFile( + name=name, + destination=destination, + native_system=native_id, + truth=truth_entry, + foreign_system=native_id not in self.platform_ids, + composite_md5=self.composite_zips and name.lower().endswith(".zip"), ) - system.files.append( - NativeFile( - name=name, - destination=destination, - native_system=native_id, - truth=truth_entry, - foreign_system=native_id not in platform_ids, - composite_md5=composite_zips and name.lower().endswith(".zip"), - ) - ) - report.files_added += 1 + ) + self.report.files_added += 1 + + +def build_native_model( + truth: dict, + scraped: dict | None, +) -> tuple[dict[str, NativeSystem], Report]: + """Rebuild the platform's systems, corrected by the truth. + + Returns the systems keyed by native id, in the platform's own order + first and truth-only additions after, plus what changed. + """ + report = Report() + scraped_systems = (scraped or {}).get("systems", {}) + systems = _platform_systems(scraped_systems, report) + + truth_pass = _TruthPass( + systems, report, scraped_systems, + (scraped or {}).get("zip_digest") == "composite", + ) + for truth_sid in sorted(truth.get("systems", {})): + truth_pass.apply(truth_sid, truth["systems"][truth_sid]) # A reader takes the files in the order the list gives, so the one the # code looks for first is named first. Only what we add is ordered: what diff --git a/scripts/exporter/batocera_exporter.py b/scripts/exporter/batocera_exporter.py index 58bebd922..9122d1b31 100644 --- a/scripts/exporter/batocera_exporter.py +++ b/scripts/exporter/batocera_exporter.py @@ -134,6 +134,35 @@ def md5_list_support(script: str) -> frozenset[str]: return frozenset(support) +def _md5_patched(item: str, md5: str | list[str]) -> str: + """An item's text with only its md5 value replaced.""" + return _MD5_VALUE.sub( + lambda m: m.group(1) + _md5_literal( + md5, spaced=not m.group(2).startswith("[\"") + ), + item, + count=1, + ) + + +def _appended_items( + added: list[str], last: re.Match[str], joined: str, original: list[str], +) -> str: + """The text that follows an entry's last item with the items it gains, + in the form that item is written.""" + # Their spacing before the closing brace: '"x"}' or '"x" }'. + tight = not last.group(0).endswith(" }") + added = [a[:-2] + "}" if tight and a.endswith(" }") else a for a in added] + if len(original) == 1: + return ", " + ", ".join(added) + line_start = joined.rfind("\n", 0, last.start()) + 1 + indent = joined[line_start:last.start()] + return "," + "".join( + f"\n{indent}{a}" + ("," if i < len(added) - 1 else "") + for i, a in enumerate(added) + ) + + def _md5_literal(value: str | list[str], spaced: bool = True) -> str: """An md5 as the script writes it: a quoted string, or a list of them with Batocera's spacing inside the brackets (`[ "a", "b" ]`).""" @@ -152,7 +181,7 @@ def _note_key(text: str) -> tuple[str, str]: return (path.group(1) if path else "", member.group(1) if member else "") -class Exporter(BaseExporter): +class Exporter(BaseExporter[str]): """Write Batocera's batocera-systems, corrected.""" # checkBios compares one md5 for a plain file. altmd5 is read only for @@ -180,7 +209,7 @@ class Exporter(BaseExporter): super().__init__() # The emulator and core each system entry of the original is gated # on, read by render. - self._gates: dict[str, tuple[str, str] | None] = {} + self._gates: dict[str, tuple[str, str | None] | None] = {} # The items the pinned checker reads an md5 list for, read by # render from the platform's own file. self._md5_lists: frozenset[str] = frozenset() @@ -338,11 +367,11 @@ class Exporter(BaseExporter): for item in (before or {}).get("biosFiles", []) if isinstance(item, dict) } - parts: list[str] = [] - for fe in files: - for runner in self._item_runners(fe): - parts.append(self._bios_item(fe, runner, originals)) - return parts + return [ + self._bios_item(fe, runner, originals) + for fe in files + for runner in self._item_runners(fe) + ] def _item_runners(self, fe: NativeFile) -> list[list[str] | None]: """One item per runner an addition names. None keeps the original's.""" @@ -431,7 +460,6 @@ class Exporter(BaseExporter): trailing[key] = line[hash_at:].rstrip() return trailing, leading - def _entry_block( self, system: NativeSystem, @@ -443,7 +471,9 @@ class Exporter(BaseExporter): before = self._parse_entry(original) own = self._own_entry(system, before) items = self._bios_items(files, own) - indent = _ENTRY_START.match(original[0]).group(1) + start = _ENTRY_START.match(original[0]) + assert start is not None, original[0] + indent = start.group(1) one_line = len(original) == 1 and not trailing and not leading if one_line: return [self._entry_line(system, files, before, indent)] @@ -483,7 +513,7 @@ class Exporter(BaseExporter): before = self._parse_entry(original) own = self._own_entry(system, before) wanted: dict[tuple, list[dict]] = {} - order: list[tuple[tuple, dict]] = [] + order: list[tuple[tuple, str]] = [] for text in self._bios_items(files, own): item = ast.literal_eval(text) key = tuple(item.get(k) for k in ("file", "zippedFile", "emulator", "core")) @@ -517,14 +547,7 @@ class Exporter(BaseExporter): continue if {k for k in {*ours, *theirs} if ours.get(k) != theirs.get(k)} - {"md5"}: return None - patched = _MD5_VALUE.sub( - lambda m: m.group(1) + _md5_literal( - ours["md5"], spaced=not m.group(2).startswith("[\"") - ), - match.group(0), - count=1, - ) - edits.append((match.start(), match.end(), patched)) + edits.append((match.start(), match.end(), _md5_patched(match.group(0), ours["md5"]))) if last is None: return None @@ -535,19 +558,7 @@ class Exporter(BaseExporter): if seen[key] > consumed.get(key, 0): added.append(text) if added: - # Their spacing before the closing brace: '"x"}' or '"x" }'. - tight = not last.group(0).endswith(" }") - added = [a[:-2] + "}" if tight and a.endswith(" }") else a for a in added] - if len(original) == 1: - insert = ", " + ", ".join(added) - else: - line_start = joined.rfind("\n", 0, last.start()) + 1 - indent = joined[line_start:last.start()] - insert = "," + "".join( - f"\n{indent}{a}" + ("," if i < len(added) - 1 else "") - for i, a in enumerate(added) - ) - edits.append((last.end(), last.end(), insert)) + edits.append((last.end(), last.end(), _appended_items(added, last, joined, original))) for start, end, text in sorted(edits, reverse=True): joined = joined[:start] + text + joined[end:] @@ -638,7 +649,8 @@ class Exporter(BaseExporter): spans = self._entry_spans(body) for key, (start, end) in spans.items(): parsed = self._parse_entry(body[start:end + 1]) or {} - own = parsed.get(key) if isinstance(parsed.get(key), dict) else {} + value = parsed.get(key) + own = value if isinstance(value, dict) else {} emulator, core = own.get("emulator"), own.get("core") self._gates[key] = ( (emulator, core if isinstance(core, str) else None) @@ -716,9 +728,11 @@ class Exporter(BaseExporter): issues.append(f"system absent: {system.native_id}") continue declared = {bios.get("file", "") for bios in entry.get("biosFiles", [])} - for fe in files: - if self.declared_path(fe) not in declared: - issues.append(f"absent: {system.native_id}/{fe.name}") + issues.extend( + f"absent: {system.native_id}/{fe.name}" + for fe in files + if self.declared_path(fe) not in declared + ) for native_id, entry in exported.items(): if not entry.get("biosFiles"): diff --git a/scripts/exporter/bizhawk_exporter.py b/scripts/exporter/bizhawk_exporter.py index 8806deed6..70bdd320d 100644 --- a/scripts/exporter/bizhawk_exporter.py +++ b/scripts/exporter/bizhawk_exporter.py @@ -18,7 +18,7 @@ SOURCE_URL = ( ) -class Exporter(BaseExporter): +class Exporter(BaseExporter[str]): """Serve BizHawk's FirmwareDatabase.cs as BizHawk wrote it.""" @staticmethod diff --git a/scripts/exporter/candidates.py b/scripts/exporter/candidates.py index a388c0256..6c2faaa89 100644 --- a/scripts/exporter/candidates.py +++ b/scripts/exporter/candidates.py @@ -22,6 +22,7 @@ from common import _norm_system_id, resolve_platform_cores, unresolved_platform_ from exporter.baseline import HASH_FIELDS, NativeSystem, _hash_values from launchers import _names as launcher_names + def _tails(path: str) -> list[str]: """Every trailing run of segments of a path, longest first.""" parts = [p for p in path.casefold().strip("/").split("/") if p] @@ -431,11 +432,12 @@ class EntryCategories: def cited(f: dict) -> dict: return {k: f[k] for k in ("name", "source_ref") if f.get(k)} - found: dict[int, dict] = {} - for values in declared.values(): - for value in values: - for position, f in by_hash_index.get(value, ()): - found[position] = f + found: dict[int, dict] = { + position: f + for values in declared.values() + for value in values + for position, f in by_hash_index.get(value, ()) + } if found: return [cited(found[p]) for p in sorted(found)] named = {position: f for n in names for position, f in by_name_index.get(n, ())} diff --git a/scripts/exporter/emudeck_exporter.py b/scripts/exporter/emudeck_exporter.py index 83d3258f9..d54505a26 100644 --- a/scripts/exporter/emudeck_exporter.py +++ b/scripts/exporter/emudeck_exporter.py @@ -27,7 +27,7 @@ SOURCE_URL = ( _MD5 = re.compile(r"^[0-9a-f]{32}$") -class Exporter(BaseExporter): +class Exporter(BaseExporter[str]): """Write EmuDeck's checkBIOS.sh, corrected.""" @staticmethod @@ -227,7 +227,5 @@ class Exporter(BaseExporter): if not _RE_LOCAL_HASHES.search(body): # A check with no hash list is a path check, not a hash check. continue - for md5 in md5s: - if md5 not in body: - issues.append(f"absent from {name}: {md5}") + issues.extend(f"absent from {name}: {md5}" for md5 in md5s if md5 not in body) return issues diff --git a/scripts/exporter/misterfpga_exporter.py b/scripts/exporter/misterfpga_exporter.py index 5d8b7b5e3..7fd2ca95f 100644 --- a/scripts/exporter/misterfpga_exporter.py +++ b/scripts/exporter/misterfpga_exporter.py @@ -11,6 +11,7 @@ import io import json import zipfile from collections import OrderedDict +from typing import Union from .base_exporter import BaseExporter from .baseline import NativeFile, NativeSystem, Report @@ -42,7 +43,7 @@ def rebuild_archive(original: bytes, member: str, text: str) -> bytes: return buffer.getvalue() -class Exporter(BaseExporter): +class Exporter(BaseExporter[Union[str, bytes]]): """Write MiSTer's bios_db.json, corrected.""" @staticmethod @@ -99,8 +100,8 @@ class Exporter(BaseExporter): """ return fe.record_hash(field_name) - def _by_path(self, systems: dict[str, NativeSystem]) -> dict[str, object]: - indexed: dict[str, object] = {} + def _by_path(self, systems: dict[str, NativeSystem]) -> dict[str, NativeFile]: + indexed: dict[str, NativeFile] = {} for system in systems.values(): for fe in system.files: if fe.destination: @@ -173,7 +174,7 @@ class Exporter(BaseExporter): def validate( self, systems: dict[str, NativeSystem], - produced: dict[str, str], + produced: dict[str, str | bytes], ) -> list[str]: try: database = json.loads(produced[_DB_NAME]) diff --git a/scripts/exporter/recalbox_exporter.py b/scripts/exporter/recalbox_exporter.py index 640658bd8..69e307c58 100644 --- a/scripts/exporter/recalbox_exporter.py +++ b/scripts/exporter/recalbox_exporter.py @@ -42,6 +42,36 @@ _SYSTEM_BLOCK = re.compile(r"", re.S) _BIOS_ELEMENT = re.compile(r"[ \t]*", re.S) +def _bios_line(attrs: dict[str, str]) -> str: + rendered = " ".join(f"{k}={quoteattr(v)}" for k, v in attrs.items()) + return f" " + + +def _block_body( + children: list[dict[str, str] | str], + elements: dict[str, tuple[NativeFile, str]], + raw: dict[str, str], +) -> list[str]: + """One block of theirs, each element corrected where ours differs.""" + body: list[str] = [] + for child in children: + if isinstance(child, str): + body.append(f" {child}") + continue + path = child.get("path", "") + mine = elements.pop(path, None) + kept = raw.get(" ".join(path.split())) + if kept is not None and (mine is None or _stated(mine[1]) == _stated(kept)): + body.append(kept) + elif kept is not None and mine is not None and _stated( + patched := patch_element(kept, mine[1]) + ) == _stated(mine[1]): + body.append(patched) + else: + body.append(mine[1] if mine else _bios_line(child)) + return body + + def _stated(text: str) -> dict[str, str]: """What an element says, without its layout: attribute order, spacing, line breaks inside a value and the case of a digest are not content.""" @@ -110,7 +140,7 @@ def _original_elements(original: str) -> list[dict[str, str]]: return blocks -class Exporter(BaseExporter): +class Exporter(BaseExporter[str]): """Write Recalbox's es_bios.xml, corrected.""" @staticmethod @@ -299,6 +329,50 @@ class Exporter(BaseExporter): return False return bool(fe.hashes("md5")) and bool(fe.cores()) + def _their_blocks(self, original: str) -> list[tuple[str, str, list[dict[str, str] | str]]]: + """Recalbox's blocks: platform, full name, and each bios element or + comment they hold.""" + if not original: + return [] + try: + root = parse_untrusted_xml(original, self.native_filename(), comments=True) + except (ParseError, ValueError) as exc: + # Rebuilt from our model alone, the export would drop every + # system we do not transcribe and the maintainer's comments. + raise ValueError( + f"Recalbox's {self.native_filename()} does not parse ({exc}); " + "fetch it again with --refresh-cache" + ) from exc + if root is None: + return [] + return [ + (s.get("platform", ""), s.get("fullname", ""), [ + f"" if child.tag is Comment else dict(child.attrib) + for child in s + if child.tag is Comment or child.tag == "bios" + ]) + for s in root.iter("system") + ] + + def _our_elements( + self, systems: dict[str, NativeSystem], + ) -> dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]]: + ours: dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]] = {} + for system in systems.values(): + # Two additions at one path (two cores, two dumps) are one + # element: keyed by path, the second replaced the first and its + # md5 left the file while both were counted added. + at_path: dict[str, list[NativeFile]] = {} + for fe in system.files: + if self.writable(fe): + at_path.setdefault(self._path(fe), []).append(fe) + if at_path: + ours[system.native_id] = (system, { + path: (group[0], self._bios_element(group[0], system.native_id, tuple(group[1:]))) + for path, group in at_path.items() + }) + return ours + def render( self, systems: dict[str, NativeSystem], @@ -316,27 +390,8 @@ class Exporter(BaseExporter): # and its system order with it. A platform can hold several blocks # (Pentagon and Scorpion are both zxspectrum), and an entry the # maintainer commented out stays commented out. - theirs: list[tuple[str, str, list[dict[str, str] | str]]] = [] original = originals.get(self.native_filename(), "") - if original: - try: - root = parse_untrusted_xml(original, self.native_filename(), comments=True) - except (ParseError, ValueError) as exc: - # Rebuilt from our model alone, the export would drop every - # system we do not transcribe and the maintainer's comments. - raise ValueError( - f"Recalbox's {self.native_filename()} does not parse ({exc}); " - "fetch it again with --refresh-cache" - ) from exc - if root is not None: - theirs = [ - (s.get("platform", ""), s.get("fullname", ""), [ - f"" if child.tag is Comment else dict(child.attrib) - for child in s - if child.tag is Comment or child.tag == "bios" - ]) - for s in root.iter("system") - ] + theirs = self._their_blocks(original) # Elements of theirs written back as they stand, by (platform, path). held = { @@ -353,24 +408,7 @@ class Exporter(BaseExporter): and not self.writable(fe) and (system.native_id, " ".join(self._path(fe).split())) in held } - ours: dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]] = {} - for system in systems.values(): - # Two additions at one path (two cores, two dumps) are one - # element: keyed by path, the second replaced the first and its - # md5 left the file while both were counted added. - at_path: dict[str, list[NativeFile]] = {} - for fe in system.files: - if self.writable(fe): - at_path.setdefault(self._path(fe), []).append(fe) - if at_path: - ours[system.native_id] = (system, { - path: (group[0], self._bios_element(group[0], system.native_id, tuple(group[1:]))) - for path, group in at_path.items() - }) - - def element(attrs: dict[str, str]) -> str: - rendered = " ".join(f"{k}={quoteattr(v)}" for k, v in attrs.items()) - return f" " + ours = self._our_elements(systems) def emit(platform: str, fullname: str, body: list[str], opening: str = "") -> None: stated = _stated(opening) if opening else {} @@ -392,23 +430,7 @@ class Exporter(BaseExporter): for index, (platform, fullname, children) in enumerate(theirs): elements = ours.get(platform, (None, {}))[1] raw = written[index] if index < len(written) else {} - body: list[str] = [] - for child in children: - if isinstance(child, str): - body.append(f" {child}") - continue - path = child.get("path", "") - mine = elements.pop(path, None) - kept = raw.get(" ".join(path.split())) - if kept is not None and (mine is None or _stated(mine[1]) == _stated(kept)): - body.append(kept) - elif kept is not None and mine is not None and _stated( - patched := patch_element(kept, mine[1]) - ) == _stated(mine[1]): - body.append(patched) - else: - body.append(mine[1] if mine else element(child)) - blocks.append((platform, fullname, body)) + blocks.append((platform, fullname, _block_body(children, elements, raw))) # An addition joins the block named like its file, else the first # block of its platform. @@ -446,18 +468,20 @@ class Exporter(BaseExporter): return [f"the XML does not parse: {exc}"] for element in root.iter("bios"): - for attribute in ("path", "md5", "core"): - if not element.get(attribute): - issues.append( - f"es_bios.xsd requires {attribute}: " - f"{element.get('path', '?')}" - ) + issues.extend( + f"es_bios.xsd requires {attribute}: " + f"{element.get('path', '?')}" + for attribute in ("path", "md5", "core") + if not element.get(attribute) + ) for element in root.iter("system"): if not list(element): issues.append(f"empty system: {element.get('platform', '?')}") - for attribute in ("fullname", "platform"): - if not element.get(attribute): - issues.append(f"es_bios.xsd requires {attribute} on system") + issues.extend( + f"es_bios.xsd requires {attribute} on system" + for attribute in ("fullname", "platform") + if not element.get(attribute) + ) exported = { element.get("path", "").casefold() for element in root.iter("bios") diff --git a/scripts/exporter/retrobat_exporter.py b/scripts/exporter/retrobat_exporter.py index 71f010aa1..a369d71c2 100644 --- a/scripts/exporter/retrobat_exporter.py +++ b/scripts/exporter/retrobat_exporter.py @@ -46,7 +46,7 @@ def keep_blank_lines(original: str, produced: str) -> str: return _TOP_KEY.sub(separate, produced) -class Exporter(BaseExporter): +class Exporter(BaseExporter[str]): """Write RetroBat's batocera-systems.json, corrected.""" # One md5 per entry, compared as Batocera's checkBios does. @@ -152,9 +152,10 @@ class Exporter(BaseExporter): if fe.platform is not None and fe.platform.get("required") is False: entry["optional"] = True ours.setdefault(path, entry) - bios_files = [] - for theirs in (base.get(key) or {}).get("biosFiles", []): - bios_files.append(ours.pop(theirs.get("file"), theirs)) + bios_files = [ + ours.pop(theirs.get("file"), theirs) + for theirs in (base.get(key) or {}).get("biosFiles", []) + ] bios_files.extend(ours.values()) system_entry: OrderedDict[str, object] = OrderedDict() system_entry["name"] = self.display_name(system) @@ -181,11 +182,13 @@ class Exporter(BaseExporter): issues.append(f"system without a name: {key}") if not entry.get("biosFiles"): issues.append(f"empty entry: {key}") - for bios in entry.get("biosFiles", []): - # RetroBat states an unhashed file with an empty md5, so only - # a missing path makes an entry unusable. - if "md5" not in bios or not bios.get("file"): - issues.append(f"incomplete entry: {key}/{bios.get('file', '?')}") + # RetroBat states an unhashed file with an empty md5, so only + # a missing path makes an entry unusable. + issues.extend( + f"incomplete entry: {key}/{bios.get('file', '?')}" + for bios in entry.get("biosFiles", []) + if "md5" not in bios or not bios.get("file") + ) for system, files in self.exportable(systems, require="md5"): entry = data.get(system.native_id) @@ -193,7 +196,9 @@ class Exporter(BaseExporter): issues.append(f"system absent: {system.native_id}") continue declared = {bios.get("file") for bios in entry.get("biosFiles", [])} - for fe in files: - if self._path(fe) not in declared: - issues.append(f"absent: {system.native_id}/{fe.name}") + issues.extend( + f"absent: {system.native_id}/{fe.name}" + for fe in files + if self._path(fe) not in declared + ) return issues diff --git a/scripts/exporter/retrodeck_exporter.py b/scripts/exporter/retrodeck_exporter.py index b9a88a027..075c4e6c4 100644 --- a/scripts/exporter/retrodeck_exporter.py +++ b/scripts/exporter/retrodeck_exporter.py @@ -62,7 +62,7 @@ def _matching_keys( return named if len(named) == 1 else [] -class Exporter(BaseExporter): +class Exporter(BaseExporter[str]): """Write RetroDECK's component manifests, corrected.""" @staticmethod @@ -229,10 +229,10 @@ class Exporter(BaseExporter): # ATARIOSB.ROM for atari5200 and atari800 with different md5 lists, # and a name-only key wrote the first of ours over both. by_key: OrderedDict[tuple[str, str], OrderedDict] = OrderedDict() - for entry in ours: - key = (str(entry.get("filename", "")), str(entry.get("system", ""))) + for own in ours: + key = (str(own.get("filename", "")), str(own.get("system", ""))) if key[0] and key not in by_key: - by_key[key] = entry + by_key[key] = own merged: list[OrderedDict] = [] corrected: set[tuple[str, str]] = set() @@ -261,31 +261,7 @@ class Exporter(BaseExporter): if other_revision or not keys: merged.append(OrderedDict(entry)) continue - declared = entry.get("system") - combined = OrderedDict(entry) - # Only what the format says it corrects: the maintainer's - # description and search paths are theirs (neogeo.zip lost its - # four roms directories to a path that does not exist). - combined.update( - (field, value) for field, value in by_key[keys[0]].items() - if field in cls.carries() and not (field == "system" and declared) - ) - # A hash of theirs that ours no longer carries is one the truth - # contradicts: kept, it went on rejecting the dump the emulator - # loads while the summary counted it cleared. - for field in ("md5", "sha256"): - if field in cls.carries() and field not in by_key[keys[0]]: - combined.pop(field, None) - if _md5_set(entry.get("md5")) == _md5_set(combined.get("md5")): - # Their own spelling, and no key where they wrote none: an - # equal empty set wrote "md5": null 39 times. - if "md5" in entry: - combined["md5"] = entry["md5"] - else: - combined.pop("md5", None) - elif isinstance(entry.get("md5"), list) and isinstance(combined.get("md5"), str): - combined["md5"] = [combined["md5"]] - merged.append(combined) + merged.append(cls._corrected(entry, by_key[keys[0]])) corrected.update(keys) uncorrected = [key for key in by_key if key not in corrected] @@ -302,15 +278,47 @@ class Exporter(BaseExporter): for e in merged for system in (_systems_of(e) or [""]) } - for index, entry in enumerate(additions or []): - key = (str(entry.get("filename", "")), str(entry.get("system", "")), _paths_key(entry)) - if key[0] and key not in held: - held.add(key) - merged.append(entry) + for index, addition in enumerate(additions or []): + slot = ( + str(addition.get("filename", "")), str(addition.get("system", "")), + _paths_key(addition), + ) + if slot[0] and slot not in held: + held.add(slot) + merged.append(addition) elif held_back is not None: held_back.append(index) return merged + @classmethod + def _corrected(cls, entry: dict, own: OrderedDict) -> OrderedDict: + """The platform's entry with the fields ours corrects.""" + declared = entry.get("system") + combined = OrderedDict(entry) + # Only what the format says it corrects: the maintainer's + # description and search paths are theirs (neogeo.zip lost its + # four roms directories to a path that does not exist). + combined.update( + (field, value) for field, value in own.items() + if field in cls.carries() and not (field == "system" and declared) + ) + # A hash of theirs that ours no longer carries is one the truth + # contradicts: kept, it went on rejecting the dump the emulator + # loads while the summary counted it cleared. + for field in ("md5", "sha256"): + if field in cls.carries() and field not in own: + combined.pop(field, None) + if _md5_set(entry.get("md5")) == _md5_set(combined.get("md5")): + # Their own spelling, and no key where they wrote none: an + # equal empty set wrote "md5": null 39 times. + if "md5" in entry: + combined["md5"] = entry["md5"] + else: + combined.pop("md5", None) + elif isinstance(entry.get("md5"), list) and isinstance(combined.get("md5"), str): + combined["md5"] = [combined["md5"]] + return combined + def lands(self, fe: NativeFile) -> bool: """An addition the list already held is not written a second time.""" return self.writable(fe) and id(fe) not in getattr(self, "_held_back", set()) diff --git a/scripts/exporter/retropie_exporter.py b/scripts/exporter/retropie_exporter.py index 8f9607365..bdd8a374b 100644 --- a/scripts/exporter/retropie_exporter.py +++ b/scripts/exporter/retropie_exporter.py @@ -53,7 +53,13 @@ _SEPARATOR = re.compile(r"\s*(?:,\s*(?:and\s+)?|and\s+)") _EXAMPLES = re.compile(r"\b(?:e\.?g\b|for example|for instance|such as|like)\W*$", re.I) -class Exporter(BaseExporter): +def _aliases(fe: NativeFile) -> list[object]: + """The other names a file is declared under.""" + aliases = fe.native("aliases", []) or [] + return list(aliases) if isinstance(aliases, (list, tuple)) else [] + + +class Exporter(BaseExporter[str]): """Write RetroPie's scriptmodules, corrected.""" @staticmethod @@ -332,108 +338,124 @@ class Exporter(BaseExporter): systems_of: dict[str, set[str]] = {} for system in systems.values(): for fe in system.files: - for name in [fe.name, *(fe.native("aliases", []) or [])]: + for name in [fe.name, *_aliases(fe)]: systems_of.setdefault(str(name).lower(), set()).add(fe.native_system) - known = set(systems_of) self._skipped: dict[str, list[str]] = {} # Rewritten, with a file of a system no clause lists left out. self._partial: list[str] = [] self._named: set[int] = set() produced: dict[str, str] = {} - def skip(reason: str, module: str) -> None: - self._skipped.setdefault(reason, []).append(module) - for relative, (module_id, help_text) in sorted(modules.items()): build = "libretro" if module_id.startswith("lr-") else "standalone" core = index[build].get(module_id.removeprefix("lr-").replace("-", "_").lower()) files = by_core.get(core or "", []) if not files: - skip("which no profiled core matches", module_id) + self._skip("which no profiled core matches", module_id) continue - - listed = self._listed(help_text) - unknown = sorted(listed - known) - if unknown: - skip( - f"whose help text names a file no profile documents yet ({', '.join(unknown)})", - module_id, - ) + new_help = self._new_help(module_id, help_text, files, core, systems_of) + if new_help is None: continue - - # A file already listed under one of its other names is not - # missing: proposing the primary would name the same bytes twice. - # A system RetroPie does not have is no package's: lr-geargrafx - # adds pcengine only, not the LaserActive its core also reads. - candidates = [ - fe - for fe in files - if not fe.foreign_system - and self._required_for(fe, core) - and not ( - {fe.name.lower()} - | {str(a).lower() for a in (fe.native("aliases", []) or [])} - ) - & listed - ] - filled = { - slot - for fe in files - if ({fe.name.lower()} - | {str(a).lower() for a in (fe.native("aliases", []) or [])}) & listed - and (slot := self._slot_of(fe)) is not None - } - proposed = self._one_per_slot(candidates, filled) - if not proposed: - continue - - # A file joins the list of its own system: the clause whose - # names the platform files under that system, and only one. - clauses = self._clauses(help_text) - homes: dict[int, list[NativeFile]] = {} - homeless = False - for fe in proposed: - owners = [ - i for i, (_, names, _) in enumerate(clauses) - if fe.native_system in set().union( - *(systems_of.get(n.lower(), set()) for n in names)) - ] - if len(owners) == 1 and clauses[owners[0]][2] is not None: - homes.setdefault(owners[0], []).append(fe) - else: - homeless = True - # No enumeration of that system to extend, and a sentence we - # would have to write ourselves is a documentation change, not a - # correction. With nothing placed the package is left as is. - if not homes: - skip("whose help text lists no files of that system to add to", module_id) - continue - - added = sum(len(self._in_search_order(fes)) for fes in homes.values()) - if len(listed) + added > self._longest: - skip("whose help text would grow longer than any it has today", module_id) - continue - - new_help = help_text - for i in sorted(homes, reverse=True): - start, _, enumeration = clauses[i] - missing = self._in_search_order(homes[i]) - new_help = self._extended(new_help, enumeration, missing) - if len(enumeration[2]) + len(missing) > 1: - new_help = new_help[:start] + _BIOS_NOUN.sub( - r"\1 files", new_help[start:enumeration[0]], count=1 - ) + new_help[enumeration[0]:] - self._named.update(id(fe) for fe in homes[i]) produced[relative] = originals[relative].replace( f'rp_module_help="{help_text}"', f'rp_module_help="{new_help}"', 1, ) - if homeless: - self._partial.append(module_id) return produced + def _skip(self, reason: str, module: str) -> None: + self._skipped.setdefault(reason, []).append(module) + + def _new_help( + self, + module_id: str, + help_text: str, + files: list[NativeFile], + core: str | None, + systems_of: dict[str, set[str]], + ) -> str | None: + """The help sentence with the files it lacks, None when left as is.""" + listed = self._listed(help_text) + unknown = sorted(listed - set(systems_of)) + if unknown: + self._skip( + f"whose help text names a file no profile documents yet ({', '.join(unknown)})", + module_id, + ) + return None + + # A file already listed under one of its other names is not + # missing: proposing the primary would name the same bytes twice. + # A system RetroPie does not have is no package's: lr-geargrafx + # adds pcengine only, not the LaserActive its core also reads. + candidates = [ + fe + for fe in files + if not fe.foreign_system + and self._required_for(fe, core) + and not ( + {fe.name.lower()} + | {str(a).lower() for a in _aliases(fe)} + ) + & listed + ] + filled = { + slot + for fe in files + if ({fe.name.lower()} + | {str(a).lower() for a in _aliases(fe)}) & listed + and (slot := self._slot_of(fe)) is not None + } + proposed = self._one_per_slot(candidates, filled) + if not proposed: + return None + + # A file joins the list of its own system: the clause whose + # names the platform files under that system, and only one. + clauses = self._clauses(help_text) + homes: dict[int, list[NativeFile]] = {} + enumerations: dict[int, tuple[int, int, list[str]]] = {} + homeless = False + for fe in proposed: + owners = [ + i for i, (_, names, _) in enumerate(clauses) + if fe.native_system in set().union( + *(systems_of.get(n.lower(), set()) for n in names)) + ] + enumeration = clauses[owners[0]][2] if len(owners) == 1 else None + if enumeration is not None: + homes.setdefault(owners[0], []).append(fe) + enumerations[owners[0]] = enumeration + else: + homeless = True + # No enumeration of that system to extend, and a sentence we + # would have to write ourselves is a documentation change, not a + # correction. With nothing placed the package is left as is. + if not homes: + self._skip("whose help text lists no files of that system to add to", module_id) + return None + + added = sum(len(self._in_search_order(fes)) for fes in homes.values()) + if len(listed) + added > self._longest: + self._skip("whose help text would grow longer than any it has today", module_id) + return None + + new_help = help_text + for i in sorted(homes, reverse=True): + start = clauses[i][0] + enumeration = enumerations[i] + missing = self._in_search_order(homes[i]) + new_help = self._extended(new_help, enumeration, missing) + if len(enumeration[2]) + len(missing) > 1: + new_help = new_help[:start] + _BIOS_NOUN.sub( + r"\1 files", new_help[start:enumeration[0]], count=1 + ) + new_help[enumeration[0]:] + self._named.update(id(fe) for fe in homes[i]) + if homeless: + self._partial.append(module_id) + return new_help + def lands(self, fe: NativeFile) -> bool: """An addition lands only where a help sentence now names it. diff --git a/scripts/exporter/romm_exporter.py b/scripts/exporter/romm_exporter.py index fb8acf801..6fb168485 100644 --- a/scripts/exporter/romm_exporter.py +++ b/scripts/exporter/romm_exporter.py @@ -30,7 +30,7 @@ SOURCE_URL = ( _FIELDS = (("size", "size"), ("crc", "crc32"), ("md5", "md5"), ("sha1", "sha1")) -class Exporter(BaseExporter): +class Exporter(BaseExporter[str]): """Write RomM's known_bios_files.json, corrected.""" def __init__(self) -> None: diff --git a/scripts/exporter/systemdat_exporter.py b/scripts/exporter/systemdat_exporter.py index 3bb02de04..3d4b1ac17 100644 --- a/scripts/exporter/systemdat_exporter.py +++ b/scripts/exporter/systemdat_exporter.py @@ -77,7 +77,25 @@ def _sections(original: str) -> list[tuple[str, list[str]]]: return sections -class Exporter(BaseExporter): +def _rom_fields(fe: NativeFile, name: str) -> list[str]: + """The fields of a rom line, in the order clrmamepro writes them.""" + parts = [f"name {name}"] + size = fe.size() + if size: + parts.append(f"size {size}") + crc = fe.record_hash("crc32") + if crc: + parts.append(f"crc {crc.upper()}") + md5 = fe.record_hash("md5") + if md5: + parts.append(f"md5 {md5}") + sha1 = fe.record_hash("sha1") + if sha1: + parts.append(f"sha1 {sha1}") + return parts + + +class Exporter(BaseExporter[str]): """Write libretro's System.dat, corrected.""" @staticmethod @@ -184,19 +202,7 @@ class Exporter(BaseExporter): if not any(fe.hash(h) for h in ("crc32", "md5", "sha1")): continue name = _quote(self._rom_name(fe), quoted) - parts = [f"name {name}"] - size = fe.size() - if size: - parts.append(f"size {size}") - crc = fe.record_hash("crc32") - if crc: - parts.append(f"crc {crc.upper()}") - md5 = fe.record_hash("md5") - if md5: - parts.append(f"md5 {md5}") - sha1 = fe.record_hash("sha1") - if sha1: - parts.append(f"sha1 {sha1}") + parts = _rom_fields(fe, name) if name in rendered: if fe.platform is None: self._shadowed.add(id(fe)) From 01ea18dc55ff0a508905f5c5ed913750705e71a7 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:54:05 +0100 Subject: [PATCH 6/9] chore: lint launchers, regions and slots --- scripts/gamedata.py | 10 +++--- scripts/launchers.py | 85 +++++++++++++++++++++++++++----------------- scripts/region.py | 5 +-- scripts/slot.py | 2 +- scripts/slots.py | 1 + 5 files changed, 64 insertions(+), 39 deletions(-) diff --git a/scripts/gamedata.py b/scripts/gamedata.py index 2035c9a9a..9a76c16df 100644 --- a/scripts/gamedata.py +++ b/scripts/gamedata.py @@ -139,10 +139,12 @@ def without_game_data( )) systems[sys_id] = {**system, "files": kept} if len(kept) != len(files) else system - for key in examined: - for fe in profiles[key].get("files") or []: - if isinstance(fe, dict) and is_game_data(fe): - left_out.append(LeftOut("core", "", str(fe.get("name") or ""), (key,))) + left_out.extend( + LeftOut("core", "", str(fe.get("name") or ""), (key,)) + for key in examined + for fe in profiles[key].get("files") or [] + if isinstance(fe, dict) and is_game_data(fe) + ) stripped = { key: ( diff --git a/scripts/launchers.py b/scripts/launchers.py index 78b92f676..3793db813 100644 --- a/scripts/launchers.py +++ b/scripts/launchers.py @@ -568,6 +568,16 @@ def launcher_unproven( return rows +def _place_paths(name: str, directories: list[str] | None) -> tuple[str, ...]: + """The paths a name is opened at: under each directory, or bare when the + record anchors it nowhere.""" + if directories is None: + return (name,) + return tuple( + sanitize_pack_path(f"{d}/{name}" if d else name) for d in directories + ) + + def launcher_places( config: dict, profiles: Mapping[str, dict] | None = None ) -> list[LauncherPlace]: @@ -583,14 +593,6 @@ def launcher_places( if not names or directories == []: continue anchored = directories is not None - - def paths_of(name: str) -> tuple[str, ...]: - if not anchored: - return (name,) - return tuple( - sanitize_pack_path(f"{d}/{name}" if d else name) for d in directories - ) - common = { "emulator": str(record.get("emulator", "")), "build": str(record.get("build", "")), @@ -607,8 +609,10 @@ def launcher_places( settings = name_settings(record, names) if kind == "names_searched": # Each directory in turn, every name in it. - depth = len(directories) if anchored else 1 - ordered = tuple(paths_of(name)[i] for i in range(depth) for name in names) + depth = len(directories) if directories is not None else 1 + ordered = tuple( + _place_paths(name, directories)[i] for i in range(depth) for name in names + ) places.append(LauncherPlace( paths=ordered, passes_to=str(record.get("passes_to") or ""), **common )) @@ -616,7 +620,9 @@ def launcher_places( # A fixed name is the one file passed, and a core option offers # each value as the file the user picks: one place per name. places.extend( - LauncherPlace(paths=paths_of(name), passes_to=settings[name], **common) + LauncherPlace( + paths=_place_paths(name, directories), passes_to=settings[name], **common + ) for name in names ) return places @@ -852,8 +858,8 @@ def handed_directories( if (handle := normalize_handle(token, home)) and handle != directory ) | ini_keys(passes_to) folder = _folder_in_bios(part, base) - for emulator in (e.strip() for e in str(record.get("emulator", "")).split(",")): - found.append(HandedDirectory( + found.extend( + HandedDirectory( emulator=emulator, folder=folder, directory=directory, @@ -868,7 +874,9 @@ def handed_directories( holds_declared=bool(folder) and any( d.startswith(f"{(folder or '').lower()}/") for d in declared ), - )) + ) + for emulator in (e.strip() for e in str(record.get("emulator", "")).split(",")) + ) return found @@ -999,10 +1007,12 @@ def executed_files(config: dict) -> list[ExecutedFile]: place = (EMULATORS_TREE, sanitize_pack_path(f"{emulator_folder}/{name}")) else: place = None - for emulator in (e.strip() for e in str(record.get("emulator", "")).split(",")): - found.append(ExecutedFile( + found.extend( + ExecutedFile( emulator, name.rsplit("/", 1)[-1], place, str(record.get("source_ref", "")) - )) + ) + for emulator in (e.strip() for e in str(record.get("emulator", "")).split(",")) + ) return found @@ -1440,6 +1450,26 @@ class LauncherLayer: pool = self.declared_names_folded if place.case_insensitive else self.declared_names return bool(place.basenames() & pool) + def _add_unoffered( + self, + by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]], + offered: set[int], + resolve_held: Callable[[dict], dict | None], + ) -> None: + """The entries the report left out, each answering only through a + launcher's setting or extended name.""" + for layout, members in self._unoffered.items(): + for entry, report in members: + if id(entry) in offered: + continue + if "<" not in str(entry.get("name", "")): + report["in_repo"] = resolve_held(report) is not None + report["unoffered"] = True + if (*layout, str(entry.get("name", "")), + str(entry.get("path") or "")) in self._declared_elsewhere: + report["declared_elsewhere"] = True + by_layout.setdefault(layout, []).append((entry, report)) + def settle( self, candidates: list[tuple[str, bool, dict, dict]], @@ -1470,18 +1500,9 @@ class LauncherLayer: by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]] = {} for emulator, standalone, entry, report in candidates: by_layout.setdefault((emulator, standalone), []).append((entry, report)) - offered = {id(entry) for _e, _s, entry, _r in candidates} - for layout, members in self._unoffered.items(): - for entry, report in members: - if id(entry) in offered: - continue - if "<" not in str(entry.get("name", "")): - report["in_repo"] = resolve_held(report) is not None - report["unoffered"] = True - if (*layout, str(entry.get("name", "")), - str(entry.get("path") or "")) in self._declared_elsewhere: - report["declared_elsewhere"] = True - by_layout.setdefault(layout, []).append((entry, report)) + self._add_unoffered( + by_layout, {id(entry) for _e, _s, entry, _r in candidates}, resolve_held, + ) placed: set[str] = set() for (emulator, standalone), members in sorted(by_layout.items()): for place in self.places_for(emulator, standalone): @@ -1621,9 +1642,9 @@ class LauncherLayer: continue if not report.get("in_repo"): continue - record = resolve_held(report) - if record is not None: - return report, record + held = resolve_held(report) + if held is not None: + return report, held for candidate, report in matched: if key not in candidate.names or not set_by(candidate.entry, place.passes_to): continue diff --git a/scripts/region.py b/scripts/region.py index 0fa9fcfda..1e1c93b1e 100644 --- a/scripts/region.py +++ b/scripts/region.py @@ -403,8 +403,9 @@ def resolve_region_drops( for destination, name in members if destination in rivals ] - known = None not in world_ranks - best_world = min(world_ranks) if known and world_ranks else None + ranked = [rank for rank in world_ranks if rank is not None] + known = len(ranked) == len(world_ranks) + best_world = min(ranked) if known and ranked else None for _r, destination in regional: name = next(n for d, n in members if d == destination) ours = lookup_priority(index, destination, name) diff --git a/scripts/slot.py b/scripts/slot.py index 68ce93cd5..3a25736da 100644 --- a/scripts/slot.py +++ b/scripts/slot.py @@ -193,7 +193,7 @@ def resolve_slot_drops( keep.update(dest for dest, _p in candidates) continue - best = min(p for _d, p in candidates) + best = min(p for _d, p in candidates if p is not None) winners = [dest for dest, p in candidates if p == best] if len(winners) != 1: undecidable.append(f"{group_id}|{','.join(tier)}" if tier else group_id) diff --git a/scripts/slots.py b/scripts/slots.py index 07b1c2d93..66f22b63c 100644 --- a/scripts/slots.py +++ b/scripts/slots.py @@ -75,6 +75,7 @@ def _size_the_code_reads(entry: dict, local: str | None) -> bool: except OSError: return False + # A core that reads ROMs inside an archive proves the archive by its members: # FBNeo's neocdz.zip is any copy holding neocd.bin and 000-lo.lo by crc. MEMBERS_HELD = "members_held" From 883af054debd6cad5d56d683a9753ecb6ade4ccd Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:21:11 +0100 Subject: [PATCH 7/9] refactor: keep the public signatures callers use --- scripts/cross_reference.py | 32 ++---- scripts/validation.py | 15 +-- scripts/verify.py | 201 +++++++++++++++++-------------------- 3 files changed, 97 insertions(+), 151 deletions(-) diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index cd37b85f5..d997bfa1c 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -23,7 +23,6 @@ from collections import Counter import dataclasses from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, TypedDict sys.path.insert(0, os.path.dirname(__file__)) from alternatives import set_keys, set_requirements, settle_sets @@ -82,9 +81,6 @@ from validation import ( with_archive_members, ) -if TYPE_CHECKING: - from typing_extensions import Unpack - yaml = require_yaml() DEFAULT_EMULATORS_DIR = "emulators" @@ -1459,25 +1455,18 @@ def print_launcher_reads(rows: list[dict]) -> None: ) -class ReportScope(TypedDict, total=False): - """What narrows a cross_reference run: the declarations it compares - against and the platform it answers for.""" - - all_declared: dict[str, list[tuple[int | None, str]]] | None - standalone_cores: set[str] | None - folded_slots: frozenset[str] - platform: str - launcher_layer: LauncherLayer | None - declared_contents: dict[str, set[str]] | None - - def cross_reference( profiles: dict[str, dict], declared: dict[str, set[str]], db: dict, platform_data_dirs: dict[str, set[str]] | None = None, data_names: set[str] | None = None, - **scope: Unpack[ReportScope], + all_declared: dict[str, list[tuple[int | None, str]]] | None = None, + standalone_cores: set[str] | None = None, + folded_slots: frozenset[str] = frozenset(), + platform: str = "", + launcher_layer: LauncherLayer | None = None, + declared_contents: dict[str, set[str]] | None = None, ) -> dict: """Compare emulator profiles against platform declarations. @@ -1494,15 +1483,6 @@ def cross_reference( instead of the per-system lookup. This is appropriate for the global gap analysis page where "undeclared" means "no platform declares it at all". """ - unknown = [key for key in scope if key not in ReportScope.__annotations__] - if unknown: - raise TypeError(f"cross_reference() got an unexpected keyword argument '{unknown[0]}'") - all_declared = scope.get("all_declared") - standalone_cores = scope.get("standalone_cores") - folded_slots = scope.get("folded_slots", frozenset()) - platform = scope.get("platform", "") - launcher_layer = scope.get("launcher_layer") - declared_contents = scope.get("declared_contents") platform_data_dirs = platform_data_dirs or {} by_name = db.get("indexes", {}).get("by_name", {}) by_name_lower = {k.lower(): k for k in by_name} diff --git a/scripts/validation.py b/scripts/validation.py index c1a0bbdf7..32fd9aded 100644 --- a/scripts/validation.py +++ b/scripts/validation.py @@ -11,7 +11,6 @@ import os import re import zipfile from collections.abc import Callable, Collection, Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, TypedDict from common import ( adler32_of, @@ -29,9 +28,6 @@ from hashing import md5_composite, parse_hash_list, parse_md5_list from nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file from ziptools import check_inside_zip -if TYPE_CHECKING: - from typing_extensions import Unpack - # Validation types that require console-specific cryptographic keys. # verify.py cannot reproduce these: size checks still apply if combined. _CRYPTO_CHECKS = frozenset({"signature", "crypto"}) @@ -1144,10 +1140,6 @@ def _owners_of(destination: str, name: str, owners: dict) -> set[str]: return {emu for tail, emu in matching if len(tail) == longest} -class _Judging(TypedDict, total=False): - emulators: set[str] | None - - def validated_choice( file_entry: dict, local_path: str | None, @@ -1157,7 +1149,7 @@ def validated_choice( platform_digest: str | None, destination: str = "", owners: dict | None = None, - **judging: Unpack[_Judging], + emulators: set[str] | None = None, ) -> tuple[str | None, str | None]: """The file a platform destination ships, and the disagreement if any. @@ -1166,12 +1158,7 @@ def validated_choice( manifest both read this, so they name the same file. A destination another emulator declares more precisely is that emulator's: ZEsarUX's 48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom. - ``emulators`` names the cores that judge the file, each by its own entries. """ - unknown = [key for key in judging if key not in _Judging.__annotations__] - if unknown: - raise TypeError(f"validated_choice() got an unexpected keyword argument '{unknown[0]}'") - emulators = judging.get("emulators") if not local_path or not validation_index: return local_path, None name = file_entry.get("name", "") diff --git a/scripts/verify.py b/scripts/verify.py index d1d5064b2..b7984e72f 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -33,7 +33,7 @@ from collections import Counter from collections.abc import Callable, Mapping from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, TypedDict +from typing import TYPE_CHECKING import slots @@ -137,8 +137,6 @@ from validation import ( from packpaths import core_save_folder if TYPE_CHECKING: - from typing_extensions import Unpack - from packextras import ExtraResolver yaml = require_yaml() @@ -600,7 +598,8 @@ class _GapScan: # In the emulator's own folder: no other core reads it. else ("emulator", emu_name) if f.get("unplaced") else None, ) - if not fname or unread_on(f, self.config.get("_key", "")): + config = self.config + if not fname or unread_on(f, config.get("_key", "")): return first = self.reported.get(seen_key) duplicate = seen_key in self.seen_files @@ -1380,15 +1379,6 @@ def _resolve_for_platform( return local_path, status -class PackNarrowing(TypedDict, total=False): - """The narrowings of a platform pack that verify_platform reports on.""" - - regions: list[str] | None - system_filter: list[str] | None - no_game_data: bool - required_only: bool - - @dataclass(frozen=True) class _PlatformRun: """The inputs of one verify_platform run, read by each of its stages.""" @@ -1457,6 +1447,7 @@ class _PlatformTally: ) self.details.append(result) config = self.run.config + mode = self.run.mode # Occupied only where the builder ships the declaration: a hash # the frontend refuses is left out, and the destination stays free # for a core's file the pack does carry. @@ -1464,8 +1455,7 @@ class _PlatformTally: local_path and result["status"] != Status.MISSING and baseline_verdict( - file_entry, local_path, resolve_status, self.run.mode, - config.get("hash_rule", ""), + file_entry, local_path, resolve_status, mode, config.get("hash_rule", "") )[1] is None ): self.packed_order.append((sys_id, self.run.full(destination), local_path)) @@ -1625,14 +1615,6 @@ class _PlatformTally: return counts, not_firmware -def _refuse_unknown_narrowings(narrowing: Mapping[str, object]) -> None: - unknown = [key for key in narrowing if key not in PackNarrowing.__annotations__] - if unknown: - raise TypeError( - f"verify_platform() got an unexpected keyword argument '{unknown[0]}'" - ) - - def _cut_game_data( config: dict, emu_profiles: dict | None, @@ -1813,7 +1795,10 @@ def verify_platform( emu_profiles: dict | None = None, target_cores: set[str] | None = None, data_dir_registry: dict | None = None, - **narrowing: Unpack[PackNarrowing], + regions: list[str] | None = None, + system_filter: list[str] | None = None, + no_game_data: bool = False, + required_only: bool = False, ) -> dict: """Verify all BIOS files for a platform, including cross-reference gaps. @@ -1828,11 +1813,6 @@ def verify_platform( declarations, trees and core extras marked ``required: false`` are left out before any of them takes a path, as the builder leaves them out. """ - _refuse_unknown_narrowings(narrowing) - regions = narrowing.get("regions") - system_filter = narrowing.get("system_filter") - no_game_data = narrowing.get("no_game_data", False) - required_only = narrowing.get("required_only", False) left_out: list[str] = [] if no_game_data: config, emu_profiles, left_out = _cut_game_data( @@ -2520,7 +2500,8 @@ def print_platform_result( label = " / ".join(group) if result.get("systems"): label += f" ({', '.join(result['systems'])})" - print(f"{label}: {', '.join(_platform_summary_parts(result))} [{mode}]") + parts = _platform_summary_parts(result) + print(f"{label}: {', '.join(parts)} [{mode}]") _print_release_assets(result["details"]) _print_platform_notices(result, verbose) @@ -2632,78 +2613,6 @@ def _emulator_files( return files -def _loose_result( - file_entry: dict, name: str, required: bool, local_path: str | None, - resolve_status: str, chosen_check: Callable[[], tuple[str | None, str | None]], -) -> dict: - """The verdict on a loose profile entry, from its resolution.""" - stored = _storage_verdict(file_entry, emulator_pack=True) - if stored is not None: - return stored - if resolve_status == RELEASE_ASSET_PENDING: - return { - "name": name, - "status": Status.OK, - "required": required, - "path": local_path, - "release_asset": local_path, - "reason": "release asset, fetched when the pack is built", - } - if not local_path: - result = {"name": name, "status": Status.MISSING, "required": required} - # An entry the profile documents as unsourceable is absent by - # design: a per-user key, a slot the user fills, a dump nobody - # has made. Counting it beside a file somebody could still - # find invites the wrong repair: dropping the flag, or - # chasing a vendor's whole install tree. - unsourceable = file_entry.get("unsourceable") - if unsourceable: - result["unsourceable"] = ( - unsourceable if isinstance(unsourceable, str) else "" - ) - return result - # Apply emulator validation - # Judged by this emulator's own entries, as it runs its check, - # through the selection the emulator pack makes. - chosen, disagreement = chosen_check() - if disagreement: - return { - "name": name, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": disagreement.split(" says ", 1)[-1], - } - if chosen != local_path: - return { - "name": name, - "status": Status.OK, - "required": required, - "path": chosen, - } - if resolve_status == "hash_mismatch": - # Nothing in validation: caught it, but the name matched - # while the bytes contradict the hash the profile - # declares. That is a different file wearing the right - # name (config.ini and ROM collide across systems), so - # calling it covered reports the collection as holding - # something it does not. Validation runs first because it - # names the specific field that disagrees. - return { - "name": name, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": "declared hash contradicted by the local file", - } - return { - "name": name, - "status": Status.OK, - "required": required, - "path": local_path, - } - - def _archive_result( archive: str, required: bool, local_path: str | None, resolve_status: str, ) -> dict: @@ -2975,13 +2884,8 @@ class _EmulatorPack: required = file_entry.get("required", True) hle = file_entry.get("hle_fallback", False) - result = _loose_result( - file_entry, name, required, local_path, resolve_status, - functools.partial( - validated_choice, file_entry, local_path, self.db, - self.validation_index, DEFAULT_BIOS_DIR, None, - emulators={emu_name}, - ), + result = self._loose_result( + file_entry, name, required, local_path, resolve_status, emu_name, ) result["system"] = file_entry.get("system", "") result["hle_fallback"] = hle @@ -2992,6 +2896,80 @@ class _EmulatorPack: emu_results.setdefault(dest, []).append((result, required, hle, file_entry)) return emu_results + def _loose_result( + self, file_entry: dict, name: str, required: bool, local_path: str | None, + resolve_status: str, emu_name: str, + ) -> dict: + """The verdict on a loose profile entry, from its resolution.""" + stored = _storage_verdict(file_entry, emulator_pack=True) + if stored is not None: + return stored + if resolve_status == RELEASE_ASSET_PENDING: + return { + "name": name, + "status": Status.OK, + "required": required, + "path": local_path, + "release_asset": local_path, + "reason": "release asset, fetched when the pack is built", + } + if not local_path: + result = {"name": name, "status": Status.MISSING, "required": required} + # An entry the profile documents as unsourceable is absent by + # design: a per-user key, a slot the user fills, a dump nobody + # has made. Counting it beside a file somebody could still + # find invites the wrong repair: dropping the flag, or + # chasing a vendor's whole install tree. + unsourceable = file_entry.get("unsourceable") + if unsourceable: + result["unsourceable"] = ( + unsourceable if isinstance(unsourceable, str) else "" + ) + return result + # Apply emulator validation + # Judged by this emulator's own entries, as it runs its check, + # through the selection the emulator pack makes. + chosen, disagreement = validated_choice( + file_entry, local_path, self.db, self.validation_index, DEFAULT_BIOS_DIR, + None, emulators={emu_name}, + ) + if disagreement: + return { + "name": name, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": disagreement.split(" says ", 1)[-1], + } + if chosen != local_path: + return { + "name": name, + "status": Status.OK, + "required": required, + "path": chosen, + } + if resolve_status == "hash_mismatch": + # Nothing in validation: caught it, but the name matched + # while the bytes contradict the hash the profile + # declares. That is a different file wearing the right + # name (config.ini and ROM collide across systems), so + # calling it covered reports the collection as holding + # something it does not. Validation runs first because it + # names the specific field that disagrees. + return { + "name": name, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": "declared hash contradicted by the local file", + } + return { + "name": name, + "status": Status.OK, + "required": required, + "path": local_path, + } + def _place_loose( self, emu_name: str, emu_results: dict[str, list[tuple[dict, bool, bool, dict]]], @@ -3336,7 +3314,8 @@ def print_emulator_result(result: dict, verbose: bool = False) -> None: """Print verification result for emulator/system mode.""" label = " + ".join(result["emulators"]) mode = result["verification_mode"] - print(f"{label}: {', '.join(_emulator_summary_parts(result))} [{mode}]") + parts = _emulator_summary_parts(result) + print(f"{label}: {', '.join(parts)} [{mode}]") fetched = sorted({d["name"] for d in result["details"] if d.get("release_asset")}) if fetched: shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") @@ -3550,7 +3529,7 @@ def _requested_regions(args: argparse.Namespace, parser: argparse.ArgumentParser def _check_mode(args: argparse.Namespace, parser: argparse.ArgumentParser) -> bool: - """Refuse a request naming no mode or several; returns the system mode.""" + """Refuse a request naming no mode or several, and say if it is the system mode.""" # --system beside --platform narrows that platform, as in generate_pack. system_mode = bool(args.system) and not args.platform modes = sum(1 for x in (args.platform, args.all, args.emulator, system_mode) if x) From bc50106587e9e69b1354acef95076cd98e9a7af4 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:48:13 +0100 Subject: [PATCH 8/9] refactor: take narrowing options as typed keywords --- scripts/cross_reference.py | 31 +++++++++++++++++++++++++------ scripts/validation.py | 16 +++++++++++++++- scripts/verify.py | 25 ++++++++++++++++++++----- 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index d997bfa1c..40e5ba394 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -23,6 +23,7 @@ from collections import Counter import dataclasses from dataclasses import dataclass from pathlib import Path +from typing import TYPE_CHECKING, TypedDict sys.path.insert(0, os.path.dirname(__file__)) from alternatives import set_keys, set_requirements, settle_sets @@ -81,6 +82,9 @@ from validation import ( with_archive_members, ) +if TYPE_CHECKING: + from typing_extensions import Unpack + yaml = require_yaml() DEFAULT_EMULATORS_DIR = "emulators" @@ -1455,18 +1459,24 @@ def print_launcher_reads(rows: list[dict]) -> None: ) +class ReportScope(TypedDict, total=False): + """What a cross_reference run compares against and answers for.""" + + all_declared: dict[str, list[tuple[int | None, str]]] | None + standalone_cores: set[str] | None + folded_slots: frozenset[str] + platform: str + launcher_layer: LauncherLayer | None + declared_contents: dict[str, set[str]] | None + + def cross_reference( profiles: dict[str, dict], declared: dict[str, set[str]], db: dict, platform_data_dirs: dict[str, set[str]] | None = None, data_names: set[str] | None = None, - all_declared: dict[str, list[tuple[int | None, str]]] | None = None, - standalone_cores: set[str] | None = None, - folded_slots: frozenset[str] = frozenset(), - platform: str = "", - launcher_layer: LauncherLayer | None = None, - declared_contents: dict[str, set[str]] | None = None, + **scope: Unpack[ReportScope], ) -> dict: """Compare emulator profiles against platform declarations. @@ -1483,6 +1493,15 @@ def cross_reference( instead of the per-system lookup. This is appropriate for the global gap analysis page where "undeclared" means "no platform declares it at all". """ + unknown = sorted(set(scope) - set(ReportScope.__annotations__)) + if unknown: + raise TypeError(f"cross_reference() got an unexpected keyword argument '{unknown[0]}'") + all_declared = scope.get("all_declared") + standalone_cores = scope.get("standalone_cores") + folded_slots = scope.get("folded_slots", frozenset()) + platform = scope.get("platform", "") + launcher_layer = scope.get("launcher_layer") + declared_contents = scope.get("declared_contents") platform_data_dirs = platform_data_dirs or {} by_name = db.get("indexes", {}).get("by_name", {}) by_name_lower = {k.lower(): k for k in by_name} diff --git a/scripts/validation.py b/scripts/validation.py index 32fd9aded..c07aebf6b 100644 --- a/scripts/validation.py +++ b/scripts/validation.py @@ -11,6 +11,7 @@ import os import re import zipfile from collections.abc import Callable, Collection, Iterator, Mapping, Sequence +from typing import TYPE_CHECKING, TypedDict from common import ( adler32_of, @@ -28,6 +29,9 @@ from hashing import md5_composite, parse_hash_list, parse_md5_list from nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file from ziptools import check_inside_zip +if TYPE_CHECKING: + from typing_extensions import Unpack + # Validation types that require console-specific cryptographic keys. # verify.py cannot reproduce these: size checks still apply if combined. _CRYPTO_CHECKS = frozenset({"signature", "crypto"}) @@ -1140,6 +1144,12 @@ def _owners_of(destination: str, name: str, owners: dict) -> set[str]: return {emu for tail, emu in matching if len(tail) == longest} +class Judges(TypedDict, total=False): + """The cores that judge a file in validated_choice, each by its own entries.""" + + emulators: set[str] | None + + def validated_choice( file_entry: dict, local_path: str | None, @@ -1149,7 +1159,7 @@ def validated_choice( platform_digest: str | None, destination: str = "", owners: dict | None = None, - emulators: set[str] | None = None, + **judging: Unpack[Judges], ) -> tuple[str | None, str | None]: """The file a platform destination ships, and the disagreement if any. @@ -1159,6 +1169,10 @@ def validated_choice( another emulator declares more precisely is that emulator's: ZEsarUX's 48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom. """ + unknown = sorted(set(judging) - set(Judges.__annotations__)) + if unknown: + raise TypeError(f"validated_choice() got an unexpected keyword argument '{unknown[0]}'") + emulators = judging.get("emulators") if not local_path or not validation_index: return local_path, None name = file_entry.get("name", "") diff --git a/scripts/verify.py b/scripts/verify.py index b7984e72f..e8ae68319 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -33,7 +33,7 @@ from collections import Counter from collections.abc import Callable, Mapping from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, TypedDict import slots @@ -137,6 +137,8 @@ from validation import ( from packpaths import core_save_folder if TYPE_CHECKING: + from typing_extensions import Unpack + from packextras import ExtraResolver yaml = require_yaml() @@ -1788,6 +1790,15 @@ def _profile_coverage( return with_validation, with_profile +class PlatformNarrowing(TypedDict, total=False): + """The narrowings of a platform pack verify_platform reports on.""" + + regions: list[str] | None + system_filter: list[str] | None + no_game_data: bool + required_only: bool + + def verify_platform( config: dict, db: dict, @@ -1795,10 +1806,7 @@ def verify_platform( emu_profiles: dict | None = None, target_cores: set[str] | None = None, data_dir_registry: dict | None = None, - regions: list[str] | None = None, - system_filter: list[str] | None = None, - no_game_data: bool = False, - required_only: bool = False, + **narrowing: Unpack[PlatformNarrowing], ) -> dict: """Verify all BIOS files for a platform, including cross-reference gaps. @@ -1813,6 +1821,13 @@ def verify_platform( declarations, trees and core extras marked ``required: false`` are left out before any of them takes a path, as the builder leaves them out. """ + unknown = sorted(set(narrowing) - set(PlatformNarrowing.__annotations__)) + if unknown: + raise TypeError(f"verify_platform() got an unexpected keyword argument '{unknown[0]}'") + regions = narrowing.get("regions") + system_filter = narrowing.get("system_filter") + no_game_data = narrowing.get("no_game_data", False) + required_only = narrowing.get("required_only", False) left_out: list[str] = [] if no_game_data: config, emu_profiles, left_out = _cut_game_data( From 81a94fc2672becb9f6e8e581dd5a280fd92524d3 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:48:13 +0100 Subject: [PATCH 9/9] refactor: make writable an instance method --- scripts/exporter/base_exporter.py | 5 ++--- scripts/exporter/emudeck_exporter.py | 4 +++- scripts/exporter/recalbox_exporter.py | 3 +-- scripts/exporter/retrodeck_exporter.py | 3 +-- scripts/exporter/systemdat_exporter.py | 3 +-- tests/test_export_counts.py | 6 +++--- tests/test_exporters.py | 22 ++++++++++++++++++++-- 7 files changed, 31 insertions(+), 15 deletions(-) diff --git a/scripts/exporter/base_exporter.py b/scripts/exporter/base_exporter.py index c3bc14244..756c922d6 100644 --- a/scripts/exporter/base_exporter.py +++ b/scripts/exporter/base_exporter.py @@ -167,8 +167,7 @@ class BaseExporter(ABC, Generic[Content]): list carries.""" return False - @classmethod - def writable(cls, fe: NativeFile, require: str = "") -> bool: + def writable(self, fe: NativeFile, require: str = "") -> bool: """Whether this format can carry the entry. An entry the platform already declares is always carried, hash or @@ -176,7 +175,7 @@ class BaseExporter(ABC, Generic[Content]): hands back a file poorer than the one it corrects. The requirement only gates what we would be adding. """ - return cls._carried(fe, require, cls.SINGLE_HASH_FIELD) + return self._carried(fe, require, self.SINGLE_HASH_FIELD) @classmethod def _carried(cls, fe: NativeFile, require: str, single: str | None) -> bool: diff --git a/scripts/exporter/emudeck_exporter.py b/scripts/exporter/emudeck_exporter.py index d54505a26..47f7a9621 100644 --- a/scripts/exporter/emudeck_exporter.py +++ b/scripts/exporter/emudeck_exporter.py @@ -135,7 +135,9 @@ class Exporter(BaseExporter[str]): if system.native_id != system_id: continue for fe in system.files: - if not cls.writable(fe): + # The base writable rule, which EmuDeck keeps: it needs no + # render state, so the class answers it. + if not cls._carried(fe, "", cls.SINGLE_HASH_FIELD): continue for value in cls._entry_md5s(fe): if _MD5.match(value) and value not in seen: diff --git a/scripts/exporter/recalbox_exporter.py b/scripts/exporter/recalbox_exporter.py index 69e307c58..210894150 100644 --- a/scripts/exporter/recalbox_exporter.py +++ b/scripts/exporter/recalbox_exporter.py @@ -318,8 +318,7 @@ class Exporter(BaseExporter[str]): for label in sorted(getattr(self, "_held_whole", {}).values()) ] - @classmethod - def writable(cls, fe: NativeFile, require: str = "") -> bool: + def writable(self, fe: NativeFile, require: str = "") -> bool: """es_bios.xsd makes md5 and core required: without them, no element. An entry Recalbox already ships has both, so this only ever gates diff --git a/scripts/exporter/retrodeck_exporter.py b/scripts/exporter/retrodeck_exporter.py index 075c4e6c4..328920cf1 100644 --- a/scripts/exporter/retrodeck_exporter.py +++ b/scripts/exporter/retrodeck_exporter.py @@ -83,8 +83,7 @@ class Exporter(BaseExporter[str]): # one from BIOS data alone would throw the component away. return True - @classmethod - def writable(cls, fe: NativeFile, require: str = "") -> bool: + def writable(self, fe: NativeFile, require: str = "") -> bool: """An addition lands only in a manifest it can be placed in.""" if fe.platform is None and not fe.native("component", ""): return False diff --git a/scripts/exporter/systemdat_exporter.py b/scripts/exporter/systemdat_exporter.py index 3d4b1ac17..6e54f79a7 100644 --- a/scripts/exporter/systemdat_exporter.py +++ b/scripts/exporter/systemdat_exporter.py @@ -114,8 +114,7 @@ class Exporter(BaseExporter[str]): def native_sources() -> dict[str, str]: return {"System.dat": SOURCE_URL} - @classmethod - def writable(cls, fe: NativeFile, require: str = "") -> bool: + def writable(self, fe: NativeFile, require: str = "") -> bool: """A clrmamepro rom line is a hash record, and the DAT has no other. The original never states a rom it cannot hash, so neither do we. diff --git a/tests/test_export_counts.py b/tests/test_export_counts.py index 3f78e2e68..b39ee258d 100644 --- a/tests/test_export_counts.py +++ b/tests/test_export_counts.py @@ -145,7 +145,7 @@ class RetroDeckWritesWhatItCounts(unittest.TestCase): written = json.loads(produced["duckstation/component_manifest.json"]) names = [e["filename"] for e in written["duckstation"]["bios"]] self.assertIn("b.bin", names) - self.assertFalse(RetroDeck.writable(spread.files[2])) + self.assertFalse(RetroDeck().writable(spread.files[2])) class HashesTheFormatCannotHold(unittest.TestCase): @@ -434,8 +434,8 @@ class OneMd5FormatsAddWhole(unittest.TestCase): several = NativeFile("boot.bin", "boot.bin", "dc", truth={"md5": [A, B, C]}) single = NativeFile("boot2.bin", "boot2.bin", "dc", truth={"md5": A}) - self.assertFalse(RetroBat.writable(several)) - self.assertTrue(RetroBat.writable(single)) + self.assertFalse(RetroBat().writable(several)) + self.assertTrue(RetroBat().writable(single)) class BizHawkKeepsItsOwnHashes(unittest.TestCase): diff --git a/tests/test_exporters.py b/tests/test_exporters.py index 4bb1cc614..306babfad 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -558,7 +558,7 @@ class Reconciliation(unittest.TestCase): } systems, _ = build_native_model({"systems": {}}, scraped) entry = systems["nds"].files[0] - self.assertTrue(BaseExporter.writable(entry, require="md5")) + self.assertTrue(_BaseRule().writable(entry, require="md5")) def test_no_format_drops_what_the_platform_already_declares(self): """An export poorer than the file it corrects is not usable.""" @@ -579,7 +579,25 @@ class Reconciliation(unittest.TestCase): } systems, _ = build_native_model(truth, None) entry = systems["nintendo-ds"].files[0] - self.assertFalse(BaseExporter.writable(entry, require="md5")) + self.assertFalse(_BaseRule().writable(entry, require="md5")) + + +class _BaseRule(BaseExporter): + """A concrete exporter that keeps every rule of the base class.""" + + @staticmethod + def platform_name() -> str: + return "base" + + @staticmethod + def native_filename() -> str: + return "base" + + def render(self, systems, report, originals, scraped=None): + return {} + + def validate(self, systems, produced): + return [] class ExporterRegistry(unittest.TestCase):