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] 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.