From ce92eff0aa981ab908b46da2ff54a65f48daacaf Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:16:29 +0100 Subject: [PATCH] refactor: split core extras by subject --- .github/workflows/deploy-site.yml | 4 + scripts/packs/coverage.py | 12 +- scripts/packs/datatrees.py | 2 +- scripts/packs/emulatorcheck.py | 2 +- scripts/packs/emulatorentries.py | 3 +- scripts/packs/emulatorpack.py | 2 +- scripts/packs/extraplace.py | 496 ++++++++ scripts/packs/extraregions.py | 438 +++++++ scripts/packs/extraresolver.py | 298 +++++ scripts/packs/extras.py | 1817 +--------------------------- scripts/packs/extrascan.py | 626 ++++++++++ scripts/packs/manifestbuild.py | 8 +- scripts/packs/manifestcores.py | 7 +- scripts/packs/manifestentry.py | 4 +- scripts/packs/manifestselect.py | 4 +- scripts/packs/packplan.py | 3 +- scripts/packs/platformcheck.py | 4 +- scripts/packs/platformpack.py | 8 +- scripts/packs/platformzip.py | 10 +- scripts/packs/slots.py | 4 +- tests/test_agnostic_scan.py | 5 +- tests/test_agnostic_scope.py | 4 +- tests/test_audit_regressions.py | 28 +- tests/test_bios_companions.py | 6 +- tests/test_content_checks.py | 3 +- tests/test_directory_entries.py | 2 +- tests/test_e2e.py | 4 +- tests/test_hidden_extras.py | 8 +- tests/test_launcher_layer.py | 3 +- tests/test_mame_devices.py | 3 +- tests/test_pack_counts.py | 3 +- tests/test_region.py | 14 +- tests/test_region_agnostic_scan.py | 2 +- tests/test_region_groups.py | 6 +- tests/test_region_held.py | 4 +- tests/test_region_required_only.py | 4 +- tests/test_system_ids.py | 3 +- tests/test_system_pack_extras.py | 2 +- tests/test_system_selection.py | 2 +- tests/test_unplaced_extras.py | 2 +- tests/test_validated_choice.py | 15 +- tests/test_validation_scope.py | 3 +- wiki/adding-a-platform.md | 2 +- 43 files changed, 1976 insertions(+), 1904 deletions(-) create mode 100644 scripts/packs/extraplace.py create mode 100644 scripts/packs/extraregions.py create mode 100644 scripts/packs/extraresolver.py create mode 100644 scripts/packs/extrascan.py diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index ea49db98f..eb3f91b97 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -89,7 +89,11 @@ on: - "scripts/packs/datadirextract.py" - "scripts/packs/datadirs.py" - "scripts/packs/executable.py" + - "scripts/packs/extraplace.py" + - "scripts/packs/extraregions.py" + - "scripts/packs/extraresolver.py" - "scripts/packs/extras.py" + - "scripts/packs/extrascan.py" - "scripts/packs/gaps.py" - "scripts/packs/naming.py" - "scripts/packs/parts.py" diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py index 672d0c875..a70415358 100644 --- a/scripts/packs/coverage.py +++ b/scripts/packs/coverage.py @@ -28,7 +28,7 @@ from resolve.validation import build_validation_index from resolve.acceptance import destination_owners if TYPE_CHECKING: - from packs.extras import ExtraResolver + from packs.extraresolver import ExtraResolver from typing_extensions import Unpack from packs.platformtally import ( DeclarationResolver, @@ -57,7 +57,7 @@ _UNPLACED_REASONS = { def _mark_unplaced(config: dict, undeclared: list[dict], profiles: dict) -> None: """What the builder cannot place is not in the pack, held or not.""" - from packs.extras import unplaceable_extras + from packs.extraresolver import unplaceable_extras unplaced = unplaceable_extras(config, undeclared, profiles) for u in undeclared: @@ -116,7 +116,7 @@ def _mark_hidden( ``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 packs.extras import hidden_extras + from packs.extraresolver import hidden_extras placed: set[str] = set() hidden = hidden_extras( @@ -215,7 +215,7 @@ def _region_pass( # 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 packs.extras import platform_region_groups + from packs.extraregions import platform_region_groups config = run.config held: set[str] = set() @@ -255,7 +255,7 @@ def _narrowed( """The rows of the core walk a narrowed pack keeps, as the builder keeps them.""" if run.system_filter: # A system pack carries the extras its systems own. - from packs.extras import report_owned_by_systems + from packs.extraregions import report_owned_by_systems rows = report_owned_by_systems(rows, run.system_filter) if run.required_only: @@ -308,7 +308,7 @@ def _platform_gaps( spares = core_file_spares(undeclared) undeclared = [u for u in undeclared if id(u) not in spares] _mark_unplaced(config, undeclared, run.profiles) - from packs.extras import ExtraResolver + from packs.extraresolver import ExtraResolver placed_kind: dict[str, str] = {} placed = _mark_hidden(config, undeclared, occupied, _BuilderPass( diff --git a/scripts/packs/datatrees.py b/scripts/packs/datatrees.py index a5fb3ed51..c4f6cec41 100644 --- a/scripts/packs/datatrees.py +++ b/scripts/packs/datatrees.py @@ -16,7 +16,7 @@ from model.profiles import entry_system_ids, installed_data_refs_in from model.systems import norm_system_id from packs.archive import PackRecord, Placed, add_pack_member from packs.datadirs import cache_lock, revisioned -from packs.extras import prefixed_destination +from packs.extraplace import prefixed_destination from packs.paths import MEDIA_MARKER, lands_on_android from resolve.cores import resolve_platform_cores as _platform_cores from resolve.layout import core_system_dirs diff --git a/scripts/packs/emulatorcheck.py b/scripts/packs/emulatorcheck.py index f7303e7be..a54fbde70 100644 --- a/scripts/packs/emulatorcheck.py +++ b/scripts/packs/emulatorcheck.py @@ -527,7 +527,7 @@ def verify_emulator( # The emulator pack withdraws these, and the report withdraws the same. region_drops: set[str] = set() if regions: - from packs.extras import emulator_region_drops + from packs.extraregions import emulator_region_drops region_drops = emulator_region_drops( selected, standalone, regions, required_only, db=db, diff --git a/scripts/packs/emulatorentries.py b/scripts/packs/emulatorentries.py index 07e954d1d..a49f1fac7 100644 --- a/scripts/packs/emulatorentries.py +++ b/scripts/packs/emulatorentries.py @@ -5,7 +5,8 @@ from __future__ import annotations from dataclasses import dataclass, field from model.profiles import entry_serves_systems -from packs.extras import emulator_required_spares, expand_agnostic_entries +from packs.extraregions import emulator_required_spares +from packs.extrascan import expand_agnostic_entries from packs.paths import archive_destination, resolve_destination from resolve.archives import archive_entry, archive_is_optional from resolve.directories import expand_directory_entries diff --git a/scripts/packs/emulatorpack.py b/scripts/packs/emulatorpack.py index 1a91d76a8..bc59c14db 100644 --- a/scripts/packs/emulatorpack.py +++ b/scripts/packs/emulatorpack.py @@ -40,7 +40,7 @@ from packs.archive import ( ) from packs.datatrees import carried_trees, pack_data_tree from packs.emulatorentries import EmulatorSelection, emulator_pack_entries -from packs.extras import emulator_region_drops +from packs.extraregions import emulator_region_drops from packs.naming import ( MAX_PACK_NAME_BYTES, bounded_join, file_name_part, pack_narrowings, system_display_name, ) diff --git a/scripts/packs/extraplace.py b/scripts/packs/extraplace.py new file mode 100644 index 000000000..e43055a3f --- /dev/null +++ b/scripts/packs/extraplace.py @@ -0,0 +1,496 @@ +"""Where a core extra lands in a pack and which extra takes a destination.""" + +from __future__ import annotations + +from core.paths import declared_destination, sanitize_pack_path +from model.declarations import OUTER_ROOTS, declared_root, outer_layout +from model.profiles import entry_system_ids, lists_files, profile_names +from packs.paths import libretro_systems, save_destination, save_layout +from resolve.archives import archive_members +from resolve.launches import PlatformLaunches +from resolve.layout import core_system_dirs, system_dir_path +from resolve.standalone import platform_layouts + + +def detect_extras_prefix(config: dict, base_dest: str) -> str: + """The prefix core-extra destinations take (may be empty). + + When base_destination is empty (RetroDECK), it is the dominant root of + the YAML-declared destinations. + """ + return base_dest or declared_root(config) + + +def extra_full_destination(fe: dict, prefix: str) -> str: + """Where a pack writes a core extra, from the pack root. + + A file the core reads below the frontend's save directory goes to the + pack path its placement recorded (ExtraPlacement.place). Any other one + goes below the platform's prefix, unless its destination carries it. + The builder, the manifest and verify's replay all read this. + """ + if fe.get("root") == "save": + return str(fe.get("pack_path") or "") + if fe.get("unprefixed"): + # A path of the install tree outside the BIOS folder (AmberELEC's + # pico-8/ beside bios/): no platform prefix in front. + return declared_destination(fe) + if fe.get("root") in OUTER_ROOTS: + return outer_destination( + fe["root"], declared_destination(fe) + ) + return prefixed_destination( + declared_destination(fe), prefix + ) + + +def outer_destination(root: str, dest: str) -> str: + """The key of a destination below the roms or an emulator folder. + + Kept apart from the BIOS tree's paths and never written into a pack: + the pack is extracted into the BIOS folder, and the installer places + these files (``root: roms``, ``root: emulators``). + """ + return f"{root}:{dest}" + + +def prefixed_destination(dest: str, prefix: str) -> str: + """A core extra's destination from the pack root. + + The one rule the collector, the builder and the manifest place a file + by. DuckStation's standalone `bios/` on Recalbox lands in the + `bios` folder itself: deduplicated at `bios/bios/` but written at + `bios/`, it let PCSX2's scan claim the same path under another + key, and `--region` withdrew one claim while the other kept the file. + """ + if not dest or not prefix or dest.startswith(f"{prefix}/"): + return dest + return f"{prefix}/{dest}" + + +def extra_region_key(fe: dict, prefix: str) -> str: + """The key a core extra is grouped, dropped and held under by --region. + + Its destination with the BIOS directory the platform writes in front of + its own (declared_root): RetroDECK declares bios/scph5501.bin, and + Beetle PSX's scph5501.bin grouped bare was looked up under another key, + kept by the pack while the declaration of the same file was dropped, + and the installer, which records the path once, dropped it. + """ + return prefixed_destination( + declared_destination(fe), prefix + ) + + +def save_entry_fields(fe: dict) -> dict: + """What a manifest entry adds for a file read below the save directory. + + ``root: save`` puts its ``dest`` below the frontend's save directory, + laid out as the pack lays it out. ``core_folder`` is the core's + library_name when the platform's frontend inserts it as the first folder + of ``dest`` (RetroArch's sort_savefiles_enable): the installer drops it + where the frontend's own config turns sorting off. + """ + fields = {"root": "save"} + if fe.get("core_folder"): + fields["core_folder"] = str(fe["core_folder"]) + return fields + + +def save_manifest_dest(fe: dict) -> str: + """A manifest dest for a file read below the save directory. + + The pack path below the platform's save folder when the file is placed + (``save_dest``), the system's folder first where the launcher keeps one + per system, the core's own folder first where the frontend sorts saves + by core. + Without a save folder (an omission), the same shape: the core's folder, + then the path the core reads, so two cores reading one name below their + own folders stay two entries. + """ + if fe.get("save_dest"): + return str(fe["save_dest"]) + rel = sanitize_pack_path(fe.get("destination") or fe.get("path") or fe.get("name", "")) + folder = fe.get("core_folder") + return f"{folder}/{rel}" if folder else rel + + +def _detect_slug_structure(config: dict) -> tuple[bool, dict[str, str]]: + """Detect whether a platform uses per-system slug destinations. + + Returns ``(is_slug_based, system_to_slug)`` where ``system_to_slug`` + maps system IDs to their destination slug prefix. Slug-based means + each system's files live under a per-system subfolder (e.g. RomM's + ``bios/{platform_slug}/{file}``), with varying slugs across systems. + + Only returns True when nearly ALL destinations have a subfolder and + nearly ALL systems map to a consistent slug, distinguishing true + slug-based layouts (RomM) from platforms that happen to have some + subfoldered files (RetroArch ``dc/``, ``neocd/``). + """ + total_files = 0 + files_with_slash = 0 + sys_to_slug: dict[str, str] = {} + total_systems_with_files = 0 + for sys_id, sys_data in config.get("systems", {}).items(): + files = sys_data.get("files", []) + if not files: + continue + total_systems_with_files += 1 + slugs: set[str] = set() + for f in files: + d = f.get("destination", "") + if d: + total_files += 1 + if "/" in d: + files_with_slash += 1 + slugs.add(d.split("/", 1)[0]) + if len(slugs) == 1: + sys_to_slug[sys_id] = slugs.pop() + + if not sys_to_slug or total_files == 0: + return False, {} + # All conditions must hold for slug-based detection: + # 1. Nearly all files have a subfolder + # 2. Multiple distinct slugs (not a constant prefix) + # 3. Nearly all systems with files map to a slug + # 4. Files are exactly slug/filename (depth 2), not deeper + unique_slugs = set(sys_to_slug.values()) + all_have_slash = files_with_slash / total_files > 0.95 + varying_slugs = len(unique_slugs) > 1 + high_coverage = len(sys_to_slug) / total_systems_with_files > 0.9 + # Count files deeper than slug/filename (e.g., amiga/bios/kick.rom) + deep_files = 0 + for sys_data in config.get("systems", {}).values(): + for f in sys_data.get("files", []): + d = f.get("destination", "") + if d and d.count("/") > 1: + deep_files += 1 + shallow = deep_files / total_files < 0.05 if total_files else True + return (all_have_slash and varying_slugs and high_coverage and shallow), sys_to_slug + +def _map_emulator_to_slug( + profile: dict, + platform_systems: set[str], + norm_map: dict[str, str], + sys_to_slug: dict[str, str], +) -> str: + """Map an emulator to a destination slug for slug-based platforms.""" + from model.systems import norm_system_id + + emu_systems = set(profile.get("systems", [])) + # Direct match + direct = emu_systems & platform_systems + if direct: + target = sorted(direct)[0] + return sys_to_slug.get(target, "") + # Normalized match + for es in sorted(emu_systems): + norm = norm_system_id(es) + if norm in norm_map: + target = norm_map[norm] + return sys_to_slug.get(target, "") + return "" + +def _slug_for( + u: dict, profiles: dict, platform_systems: set, norm_map: dict, sys_to_slug: dict, + native_systems: set | None = None, +) -> str: + """The platform slug a report entry files under, or empty. + + The entry's own system decides, and alone: picodrive's Mega CD BIOS + belongs under segacd/, where RomM looks for a Mega CD game's firmware, + and a file of a system the platform lacks has no folder there (MAME + 2003's ZN-1 BIOS once fell back on its Neo Geo systems). A file of no + system takes the emulator's first system the platform declares for + itself: a folder present only as a mirror of another slug's firmware + (RomM's neogeoaes/) says nothing about the emulators that read it. + """ + own = u.get("system") + if own: + return _map_emulator_to_slug( + {"systems": [own]}, platform_systems, norm_map, sys_to_slug + ) + emu_name = u.get("profile") or u.get("emulator", "") + # The report carries the entry's own systems: (a MAME device set) or + # its profile's, the same list either way when the entry names none. + profile = {"systems": u["systems"]} if u.get("systems") else profiles.get(emu_name, {}) + if not profile: + # The report names the display name where the key failed. + profile = next( + (pp for pp in profiles.values() if pp.get("emulator") == emu_name), {} + ) + systems = platform_systems if native_systems is None else native_systems + native_norm = {k: v for k, v in norm_map.items() if v in systems} + return _map_emulator_to_slug(profile, systems, native_norm, sys_to_slug) + + +def native_slug_systems(config: dict) -> set[str]: + """Systems the platform declares at least one file of its own for.""" + return { + sid for sid, data in (config.get("systems") or {}).items() + if any(not f.get("mirror_of") for f in data.get("files", [])) + } + + +def extra_dest(u: dict) -> str: + """Where a report entry lands before any platform prefix. + + An archive entry goes by the archive's name, and a directory path takes + the file's name after it ("cafeLibs/" + "snd_user.rpl"). A directory + entry ("registered/") is that path itself. + """ + archive = u.get("archive") + # An archive goes at the root of the core's system directory, which a + # platform handing each core its own folder writes in the path. + raw = (u.get("path") or archive) if archive else (u.get("path") or u["name"]) + if not raw.endswith("/") or str(u["name"]).endswith("/"): + return raw + return f"{raw}{u['name']}" + + +def archive_prefix_extras( + profiles: dict, + relevant: set, + covered_names: set, + seen_dests: set, + extras_prefix: str, + by_name: dict, + taken: dict[str, dict] | None = None, + launches: PlatformLaunches | None = None, +) -> list[dict]: + """A second copy of an archive under the subdirectory a core reads. + + Some cores look for their romset under a directory of their own + (system/fbneo/neogeo.zip) while the platform declares it at the + root. Both paths are carried so the core's own check finds it. + """ + extras: list[dict] = [] + # Archive prefix pass: cores that store BIOS archives in a subdirectory + # (e.g. system/fbneo/neogeo.zip). When the archive is already covered at + # the root, add a copy at the prefixed path so the core's .info firmware + # check finds it. + for emu_name, profile in sorted(profiles.items()): + if not lists_files(profile): + continue + if emu_name not in relevant: + continue + # A platform that hands each core its own system directory moves the + # subfolder with it, once per directory. + views = [profile] + if core_system_dirs(emu_name, profile, launches or PlatformLaunches()) is not None: + views = [ + view for view, standalone + in platform_layouts(emu_name, profile, launches or PlatformLaunches()) + if not standalone + ] + for view in views: + extras.extend(_archive_prefix_copies( + emu_name, view, covered_names, seen_dests, extras_prefix, + by_name, taken, + )) + return extras + + +def _archive_prefix_copies( + emu_name: str, + profile: dict, + covered_names: set, + seen_dests: set, + extras_prefix: str, + by_name: dict, + taken: dict[str, dict] | None, +) -> list[dict]: + """The prefixed copies of one layout's archives.""" + extras: list[dict] = [] + prefix = profile.get("archive_prefix", "") + if not prefix: + return extras + profile_archives: dict[str, dict] = {} + for f in profile.get("files", []): + archive = f.get("archive", "") + if archive: + profile_archives.setdefault(archive, f) + for archive_name, archive_entry in sorted(profile_archives.items()): + if archive_name not in covered_names: + continue + dest = f"{prefix}/{archive_name}" + full_dest = prefixed_destination(dest, extras_prefix) + if full_dest in seen_dests and (taken is None or full_dest not in taken): + continue + if not by_name.get(archive_name): + continue + extra = { + "name": archive_name, + "destination": dest, + "required": True, + "hle_fallback": False, + "source_emulator": profile.get("emulator", emu_name), + "source_profile": emu_name, + # Keyed as the gap report keys an archive: name and path alike. + "source_name": archive_name, + "source_path": system_dir_path(archive_entry, archive_name), + "category": archive_entry.get("category", "bios"), + "source_system": archive_entry.get("system"), + "source_systems": entry_system_ids(archive_entry, profile), + "region": archive_entry.get("region"), + "selection_slot": archive_entry.get("selection_slot"), + } + members = archive_members(archive_name, profile.get("files", [])) + if members: + extra["members"] = members + if archive_entry.get("system_dir"): + extra["system_dir"] = archive_entry["system_dir"] + extra["claim_order"] = (3, 0, emu_name) + if take(extra, full_dest, seen_dests, taken): + extras.append(extra) + + return extras + + +class ExtraPlacement: + """Where a pack puts a core's file, decided once for every reader. + + The builder, and slots.py judging what a destination holds, both read + this: placed apart, slot arbitration compared RetroDECK's bios/ claims + with core claims at the root and never saw them meet. + """ + + def __init__(self, config: dict, base_dest: str, profiles: dict) -> None: + from model.systems import norm_system_id + + self.prefix = detect_extras_prefix(config, base_dest) + self.slug_based, self.sys_to_slug = _detect_slug_structure(config) + self.platform_systems = set(config.get("systems", {}).keys()) + self.native_systems = native_slug_systems(config) + self.flat = bool(config.get("firmware_folder_flat")) + self.save = save_layout(config) + # The roms root and emulator folders the platform's files describe, + # for a file a launcher runs from them (ROCKNIX's roms/pico-8, + # RetroBat's emulators/pico8). + self.outer = {root for root in OUTER_ROOTS if outer_layout(config, root)} + self.config = config + self.norm_map = ( + {norm_system_id(sid): sid for sid in self.platform_systems} + if self.slug_based + else {} + ) + self.profiles = profiles + + def place(self, entry: dict, dest: str) -> tuple[str, str] | None: + """(pack-relative destination, full destination), or None. + + ``entry`` names its profile and may name its own system. A + slug-based platform cannot place a file of a system it has no + folder for. A file the core reads below the frontend's save + directory (``root: save``) keeps its path relative to that + directory and goes below the platform's save folder, which a + platform keeping saves beside the content does not have. + """ + if entry.get("unplaced"): + return None + if entry.get("unprefixed"): + return dest, dest + if entry.get("root") in OUTER_ROOTS: + root = entry["root"] + return (dest, outer_destination(root, dest)) if root in self.outer else None + if entry.get("root") == "save": + placed = self.save_places(entry, dest) + return placed[0] if placed else None + if self.slug_based: + slug = _slug_for( + entry, self.profiles, self.platform_systems, self.norm_map, + self.sys_to_slug, self.native_systems, + ) + if not slug or self.nested(dest): + return None + dest = f"{slug}/{dest}" + return dest, prefixed_destination(dest, self.prefix) + + def places(self, entry: dict, dest: str) -> list[tuple[str, str]]: + """Every (pack-relative, full) destination the pack gives an entry. + + One for most entries. A file read below the save directory of a + platform that hands each system a save folder of its own goes once + below each system that runs the core. + """ + if entry.get("unplaced"): + return [] + if entry.get("root") == "save": + return self.save_places(entry, dest) + placed = self.place(entry, dest) + return [placed] if placed is not None else [] + + def save_places(self, entry: dict, dest: str) -> list[tuple[str, str]]: + """The destinations of a file read below the save directory.""" + if self.save is None: + return [] + names = self.core_names(entry) + sorted_by_core = self.save.sorts(names) + systems = libretro_systems(self.config, names) if self.save.by_system else [""] + placed = [] + for system in systems: + full = save_destination( + dest, entry.get("core_folder"), self.save, system, sorted_by_core + ) + if full: + placed.append((dest, full)) + return placed + + def core_names(self, entry: dict) -> set[str]: + """The names a report entry's core goes by: its profile key and the + upstream names its profile lists.""" + key = entry.get("profile") or entry.get("emulator", "") + profile: dict = self.profiles.get(key) or next( + (pp for pp in self.profiles.values() if pp.get("emulator") == key), {} + ) + return set(profile_names(str(key), profile)) - {""} + + def nested(self, dest: str) -> bool: + """True when the file would sit below a folder the frontend lists flat.""" + return self.slug_based and self.flat and "/" in dest + + def unplaced_reason(self, entry: dict, dest: str) -> str: + """Why ``place`` returned None for this entry.""" + if entry.get("unplaced"): + return str(entry["unplaced"]) + if entry.get("root") in OUTER_ROOTS: + return f"no_{entry['root']}_directory" + if entry.get("root") == "save": + if self.save is None: + return "no_save_directory" + if self.save.by_system and not libretro_systems( + self.config, self.core_names(entry) + ): + return "no_save_system" + return "no_core_folder" + return "below_platform_folder" if self.nested(dest) else "no_platform_slug" + + +def take( + extra: dict, full_dest: str, seen_dests: set[str], taken: dict[str, dict] | None +) -> bool: + """Whether an extra takes its destination. A taken one records the claim.""" + if full_dest in seen_dests: + if taken is not None: + another_claim(taken.get(full_dest), extra) + return False + seen_dests.add(full_dest) + if taken is not None: + taken[full_dest] = extra + return True + + +def another_claim(extra: dict | None, claim: dict) -> None: + """Record a core that reads a destination another core's extra took. + + The pack ships one file per destination, so the first claimant's extra + stands. The others are kept on it so the manifest can name every core + the file serves. A pack built for a target without the first core packs + the next one's copy, and an installer narrowing by core must keep it. + """ + if extra is None or claim.get("source_profile") == extra.get("source_profile"): + return + claims = extra.setdefault("other_claims", []) + claims.append(claim) + claims.sort(key=lambda c: c["claim_order"]) diff --git a/scripts/packs/extraregions.py b/scripts/packs/extraregions.py new file mode 100644 index 000000000..76ce14f4b --- /dev/null +++ b/scripts/packs/extraregions.py @@ -0,0 +1,438 @@ +"""The systems each extra serves, its region groups and its required-only spares.""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import TYPE_CHECKING, TypedDict + +from core.options import reject_unknown +from core.paths import declared_destination +from model.alternatives import required_only_spares +from model.declarations import declared_root +from model.profiles import entry_system_ids +from model.systems import norm_system_id +from packs.extraplace import extra_region_key +from packs.extras import collect_emulator_extras +from resolve.nativemode import platform_mode +from resolve.regions import FILE_GROUP + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def extra_system_ids(extra: dict) -> list[str]: + """Return the narrowest system ownership preserved on a core extra.""" + explicit = extra.get("source_system") + if explicit: + return [str(explicit)] + return [str(value) for value in extra.get("source_systems", []) if value] + +def serving_system_ids(extra: dict) -> list[str]: + """Every system the extra's file serves: its own core's and those of the + other cores whose claim rides on it. One file stands per destination, so + narrowed to any of their systems the file is what that core reads. + """ + ids = list(extra_system_ids(extra)) + for claim in extra.get("other_claims", []): + ids.extend(s for s in extra_system_ids(claim) if s not in ids) + return ids + + +def kept_entries(entries: list[dict], required_only: bool) -> list[dict]: + """The entries a pack keeps: optional ones go under --required-only.""" + if not required_only: + return entries + return [e for e in entries if e.get("required") is not False] + + +def extras_for_systems(extras: list[dict], system_ids: list[str]) -> list[dict]: + """Core extras owned by one of the given systems. + + Extras carry their profile/system identity directly. Display labels are + presentation only and must never drive routing. + """ + wanted = set(system_ids) | {norm_system_id(s) for s in system_ids} + return [ + fe for fe in extras + if ( + set(serving_system_ids(fe)) + | {norm_system_id(s) for s in serving_system_ids(fe)} + ) & wanted + ] + + +def report_owned_by_systems(report: list[dict], system_ids: list[str]) -> list[dict]: + """Gap report entries whose extra a pack built with --system carries. + + The other cores whose claim rides on the entry count, as the builder + counts them: MAME 2009's taitofx1.zip went into a --system + panasonic-3do pack for MAME 2016 and was missing from the report. + """ + def owner(entry: dict) -> dict: + return {"source_system": entry.get("system"), "source_systems": entry.get("systems", [])} + + return [ + u for u in report + if extras_for_systems( + [{**owner(u), "other_claims": [owner(c) for c in u.get("other_claims", [])]}], + system_ids, + ) + ] + + +def _ships( + config: dict, + file_entry: dict, + db: dict, + zip_contents: dict | None, + data_registry: dict | None, + override: str | None, +) -> bool: + """Whether the builder packs this declaration: resolved, and not refused + by a hash frontend. A dump whose md5 Recalbox would reject is left out + of the pack, so it cannot win a regional slot over a file that ships. + + Resolved with the builder's own inputs: without the data directories, + AmberELEC's bluemsx config.ini read as missing while the pack held it. + """ + from resolve.packfiles import resolve_declaration + from resolve.acceptance import baseline_verdict + + path, status = resolve_declaration( + file_entry, db, "bios", zip_contents, data_registry, override, offline=True, + ) + if not path: + return False + return baseline_verdict( + file_entry, path, status, platform_mode(config), + config.get("hash_rule", ""), + )[1] is None + + +class RegionGroupOptions(TypedDict, total=False): + """What platform_region_groups reads besides the platform, and fills.""" + + include_all: bool + required_only: bool + extras_out: list[dict] | None + held_out: set[str] | None + undeclared: list[dict] | None + zip_contents: dict | None + data_registry: dict | None + slot_overrides: dict[str, str] | None + + +def platform_region_groups( + config: dict, + systems: dict, + emulators_dir: str, + db: dict | None, + base_dest: str, + emu_profiles: dict | None, + *, + target_cores: set[str] | None = None, + include_extras: bool = True, + **options: Unpack[RegionGroupOptions], +) -> tuple[dict[str, list[tuple[str, str]]], dict[tuple[str, str, str], str]]: + """Group a platform's pack candidates the way region filtering reads them. + + ``held_out`` receives the destinations whose file the collection holds: + a missing file is grouped so the report can withdraw it, but it never + takes the slot of a held one (resolve_region_drops). + + Returns the groups and, for every core extra, the destination it was + grouped under, keyed by (emulator, name). verify.py needs that mapping to + withdraw from its report exactly what the builder withdraws from the pack: + grouping the declared files here and the core extras there would let the + two answer differently on the same request. `extras_out` receives the + core extras that were grouped, for the install manifest. ``undeclared`` + is the gap report when the caller holds it (undeclared_report, with the + same target_cores and include_all). ``zip_contents``, ``data_registry`` + and ``slot_overrides`` (keyed by full pack destination) are the ones the + builder resolves with, so a held declaration is the one the pack ships. + """ + reject_unknown("platform_region_groups", options, RegionGroupOptions.__optional_keys__) + include_all = options.get("include_all", False) + undeclared = options.get("undeclared") + required_only = options.get("required_only", False) + held_out = options.get("held_out") + extras_out = options.get("extras_out") + zip_contents = options.get("zip_contents") + data_registry = options.get("data_registry") + slot_overrides = options.get("slot_overrides") + groups: dict[str, list[tuple[str, str]]] = {} + for sys_id, system in systems.items(): + members = groups.setdefault(sys_id, []) + # Decided over what the pack keeps: an optional winner removed + # afterwards left its slot empty. + for file_entry in kept_entries(system.get("files", []), required_only): + dest = declared_destination(file_entry) + if dest: + members.append((dest, file_entry.get("name", ""))) + full_dest = f"{base_dest}/{dest}" if base_dest else dest + if held_out is not None and db is not None and _ships( + config, file_entry, db, zip_contents, data_registry, + (slot_overrides or {}).get(full_dest), + ): + held_out.add(dest) + + extra_dests: dict[tuple[str, str, str], str] = {} + if not include_extras or db is None: + return groups, extra_dests + + absent: list[dict] = [] + extras = collect_emulator_extras( + config, + emulators_dir, + db, + set(), + base_dest, + emu_profiles, + target_cores=target_cores, + include_all=include_all, + claimants=extra_dests, + absent=absent, + undeclared=undeclared, + ) + held = {id(extra) for extra in extras} + spellings = system_spellings(systems) + region_prefix = declared_root(config) + for extra in kept_entries(extras + absent, required_only): + dest = extra_region_key(extra, region_prefix) + if not dest: + continue + name = extra.get("name", "") + extra_dests[ + ( + extra.get("source_emulator", ""), + extra.get("source_name", ""), + extra.get("source_path", ""), + ) + ] = dest + # A file a filename-agnostic scan accepts by shape competes only if + # its seed names a region: PCSX2 picks no PS2 BIOS by territory, and + # looked up by name its scph50006 took DuckStation's [japan], which + # describes DuckStation's own PS1-on-PS2 choice. + competes = not extra.get("agnostic_scan") or extra.get("region") + for group_id in extra_region_groups(extra, spellings) if competes else (): + groups.setdefault(group_id, []).append((dest, name)) + if extras_out is not None and id(extra) in held: + extras_out.append(extra) + if held_out is not None and id(extra) in held: + held_out.add(dest) + return groups, extra_dests + + +def system_spellings(systems: Iterable[str]) -> dict[str, str]: + """A platform's own spelling of each system, keyed the way ids compare. + + RetroDECK files the Master System as sega-master-system, the profiles as + sega-mastersystem. Grouped under both, the declared bios/bios_J.sms and + the core's bios_J.sms were reduced apart and a --region us pack kept the + Japanese BIOS. + """ + spellings: dict[str, str] = {} + for sys_id in sorted(systems): + spellings.setdefault(norm_system_id(sys_id), sys_id) + return spellings + + +def _region_basis(extra: dict) -> tuple[str, str]: + """What a core extra's region group is keyed on, in either mode. + + A selection slot, else the one system the file is chosen for, else the + file alone. Platform and emulator mode both read this, so the two + cannot group the same file apart. + """ + variant = extra.get("selection_slot") + if variant: + # A selection slot is one slot of one core, whatever system each + # member is filed under: PicoDrive files its US Mega CD BIOS under + # sega-segacd and the EU/JP ones under sega-megacd, and find_bios + # picks one of the twelve. + return "variant", str(variant) + systems = extra_system_ids(extra) + if len(systems) == 1: + return "system", systems[0] + # No system names the machine this file is chosen for. Filed under every + # system of a 30-system profile, CLK's American MSX ROM made the + # Enterprise group drop its German ROM. Alone, it drops nothing and is + # never dropped. + return "file", str(extra.get("destination", extra.get("name", ""))) + + +def extra_region_groups( + extra: dict, spellings: dict[str, str] | None = None +) -> list[str]: + """The region groups a core extra competes in. + + A group named after a system takes the platform's spelling of it, so the + extra competes beside the files the platform declares for that system. + """ + emulator = extra.get("source_emulator", "") + kind, value = _region_basis(extra) + if kind == "variant": + return [f"{emulator}:variant:{value}"] + if kind == "system": + return [(spellings or {}).get(norm_system_id(value), value)] + return [f"{emulator}{FILE_GROUP}{value}"] + + +def emulator_region_drops( + selected: list[tuple[str, dict]], + standalone: bool, + regions: list[str], + required_only: bool = False, + db: dict | None = None, + zip_contents: dict | None = None, + data_registry: dict | None = None, +) -> set[str]: + """Destinations an emulator-mode `--region` withdraws. + + One group per system (or explicit selection_slot) inside each profile, so + a multi-system core such as O2EM keeps a fallback BIOS for every system + instead of letting one matching system empty another. The emulator pack + and `verify --emulator` both read this, keyed by pack destination. + + With `db`, a requested-region file the collection lacks never displaces + a held one, as in platform mode: a held scph5501.bin was withdrawn for a + Japanese image nobody had collected, and the pack shipped no PlayStation + BIOS at all. ``zip_contents`` and ``data_registry`` are the ones the + emulator pack resolves with. + """ + from resolve import regions as resolve_regions + from packs.paths import resolve_destination + from resolve.validation import build_validation_index + from resolve.entryscope import filter_files_by_mode + + region_index = resolve_regions.build_region_index(dict(selected)) + region_groups: dict[str, list[tuple[str, str]]] = {} + held: set[str] | None = set() if db is not None else None + validation_index = build_validation_index(dict(selected)) if db is not None else {} + for emu_name, profile in sorted(selected): + # Decided over what the pack keeps, as on the platform side: an + # optional winner removed afterwards left its slot empty. + entries = filter_files_by_mode(profile.get("files", []), standalone) + for fe in kept_entries(entries, required_only): + dest = resolve_destination(fe, standalone) + if dest: + group_id = _emulator_region_group(emu_name, profile, fe, dest) + region_groups.setdefault(group_id, []).append( + (dest, fe.get("name", "")) + ) + if held is not None and db is not None and _emulator_ships( + fe, emu_name, profile, db, validation_index, + zip_contents, data_registry, + ): + held.add(dest) + return resolve_regions.resolve_region_drops(region_groups, region_index, regions, held) + + +class SpareOptions(TypedDict, total=False): + data_registry: dict | None + + +def emulator_required_spares( + emu_name: str, + profile: dict, + files: list[dict], + standalone: bool, + region_drops: set[str], + db: dict, + validation_index: dict, + zip_contents: dict | None, + **options: Unpack[SpareOptions], +) -> set[str]: + """The destinations an emulator --required-only pack leaves out: of each + required set, one held member stays, the first the code loads among + those the pack still carries after the region filter. An archive unit + is a member like a loose file: Kronos reads kronos/stvbios.zip, else + stvbios.zip. The pack and verify --emulator both read this.""" + from model.alternatives import groups_of, rank_in, required_groups + from resolve.archives import archive_entry + from packs.paths import archive_destination, resolve_destination + + reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__) + data_registry = options.get("data_registry") + candidates: list[dict] = [] + archives: list[str] = [] + for fe in files: + archive = fe.get("archive") + if archive and archive not in archives: + archives.append(archive) + own = archive_entry(archive, files) + if groups_of(own): + candidates.append({"dest": archive_destination( + archive, profile.get("archive_prefix", ""), + profile.get("pack_structure"), standalone, + ), "entry": own}) + candidates.extend( + {"dest": resolve_destination(fe, standalone), "entry": fe} + for fe in files if not fe.get("archive") and groups_of(fe) + ) + if not candidates: + return set() + spares = required_only_spares( + candidates, + owner=lambda _c: emu_name, + held=lambda c: _emulator_ships( + c["entry"], emu_name, profile, db, validation_index, zip_contents, data_registry, + ), + gone=lambda c: c["dest"] in region_drops, + sets=lambda c: {g: rank_in(c["entry"], g) for g in required_groups(c["entry"], profile)}, + ) + return {c["dest"] for c in candidates if id(c) in spares} + + +def _emulator_ships( + file_entry: dict, emu_name: str, profile: dict, db: dict, + validation_index: dict, zip_contents: dict | None, data_registry: dict | None, +) -> bool: + """Whether the emulator pack ships this entry: held, and not refused by + the core's own check, the test _ships applies on the platform side. + + Resolved as generate_emulator_pack resolves: without the data + directories, dolphin-mmjr2's nwc24msg.cfg read as missing while the pack + held it. + """ + from resolve.packfiles import resolve_file + from resolve.acceptance import validated_choice + from resolve.entryscope import with_archive_members + + local, status = resolve_file( + {**with_archive_members(file_entry, profile.get("files", [])), + "source_profile": emu_name}, + db, "bios", zip_contents, + dest_hint=file_entry.get("path", ""), + data_dir_registry=data_registry, + offline=True, + ) + if status in ("not_found", "user_provided") or not local: + return False + _chosen, disagreement = validated_choice( + file_entry, local, db, validation_index, "bios", None, emulators={emu_name}, + ) + return disagreement is None + + +def _emulator_region_group( + emu_name: str, profile: dict, file_entry: dict, dest: str +) -> str: + """Stable group ID for regional alternatives within an emulator profile. + + Keyed by _region_basis, the rule extra_region_groups applies on the + platform side, over the systems entry_system_ids gives the entry. A + system group carries the emulator, since an emulator pack reduces each + profile on its own. + """ + kind, value = _region_basis({ + "selection_slot": file_entry.get("selection_slot"), + "source_system": file_entry.get("system"), + "source_systems": entry_system_ids(file_entry, profile), + "destination": dest, + }) + if kind == "variant": + return f"{emu_name}:variant:{value}" + if kind == "system": + return f"{emu_name}:system:{value}" + return f"{emu_name}{FILE_GROUP}{dest}" diff --git a/scripts/packs/extraresolver.py b/scripts/packs/extraresolver.py new file mode 100644 index 000000000..83616867c --- /dev/null +++ b/scripts/packs/extraresolver.py @@ -0,0 +1,298 @@ +"""The copy the builder packs for a core extra, and the extras it holds yet leaves out.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, TypedDict + +from core.options import reject_unknown +from core.paths import declared_destination +from model.alternatives import core_file_spares +from model.database import sha1_at +from model.declarations import OUTER_ROOTS, declared_root +from packs.extraplace import ( + ExtraPlacement, + detect_extras_prefix, + extra_dest, + extra_full_destination, + extra_region_key, +) +from packs.extraregions import extras_for_systems +from packs.extras import collect_emulator_extras +from resolve.localfile import resolve_local_file + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def _file_sha1(path: str) -> str | None: + """sha1 of a copy the database does not index, a data tree's file.""" + from core.hashing import compute_hashes + + try: + return compute_hashes(path, frozenset({"sha1"}))["sha1"] + except OSError: + return None + + +class ResolverOptions(TypedDict, total=False): + pending_assets: bool + + +class ExtraResolver: + """How the builder finds the copy of a core's file it packs. + + The builder and verify's replay of its placement must look the file up + the same way: by the storage-aware resolver with the archive index and + the data directories, then through the core's own check. verify once + looked up by name alone and compared other bytes than the pack's + (blueMSX's MSX2P.rom from bios/ against the data tree's copy). + """ + + def __init__( + self, + db: dict, + bios_dir: str, + zip_contents: dict | None, + data_registry: dict | None, + validation_index: dict, + validation_owners: dict | None, + offline: bool | None = True, + *, + profiles: dict, + **options: Unpack[ResolverOptions], + ) -> None: + self.profiles = profiles + self.db = db + self.bios_dir = bios_dir + self.zip_contents = zip_contents + self.data_registry = data_registry + self.validation_index = validation_index + self.validation_owners = validation_owners + self.offline = offline + # verify's replay: never downloads, and counts the release asset an + # online build fetches, as it does for a platform entry. + reject_unknown("ExtraResolver", options, ResolverOptions.__optional_keys__) + self.pending_assets = options.get("pending_assets", False) + # Each profile's entries by slot, built on first use: every extra + # scanned its whole profile, 33 million entries in one verify --all. + self._slots: dict[str, dict[tuple[str, str], list[dict]]] = {} + + def alternatives(self, fe: dict) -> list[dict]: + """The versions the extra's own profile accepts at its slot, as + acceptance.extra_alternatives finds them.""" + from resolve.acceptance import slot_index + + key = fe.get("source_profile") or "" + index = self._slots.get(key) + if index is None: + profile = (self.profiles or {}).get(key, {}) + index = self._slots[key] = slot_index(profile.get("files") or []) + name = fe.get("source_name") or fe.get("name", "") + return index.get((name, fe.get("source_path") or name), []) + + def resolve(self, fe: dict, dest: str) -> tuple[str | None, str, str]: + """(local copy or None, resolver status, the core's disagreement).""" + from resolve.packfiles import release_asset_paths, resolve_file, run_is_offline + from resolve.acceptance import core_size_refusal, validated_choice + + local_path, status = resolve_file( + fe, self.db, self.bios_dir, self.zip_contents, + dest_hint=fe.get("destination", ""), + data_dir_registry=self.data_registry, offline=self.offline, + ) + if ( + self.pending_assets and status in ("not_found", "hash_mismatch") + and not run_is_offline() + ): + # The asset the online builder fetches in resolve_file. Its record + # answers the declaration, and there are no bytes on disk to check. + assets = release_asset_paths(fe, self.db) + if assets: + return assets[0], "release_asset", "" + if status in ("not_found", "external", "user_provided") or not local_path: + return None, status, "" + # The cores reading a moved layout's file are found under the + # emulator's own path, not the folder the platform put it in. + local_path, disagreement = validated_choice( + fe, local_path, self.db, self.validation_index, self.bios_dir, None, + fe.get("layout_path") or dest, self.validation_owners, + ) + # The platform never reads the bytes, the core does: a copy it turns + # away by its own size check is not its file, on any platform. + if core_size_refusal(fe, local_path, self.alternatives(fe)): + return None, "not_found", "" + return local_path, status, disagreement + + +class HiddenOptions(TypedDict, total=False): + """How hidden_extras replays the builder, and what else it fills.""" + + report: list[dict] | None + resolver: ExtraResolver | None + placed_kind: dict[str, str] | None + placed_local: dict[str, str] | None + system_ids: list[str] | None + include_all: bool + required_only: bool + + +def hidden_extras( + config: dict, + emulators_dir: str, + db: dict, + profiles: dict, + shipped: dict[str, str | None], + target_cores: set[str] | None = None, + region_drops: set[str] | None = None, + placed: set[str] | None = None, + **options: Unpack[HiddenOptions], +) -> dict[tuple[str, str, str], str]: + """Report entries the builder holds and still leaves out, with the reason. + + A destination the region pass withdraws never takes its path in the + pack, so it blocks nothing here either. + + The builder walks the core extras after the platform's own files and + skips a destination that a case-insensitive filesystem folds onto one + already packed, or that a packed file blocks as a directory. RetroPie's + openmsx fmpac.rom gave way to the platform's FMPAC.ROM, other bytes, + while the report counted it in the pack. A twin carrying the same bytes + serves the core on the filesystem that folds the names, so it is not a + file left out. ``shipped`` maps the full destination of each platform + file the pack carries to its local copy, or to None for a slot it keeps + without one (user_provided, external). ``placed``, when given, + receives the full destination of each held extra the pack carries, and + ``placed_kind`` its category, carried by the extra itself: the second + pass, the archive-prefix pass and the agnostic scan copy files no gap + report entry names. ``placed_local`` receives the local copy the builder + writes at each of those destinations, for the pack integrity check. + ``system_ids`` replays a pack built with --system: the extras collected + without the platform's paths, then those the systems own. + ``resolver`` is the builder's lookup. An extra it cannot resolve is + skipped and takes no path, as the builder skips it. ``include_all`` and + ``required_only`` are the builder's for a --source truth or a + --required-only pack: an optional extra is skipped before it takes a path. + """ + from packs.archive import Placed + + reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__) + report = options.get("report") + resolver = options.get("resolver") + placed_kind = options.get("placed_kind") + placed_local = options.get("placed_local") + system_ids = options.get("system_ids") + include_all = options.get("include_all", False) + required_only = options.get("required_only", False) + base_dest = config.get("base_destination", "") + taken = Placed(bool(config.get("case_insensitive_fs", False)), content={}) + for dest, local in shipped.items(): + taken.take(dest, sha1_at(db, local)) + prefix = detect_extras_prefix(config, base_dest) + region_prefix = declared_root(config) + hidden: dict[tuple[str, str, str], str] = {} + packed_keys: set[tuple[str, str, str]] = set() + extras = collect_emulator_extras( + config, emulators_dir, db, set() if system_ids else set(shipped), + base_dest, profiles, target_cores=target_cores, include_all=include_all, + undeclared=report, + ) + if system_ids: + extras = extras_for_systems(extras, system_ids) + spares = core_file_spares( + extras, + lambda fe: extra_region_key(fe, region_prefix) in (region_drops or set()), + ) if required_only else set() + for fe in extras: + if required_only and (fe.get("required") is False or id(fe) in spares): + continue + dest = _packable_dest(fe, region_drops, region_prefix) + if not dest: + continue + full = extra_full_destination(fe, prefix) + if not full: + continue + reason = taken.block(full) + if reason == "taken": + # Another core's claim on the same path, settled by the claims + # the collector records: not a file left out. + continue + if resolver is not None: + local, _status, _disagreement = resolver.resolve(fe, dest) + if not local: + continue + else: + local, _status = resolve_local_file( + fe, db, dest_hint=fe.get("destination", "") + ) + held = (sha1_at(db, local) or _file_sha1(local)) if local else None + if reason == "case_twin" and held and taken.content_at(full) == held: + continue + key = ( + fe.get("source_emulator", ""), fe.get("source_name", ""), + fe.get("source_path", ""), + ) + if reason is not None: + hidden.setdefault(key, reason) + continue + packed_keys.add(key) + taken.take(full, held) + if local: + _record_placed(full, local, fe, placed, placed_kind, placed_local) + # A file read below a save directory kept per system is packed once per + # system: one copy left out does not leave the file out. + return {key: reason for key, reason in hidden.items() if key not in packed_keys} + + +def _packable_dest(fe: dict, region_drops: set[str] | None, region_prefix: str) -> str: + """The extra's destination, empty when the builder never places it.""" + dest = declared_destination(fe) + if not dest or (region_drops and extra_region_key(fe, region_prefix) in region_drops): + return "" + if fe.get("root") in OUTER_ROOTS: + # As the builder does: the pack is extracted into the BIOS folder + # and cannot reach the roms, emulator or configs folder, the + # installer places these files. + return "" + return dest + + +def _record_placed( + full: str, + local: str, + fe: dict, + placed: set[str] | None, + placed_kind: dict[str, str] | None, + placed_local: dict[str, str] | None, +) -> None: + """Note a held extra the pack carries in each record the caller asked for.""" + if placed is not None: + placed.add(full) + if placed_kind is not None: + placed_kind[full] = fe.get("category", "bios") + if placed_local is not None: + placed_local[full] = local + + +def unplaceable_extras( + config: dict, undeclared: list[dict], profiles: dict +) -> dict[tuple[str, str, str], str]: + """The report entries a slug-based platform cannot place, with the reason. + + RomM files every BIOS under the slug of its system and knows no slug + for DOS or for the arcade sets MAME 2003 reads, and it lists each folder + flat. The builder skipped those entries and the report counted them in + the pack. The answer comes from the builder's own placement. + """ + placement = ExtraPlacement(config, "", profiles) + unplaced: dict[tuple[str, str, str], str] = {} + for u in undeclared: + if not u.get("in_repo") and not u.get("unplaced"): + continue + if (not placement.slug_based and u.get("root") not in ("save", *OUTER_ROOTS) + and not u.get("unplaced")): + continue + dest = extra_dest(u) + if not placement.places(u, dest): + key = (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") + unplaced[key] = placement.unplaced_reason(u, dest) + return unplaced diff --git a/scripts/packs/extras.py b/scripts/packs/extras.py index ac5ec6d19..d4175bee9 100644 --- a/scripts/packs/extras.py +++ b/scripts/packs/extras.py @@ -6,1376 +6,36 @@ this module builds so the report and the pack withdraw the same files.""" from __future__ import annotations -from collections.abc import Iterable from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict from core.options import reject_unknown -from model.database import sha1_at from model.profiles import PROFILE_IDENTITY_FIELDS, entry_system_ids, lists_files -from model.systems import norm_system_id -from model.alternatives import core_file_spares, required_only_spares, set_fields -from resolve.archives import archive_members, contents_members, holds_required_members +from model.alternatives import set_fields +from resolve.archives import contents_members, holds_required_members from model.declarations import declared_root, expand_platform_declared_names, platform_declarations -from model.profiles import core_key, core_key_index, load_emulator_profiles, profile_names +from model.profiles import core_key, core_key_index, load_emulator_profiles from resolve.localfile import resolution_is_hash_exact from resolve.localfile import resolve_local_file -from resolve.nativemode import platform_mode from resolve.cores import resolve_platform_cores -from resolve.launches import PlatformLaunches -from resolve.layout import core_system_dirs, system_dir_path from resolve.standalone import platform_layouts from resolve.standalone import platform_launches -from model.declarations import OUTER_ROOTS, outer_layout -from core.paths import declared_destination, sanitize_pack_path -from resolve.content import declares_shape, shape_fits, size_fits -from resolve.entryscope import deliverable, read_by_build, read_from_save_dir, read_from_system_dir +from model.declarations import OUTER_ROOTS +from core.paths import sanitize_pack_path +from resolve.entryscope import deliverable, read_by_build, read_from_system_dir from packs.gaps import gap_destination -from packs.paths import libretro_systems, save_destination, save_layout -from resolve.regions import FILE_GROUP if TYPE_CHECKING: from typing_extensions import Unpack - - -def detect_extras_prefix(config: dict, base_dest: str) -> str: - """The prefix core-extra destinations take (may be empty). - - When base_destination is empty (RetroDECK), it is the dominant root of - the YAML-declared destinations. - """ - return base_dest or declared_root(config) - - -def extra_full_destination(fe: dict, prefix: str) -> str: - """Where a pack writes a core extra, from the pack root. - - A file the core reads below the frontend's save directory goes to the - pack path its placement recorded (ExtraPlacement.place). Any other one - goes below the platform's prefix, unless its destination carries it. - The builder, the manifest and verify's replay all read this. - """ - if fe.get("root") == "save": - return str(fe.get("pack_path") or "") - if fe.get("unprefixed"): - # A path of the install tree outside the BIOS folder (AmberELEC's - # pico-8/ beside bios/): no platform prefix in front. - return declared_destination(fe) - if fe.get("root") in OUTER_ROOTS: - return outer_destination( - fe["root"], declared_destination(fe) - ) - return prefixed_destination( - declared_destination(fe), prefix - ) - - -def outer_destination(root: str, dest: str) -> str: - """The key of a destination below the roms or an emulator folder. - - Kept apart from the BIOS tree's paths and never written into a pack: - the pack is extracted into the BIOS folder, and the installer places - these files (``root: roms``, ``root: emulators``). - """ - return f"{root}:{dest}" - - -def prefixed_destination(dest: str, prefix: str) -> str: - """A core extra's destination from the pack root. - - The one rule the collector, the builder and the manifest place a file - by. DuckStation's standalone `bios/` on Recalbox lands in the - `bios` folder itself: deduplicated at `bios/bios/` but written at - `bios/`, it let PCSX2's scan claim the same path under another - key, and `--region` withdrew one claim while the other kept the file. - """ - if not dest or not prefix or dest.startswith(f"{prefix}/"): - return dest - return f"{prefix}/{dest}" - - -def extra_region_key(fe: dict, prefix: str) -> str: - """The key a core extra is grouped, dropped and held under by --region. - - Its destination with the BIOS directory the platform writes in front of - its own (declared_root): RetroDECK declares bios/scph5501.bin, and - Beetle PSX's scph5501.bin grouped bare was looked up under another key, - kept by the pack while the declaration of the same file was dropped, - and the installer, which records the path once, dropped it. - """ - return prefixed_destination( - declared_destination(fe), prefix - ) - - -def save_entry_fields(fe: dict) -> dict: - """What a manifest entry adds for a file read below the save directory. - - ``root: save`` puts its ``dest`` below the frontend's save directory, - laid out as the pack lays it out. ``core_folder`` is the core's - library_name when the platform's frontend inserts it as the first folder - of ``dest`` (RetroArch's sort_savefiles_enable): the installer drops it - where the frontend's own config turns sorting off. - """ - fields = {"root": "save"} - if fe.get("core_folder"): - fields["core_folder"] = str(fe["core_folder"]) - return fields - - -def save_manifest_dest(fe: dict) -> str: - """A manifest dest for a file read below the save directory. - - The pack path below the platform's save folder when the file is placed - (``save_dest``), the system's folder first where the launcher keeps one - per system, the core's own folder first where the frontend sorts saves - by core. - Without a save folder (an omission), the same shape: the core's folder, - then the path the core reads, so two cores reading one name below their - own folders stay two entries. - """ - if fe.get("save_dest"): - return str(fe["save_dest"]) - rel = sanitize_pack_path(fe.get("destination") or fe.get("path") or fe.get("name", "")) - folder = fe.get("core_folder") - return f"{folder}/{rel}" if folder else rel - - -def _detect_slug_structure(config: dict) -> tuple[bool, dict[str, str]]: - """Detect whether a platform uses per-system slug destinations. - - Returns ``(is_slug_based, system_to_slug)`` where ``system_to_slug`` - maps system IDs to their destination slug prefix. Slug-based means - each system's files live under a per-system subfolder (e.g. RomM's - ``bios/{platform_slug}/{file}``), with varying slugs across systems. - - Only returns True when nearly ALL destinations have a subfolder and - nearly ALL systems map to a consistent slug, distinguishing true - slug-based layouts (RomM) from platforms that happen to have some - subfoldered files (RetroArch ``dc/``, ``neocd/``). - """ - total_files = 0 - files_with_slash = 0 - sys_to_slug: dict[str, str] = {} - total_systems_with_files = 0 - for sys_id, sys_data in config.get("systems", {}).items(): - files = sys_data.get("files", []) - if not files: - continue - total_systems_with_files += 1 - slugs: set[str] = set() - for f in files: - d = f.get("destination", "") - if d: - total_files += 1 - if "/" in d: - files_with_slash += 1 - slugs.add(d.split("/", 1)[0]) - if len(slugs) == 1: - sys_to_slug[sys_id] = slugs.pop() - - if not sys_to_slug or total_files == 0: - return False, {} - # All conditions must hold for slug-based detection: - # 1. Nearly all files have a subfolder - # 2. Multiple distinct slugs (not a constant prefix) - # 3. Nearly all systems with files map to a slug - # 4. Files are exactly slug/filename (depth 2), not deeper - unique_slugs = set(sys_to_slug.values()) - all_have_slash = files_with_slash / total_files > 0.95 - varying_slugs = len(unique_slugs) > 1 - high_coverage = len(sys_to_slug) / total_systems_with_files > 0.9 - # Count files deeper than slug/filename (e.g., amiga/bios/kick.rom) - deep_files = 0 - for sys_data in config.get("systems", {}).values(): - for f in sys_data.get("files", []): - d = f.get("destination", "") - if d and d.count("/") > 1: - deep_files += 1 - shallow = deep_files / total_files < 0.05 if total_files else True - return (all_have_slash and varying_slugs and high_coverage and shallow), sys_to_slug - -def _map_emulator_to_slug( - profile: dict, - platform_systems: set[str], - norm_map: dict[str, str], - sys_to_slug: dict[str, str], -) -> str: - """Map an emulator to a destination slug for slug-based platforms.""" - from model.systems import norm_system_id - - emu_systems = set(profile.get("systems", [])) - # Direct match - direct = emu_systems & platform_systems - if direct: - target = sorted(direct)[0] - return sys_to_slug.get(target, "") - # Normalized match - for es in sorted(emu_systems): - norm = norm_system_id(es) - if norm in norm_map: - target = norm_map[norm] - return sys_to_slug.get(target, "") - return "" - -def _slug_for( - u: dict, profiles: dict, platform_systems: set, norm_map: dict, sys_to_slug: dict, - native_systems: set | None = None, -) -> str: - """The platform slug a report entry files under, or empty. - - The entry's own system decides, and alone: picodrive's Mega CD BIOS - belongs under segacd/, where RomM looks for a Mega CD game's firmware, - and a file of a system the platform lacks has no folder there (MAME - 2003's ZN-1 BIOS once fell back on its Neo Geo systems). A file of no - system takes the emulator's first system the platform declares for - itself: a folder present only as a mirror of another slug's firmware - (RomM's neogeoaes/) says nothing about the emulators that read it. - """ - own = u.get("system") - if own: - return _map_emulator_to_slug( - {"systems": [own]}, platform_systems, norm_map, sys_to_slug - ) - emu_name = u.get("profile") or u.get("emulator", "") - # The report carries the entry's own systems: (a MAME device set) or - # its profile's, the same list either way when the entry names none. - profile = {"systems": u["systems"]} if u.get("systems") else profiles.get(emu_name, {}) - if not profile: - # The report names the display name where the key failed. - profile = next( - (pp for pp in profiles.values() if pp.get("emulator") == emu_name), {} - ) - systems = platform_systems if native_systems is None else native_systems - native_norm = {k: v for k, v in norm_map.items() if v in systems} - return _map_emulator_to_slug(profile, systems, native_norm, sys_to_slug) - - -def native_slug_systems(config: dict) -> set[str]: - """Systems the platform declares at least one file of its own for.""" - return { - sid for sid, data in (config.get("systems") or {}).items() - if any(not f.get("mirror_of") for f in data.get("files", [])) - } - - -def _file_sha1(path: str) -> str | None: - """sha1 of a copy the database does not index, a data tree's file.""" - from core.hashing import compute_hashes - - try: - return compute_hashes(path, frozenset({"sha1"}))["sha1"] - except OSError: - return None - - -class ResolverOptions(TypedDict, total=False): - pending_assets: bool - - -class ExtraResolver: - """How the builder finds the copy of a core's file it packs. - - The builder and verify's replay of its placement must look the file up - the same way: by the storage-aware resolver with the archive index and - the data directories, then through the core's own check. verify once - looked up by name alone and compared other bytes than the pack's - (blueMSX's MSX2P.rom from bios/ against the data tree's copy). - """ - - def __init__( - self, - db: dict, - bios_dir: str, - zip_contents: dict | None, - data_registry: dict | None, - validation_index: dict, - validation_owners: dict | None, - offline: bool | None = True, - *, - profiles: dict, - **options: Unpack[ResolverOptions], - ) -> None: - self.profiles = profiles - self.db = db - self.bios_dir = bios_dir - self.zip_contents = zip_contents - self.data_registry = data_registry - self.validation_index = validation_index - self.validation_owners = validation_owners - self.offline = offline - # verify's replay: never downloads, and counts the release asset an - # online build fetches, as it does for a platform entry. - reject_unknown("ExtraResolver", options, ResolverOptions.__optional_keys__) - self.pending_assets = options.get("pending_assets", False) - # Each profile's entries by slot, built on first use: every extra - # scanned its whole profile, 33 million entries in one verify --all. - self._slots: dict[str, dict[tuple[str, str], list[dict]]] = {} - - def alternatives(self, fe: dict) -> list[dict]: - """The versions the extra's own profile accepts at its slot, as - validation.extra_alternatives finds them.""" - from resolve.acceptance import slot_index - - key = fe.get("source_profile") or "" - index = self._slots.get(key) - if index is None: - profile = (self.profiles or {}).get(key, {}) - index = self._slots[key] = slot_index(profile.get("files") or []) - name = fe.get("source_name") or fe.get("name", "") - return index.get((name, fe.get("source_path") or name), []) - - def resolve(self, fe: dict, dest: str) -> tuple[str | None, str, str]: - """(local copy or None, resolver status, the core's disagreement).""" - from resolve.packfiles import release_asset_paths, resolve_file, run_is_offline - from resolve.acceptance import core_size_refusal, validated_choice - - local_path, status = resolve_file( - fe, self.db, self.bios_dir, self.zip_contents, - dest_hint=fe.get("destination", ""), - data_dir_registry=self.data_registry, offline=self.offline, - ) - if ( - self.pending_assets and status in ("not_found", "hash_mismatch") - and not run_is_offline() - ): - # The asset the online builder fetches in resolve_file. Its record - # answers the declaration, and there are no bytes on disk to check. - assets = release_asset_paths(fe, self.db) - if assets: - return assets[0], "release_asset", "" - if status in ("not_found", "external", "user_provided") or not local_path: - return None, status, "" - # The cores reading a moved layout's file are found under the - # emulator's own path, not the folder the platform put it in. - local_path, disagreement = validated_choice( - fe, local_path, self.db, self.validation_index, self.bios_dir, None, - fe.get("layout_path") or dest, self.validation_owners, - ) - # The platform never reads the bytes, the core does: a copy it turns - # away by its own size check is not its file, on any platform. - if core_size_refusal(fe, local_path, self.alternatives(fe)): - return None, "not_found", "" - return local_path, status, disagreement - - -class HiddenOptions(TypedDict, total=False): - """How hidden_extras replays the builder, and what else it fills.""" - - report: list[dict] | None - resolver: ExtraResolver | None - placed_kind: dict[str, str] | None - placed_local: dict[str, str] | None - system_ids: list[str] | None - include_all: bool - required_only: bool - - -def hidden_extras( - config: dict, - emulators_dir: str, - db: dict, - profiles: dict, - shipped: dict[str, str | None], - target_cores: set[str] | None = None, - region_drops: set[str] | None = None, - placed: set[str] | None = None, - **options: Unpack[HiddenOptions], -) -> dict[tuple[str, str, str], str]: - """Report entries the builder holds and still leaves out, with the reason. - - A destination the region pass withdraws never takes its path in the - pack, so it blocks nothing here either. - - The builder walks the core extras after the platform's own files and - skips a destination that a case-insensitive filesystem folds onto one - already packed, or that a packed file blocks as a directory. RetroPie's - openmsx fmpac.rom gave way to the platform's FMPAC.ROM, other bytes, - while the report counted it in the pack. A twin carrying the same bytes - serves the core on the filesystem that folds the names, so it is not a - file left out. ``shipped`` maps the full destination of each platform - file the pack carries to its local copy, or to None for a slot it keeps - without one (user_provided, external). ``placed``, when given, - receives the full destination of each held extra the pack carries, and - ``placed_kind`` its category, carried by the extra itself: the second - pass, the archive-prefix pass and the agnostic scan copy files no gap - report entry names. ``placed_local`` receives the local copy the builder - writes at each of those destinations, for the pack integrity check. - ``system_ids`` replays a pack built with --system: the extras collected - without the platform's paths, then those the systems own. - ``resolver`` is the builder's lookup. An extra it cannot resolve is - skipped and takes no path, as the builder skips it. ``include_all`` and - ``required_only`` are the builder's for a --source truth or a - --required-only pack: an optional extra is skipped before it takes a path. - """ - from packs.archive import Placed - - reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__) - report = options.get("report") - resolver = options.get("resolver") - placed_kind = options.get("placed_kind") - placed_local = options.get("placed_local") - system_ids = options.get("system_ids") - include_all = options.get("include_all", False) - required_only = options.get("required_only", False) - base_dest = config.get("base_destination", "") - taken = Placed(bool(config.get("case_insensitive_fs", False)), content={}) - for dest, local in shipped.items(): - taken.take(dest, sha1_at(db, local)) - prefix = detect_extras_prefix(config, base_dest) - region_prefix = declared_root(config) - hidden: dict[tuple[str, str, str], str] = {} - packed_keys: set[tuple[str, str, str]] = set() - extras = collect_emulator_extras( - config, emulators_dir, db, set() if system_ids else set(shipped), - base_dest, profiles, target_cores=target_cores, include_all=include_all, - undeclared=report, - ) - if system_ids: - extras = extras_for_systems(extras, system_ids) - spares = core_file_spares( - extras, - lambda fe: extra_region_key(fe, region_prefix) in (region_drops or set()), - ) if required_only else set() - for fe in extras: - if required_only and (fe.get("required") is False or id(fe) in spares): - continue - dest = _packable_dest(fe, region_drops, region_prefix) - if not dest: - continue - full = extra_full_destination(fe, prefix) - if not full: - continue - reason = taken.block(full) - if reason == "taken": - # Another core's claim on the same path, settled by the claims - # the collector records: not a file left out. - continue - if resolver is not None: - local, _status, _disagreement = resolver.resolve(fe, dest) - if not local: - continue - else: - local, _status = resolve_local_file( - fe, db, dest_hint=fe.get("destination", "") - ) - held = (sha1_at(db, local) or _file_sha1(local)) if local else None - if reason == "case_twin" and held and taken.content_at(full) == held: - continue - key = ( - fe.get("source_emulator", ""), fe.get("source_name", ""), - fe.get("source_path", ""), - ) - if reason is not None: - hidden.setdefault(key, reason) - continue - packed_keys.add(key) - taken.take(full, held) - if local: - _record_placed(full, local, fe, placed, placed_kind, placed_local) - # A file read below a save directory kept per system is packed once per - # system: one copy left out does not leave the file out. - return {key: reason for key, reason in hidden.items() if key not in packed_keys} - - -def _packable_dest(fe: dict, region_drops: set[str] | None, region_prefix: str) -> str: - """The extra's destination, empty when the builder never places it.""" - dest = declared_destination(fe) - if not dest or (region_drops and extra_region_key(fe, region_prefix) in region_drops): - return "" - if fe.get("root") in OUTER_ROOTS: - # As the builder does: the pack is extracted into the BIOS folder - # and cannot reach the roms, emulator or configs folder, the - # installer places these files. - return "" - return dest - - -def _record_placed( - full: str, - local: str, - fe: dict, - placed: set[str] | None, - placed_kind: dict[str, str] | None, - placed_local: dict[str, str] | None, -) -> None: - """Note a held extra the pack carries in each record the caller asked for.""" - if placed is not None: - placed.add(full) - if placed_kind is not None: - placed_kind[full] = fe.get("category", "bios") - if placed_local is not None: - placed_local[full] = local - - -def extra_dest(u: dict) -> str: - """Where a report entry lands before any platform prefix. - - An archive entry goes by the archive's name, and a directory path takes - the file's name after it ("cafeLibs/" + "snd_user.rpl"). A directory - entry ("registered/") is that path itself. - """ - archive = u.get("archive") - # An archive goes at the root of the core's system directory, which a - # platform handing each core its own folder writes in the path. - raw = (u.get("path") or archive) if archive else (u.get("path") or u["name"]) - if not raw.endswith("/") or str(u["name"]).endswith("/"): - return raw - return f"{raw}{u['name']}" - - -def unplaceable_extras( - config: dict, undeclared: list[dict], profiles: dict -) -> dict[tuple[str, str, str], str]: - """The report entries a slug-based platform cannot place, with the reason. - - RomM files every BIOS under the slug of its system and knows no slug - for DOS or for the arcade sets MAME 2003 reads, and it lists each folder - flat. The builder skipped those entries and the report counted them in - the pack. The answer comes from the builder's own placement. - """ - placement = ExtraPlacement(config, "", profiles) - unplaced: dict[tuple[str, str, str], str] = {} - for u in undeclared: - if not u.get("in_repo") and not u.get("unplaced"): - continue - if (not placement.slug_based and u.get("root") not in ("save", *OUTER_ROOTS) - and not u.get("unplaced")): - continue - dest = extra_dest(u) - if not placement.places(u, dest): - key = (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") - unplaced[key] = placement.unplaced_reason(u, dest) - return unplaced - - -@dataclass(frozen=True) -class _ScanContext: - """What every seed of one agnostic scan reads and fills.""" - - db: dict - files_db: dict - by_name: dict - seen_dests: set - extras_prefix: str - taken: dict[str, dict] | None - profiles: dict - - -@dataclass(frozen=True) -class _ResolvedDirs: - """Where a profile's own files resolve, the evidence a scan anchors on.""" - - dirs: dict[int, str] - named_only: set[int] - votes: dict[str, int] - - -@dataclass(frozen=True) -class _ScanSeed: - """One agnostic entry of one layout and the folder its scan walks.""" - - emu_name: str - layout: dict - entry: dict - name: str - companion_ext: str - image: dict | None - path_prefix: str - exact_dirs: frozenset[str] - folder: str - - -def agnostic_scan_extras( - profiles: dict, - relevant: set, - db: dict, - by_name: dict, - seen_dests: set, - extras_prefix: str, - launches: PlatformLaunches | None = None, - taken: dict[str, dict] | None = None, -) -> list[dict]: - """Every interchangeable candidate a filename-agnostic core accepts. - - Such a core reads whatever sits in its BIOS directory, so the pack - carries every dump of the right shape rather than one chosen name. - The directory is the delicate part: anchoring it on a single - filename walked into another emulator's tree, so the profile's own - files have to agree before the scan follows an ambiguous name. - """ - extras: list[dict] = [] - context = _ScanContext( - db, db.get("files", {}), by_name, seen_dests, extras_prefix, taken, profiles, - ) - # Third pass: the agnostic scan. For filename-agnostic cores, include all - # DB files matching the system path prefix and size criteria. - for emu_name, profile in sorted(profiles.items()): - if not lists_files(profile): - continue - if emu_name not in relevant: - continue - is_profile_agnostic = profile.get("bios_mode") == "agnostic" - if not is_profile_agnostic and not any( - f.get("agnostic") for f in profile.get("files", []) - ): - continue - resolved = _resolved_dirs(emu_name, profile, db) - for layout, standalone in platform_layouts(emu_name, profile, launches or PlatformLaunches()): - # A layout copies each entry in order (a launcher's folder, a - # system directory): its files are looked up as the profile's - # own, or a bound layout scans nothing (KNULLI's bios/ps2). - origin = { - id(view): entry - for view, entry in zip(layout.get("files", []), profile.get("files", [])) - } - for f in layout.get("files", []): - if not is_profile_agnostic and not f.get("agnostic"): - continue - seed = _scan_seed(context, emu_name, layout, f, standalone, origin, resolved) - if seed is not None: - extras.extend(_seed_extras(context, seed)) - return extras - - -def _resolved_dirs(emu_name: str, profile: dict, db: dict) -> _ResolvedDirs: - """Where each of this profile's files resolves. - - A scan anchored on one filename walks into whatever tree that name - happens to hit: rom1.bin is a PS2 ROM and a Roland SC-55 ROM, - GameIndex.yaml belongs to four PS2 profiles and to an Android package. - One match is not evidence of a directory, two files of the same profile - agreeing is. - """ - resolved_dirs: dict[int, str] = {} - named_only: set[int] = set() - agnostic_votes: dict[str, int] = {} - for candidate in profile.get("files", []): - if not isinstance(candidate, dict): - continue - local, status = resolve_local_file( - {**candidate, "source_profile": emu_name}, - db, - dest_hint=candidate.get("path", ""), - ) - if not local or "/" not in local: - continue - directory = local.rsplit("/", 1)[0] - if directory.endswith("/.variants"): - directory = directory[: -len("/.variants")] - resolved_dirs[id(candidate)] = directory + "/" - if not (resolution_is_hash_exact(status) or status == "path_exact"): - named_only.add(id(candidate)) - agnostic_votes[directory + "/"] = ( - agnostic_votes.get(directory + "/", 0) + 1 - ) - return _ResolvedDirs(resolved_dirs, named_only, agnostic_votes) - - -def _seeds_a_scan(f: dict, layout: dict, standalone: bool) -> bool: - """Whether an agnostic entry may seed a scan of the BIOS directory.""" - # A file of the build the platform does not run seeds nothing: - # armsx2's proverb.zip is fetched by the Android app into its own - # arcade/ folder, and the libretro packs carried it at system/. - if not read_by_build(f, standalone): - return False - # The scan walks the BIOS tree: a file read below the save - # directory is placed by the gap report's pass. - if (read_from_save_dir(f, standalone) or f.get("unplaced") - or f.get("root") in OUTER_ROOTS or f.get("unprefixed")): - return False - # An agnostic BIOS mode says the BIOS filename is free, not that - # every file the emulator loads is. A free filename still has a - # known shape, and that shape is what identifies a candidate: an - # entry declaring no size takes the whole directory, which is how - # the flag icons of an Android package walked into a PS2 pack. - if f.get("category", "bios") != "bios": - return False - if not declares_shape(f): - return False - # The free name is the BIOS directory's: a shader, a sound or a - # font the emulator reads from its resources tree has a fixed - # name and must not seed a scan (yaps2 flattened 189 of them to - # the root of the RetroArch pack). - bios_dir = layout.get("bios_directory") - fpath = f.get("path") or "" - return not (bios_dir and "/" in fpath and not fpath.startswith(bios_dir)) - - -def _scan_seed( - context: _ScanContext, - emu_name: str, - layout: dict, - f: dict, - standalone: bool, - origin: dict[int, dict], - resolved: _ResolvedDirs, -) -> _ScanSeed | None: - """The scan an agnostic entry seeds, None when it seeds none.""" - fname = f.get("name", "") - if not fname or not _seeds_a_scan(f, layout, standalone): - return None - - # A companion is read under its image's name with the - # extension the code appends, in that case: only a file of - # that extension is one, spelled as the code spells it. Its - # size identifies nothing, PCSX2 reads min(size, filesize) - # (BiosTools.cpp:234), and a 4 MB bound swept every smaller - # file of the folder to the BIOS root. It sits beside its - # image, so the scan looks where the image resolves: the - # held ps2-0230a-20080220.rom1 is a DVD firmware dump filed - # under DVD Firmware/. - companion_ext, image = _companion_of(layout, fname) - - path_prefix = ( - resolved.dirs.get(id(origin.get(id(image), image)), "") if image - else resolved.dirs.get(id(origin.get(id(f), f)), "") - ) - # A placeholder (.bin) resolves to nothing and anchors no - # directory. The folders where the system's other profiles - # resolve hashed files of that shape do, those folders only: - # LRPS2 and PCEE2 are made of placeholders, and on Batocera, - # where no other libretro PS2 core anchors pcsx2/bios/, the - # pack held nothing there. A companion (.nvm) looks - # where its image is proven: RetroBat's pcsx2/bios/ had - # scph39001.bin and its .nvm only at the BIOS root. - exact_dirs: frozenset[str] = frozenset() - anchor = image if image else f - if not path_prefix and "<" in str(anchor.get("name", "")): - exact_dirs = placeholder_directories( - anchor, emu_name, layout, context.db, context.profiles - ) - if not path_prefix and not exact_dirs: - return None - # A name matching one file identifies it. A name matching several - # identifies nothing on its own, so the profile's other files have - # to agree on the directory before the scan walks it. - ambiguous = ( - id(origin.get(id(f), f)) in resolved.named_only - and len(context.by_name.get(fname, [])) > 1 - ) - if ambiguous and resolved.votes.get(path_prefix, 0) < 2: - return None - - # Into the directory the seed entry names, not the root: - # yaps2 reads its BIOS from pcsx2/bios/. - seed = f.get("path") or "" - if standalone: - seed = f.get("standalone_path") or seed - else: - seed = system_dir_path(f, seed or fname) - folder = seed.rsplit("/", 1)[0] if "/" in seed else "" - return _ScanSeed( - emu_name, layout, f, fname, companion_ext, image, path_prefix, exact_dirs, folder, - ) - - -def _scanned_name(context: _ScanContext, seed: _ScanSeed, entry: dict) -> tuple[str, str] | None: - """(path, name in the pack) of a database file the seed's scan accepts.""" - path = entry.get("path", "") - if seed.exact_dirs: - if ("/" not in path or path.rsplit("/", 1)[0] not in seed.exact_dirs - or "/.variants/" in path): - return None - elif not path.startswith(seed.path_prefix): - return None - if not seed.companion_ext and not shape_fits(seed.entry, path, entry.get("size", 0)): - return None - scan_name = entry.get("name", "") - if not scan_name: - return None - if seed.companion_ext: - stem, _, ext = scan_name.rpartition(".") - if not stem or ext.lower() != seed.companion_ext.lower(): - return None - # Read only beside the image the core selected, so a - # companion counts only next to an image the image's - # own test accepts: Namco System 246 .nvm and .mec - # dumps sit beside no PS2 BIOS. - if not _image_beside(path, stem, seed.image, context.files_db): - return None - scan_name = f"{stem}.{seed.companion_ext}" - return path, scan_name - - -def _scan_extra(seed: _ScanSeed, scan_name: str, dest: str, sha1: str) -> dict: - """The extra a scan emits for one database file.""" - f, layout, emu_name = seed.entry, seed.layout, seed.emu_name - extra = { - "name": scan_name, - "destination": dest, - # The scan already holds the entry it selected, so it - # names it by content. Emitting the filename alone - # sent the packing step back to a by-name lookup, and - # three PS2 resources came back from another - # emulator's copy of the same filename. - "sha1": sha1, - "required": False, - "hle_fallback": False, - "source_emulator": layout.get("emulator", emu_name), - "source_profile": emu_name, - "source_name": seed.name, - "source_path": f.get("path") or "", - "category": f.get("category", "bios"), - "source_system": f.get("system"), - "source_systems": entry_system_ids(f, layout), - "region": f.get("region"), - "selection_slot": f.get("selection_slot"), - "agnostic_scan": True, - } - extra["claim_order"] = (4, 0, emu_name) - return extra - - -def _seed_extras(context: _ScanContext, seed: _ScanSeed) -> list[dict]: - """The extras one seed's scan places, companions included.""" - extras: list[dict] = [] - taken = context.taken - # Scan DB for all files under this prefix matching size - for sha1, entry in context.files_db.items(): - scanned = _scanned_name(context, seed, entry) - if scanned is None: - continue - path, scan_name = scanned - dest = f"{seed.folder}/{scan_name}" if seed.folder else scan_name - full_dest = prefixed_destination(dest, context.extras_prefix) - if full_dest in context.seen_dests and (taken is None or full_dest not in taken): - continue - extra = _scan_extra(seed, scan_name, dest, sha1) - if take(extra, full_dest, context.seen_dests, taken): - extras.append(extra) - else: - # The image another core's scan placed is this core's - # too, and so are the companions it reads beside it: - # Recalbox's libretro PCSX2 opens .erom next to - # the images LRPS2 placed, which LRPS2 never reads. - held = taken.get(full_dest) if taken is not None else None - if held is None or held.get("sha1") != sha1: - continue - extras.extend(_companion_extras( - _companions( - path, scan_name, _companion_extensions(seed.layout, seed.name), - context.files_db, - ), - seed.folder, context.extras_prefix, context.seen_dests, seed.layout, - seed.emu_name, seed.entry, taken, - )) - return extras - - -def placeholder_directories( - seed: dict, emu_name: str, profile: dict, db: dict, all_profiles: dict, -) -> frozenset[str]: - """The folders that hold the dumps a placeholder entry accepts. - - Each folder where another profile of the same system resolves a hashed - file of the seed's shape by content: PCSX2 proves bios/Sony/PlayStation 2/. - Only that folder, not the ones below it (its DVD firmware). - """ - systems = set(profile.get("systems", [])) - directories: set[str] = set() - for other_name, other in all_profiles.items(): - if other_name == emu_name or not systems & set(other.get("systems", [])): - continue - for f in other.get("files", []): - if not isinstance(f, dict) or not any(f.get(h) for h in ("sha1", "md5", "sha256", "crc32")): - continue - if f.get("size") and not size_fits(seed, f["size"]): - continue - local, status = resolve_local_file({**f, "source_profile": other_name}, db) - if (local and "/" in local and resolution_is_hash_exact(status) - and shape_fits(seed, local)): - directories.add(local.rsplit("/", 1)[0]) - return frozenset(directories) - - -def _placeholder_scan( - files: list[dict], emu_name: str, profile: dict, db: dict, standalone: bool, - all_profiles: dict | None = None, -) -> list[dict]: - """The dumps a profile made of placeholders accepts, found by evidence. - - `.bin` resolves to nothing, so it anchors no directory. The folder - where other profiles of the same system resolve their hashed files of - that shape is one: PCSX2 proves bios/Sony/PlayStation 2/ by content, and - LRPS2 reads any 4-8 MB image. Only that folder, not the ones below it - (its DVD firmware). Nothing proven, nothing scanned. - """ - files_db = db.get("files", {}) - extras: list[dict] = [] - for seed in files: - name = str(seed.get("name", "")) - if "<" not in name or seed.get("category", "bios") != "bios": - continue - if not declares_shape(seed): - continue - # .nvm is read beside the image the core selected, never on - # its own: its files come with each scanned image (_companions). - if _companion_of(profile, name)[1] is not None: - continue - directories = placeholder_directories( - seed, emu_name, profile, db, - all_profiles or load_emulator_profiles("emulators"), - ) - layout = (seed.get("standalone_path") if standalone else None) or seed.get("path") or "" - folder = layout.rsplit("/", 1)[0] if "/" in layout else "" - for sha1, entry in sorted(files_db.items(), key=lambda kv: kv[1].get("path", "")): - path = entry.get("path", "") - if "/" not in path or path.rsplit("/", 1)[0] not in directories: - continue - if "/.variants/" in path or not shape_fits(seed, path, entry.get("size", 0)): - continue - scan_name = entry.get("name", "") - dest = f"{folder}/{scan_name}" if folder else scan_name - extras.append({ - "name": scan_name, - "destination": dest, - "sha1": sha1, - "source_name": name, - "source_system": seed.get("system"), - "region": seed.get("region"), - }) - extras.extend(_companion_extras( - _companions(path, scan_name, _companion_extensions(profile, name), files_db), - folder, "", set(), profile, emu_name, seed, - )) - return extras - - -def expand_agnostic_entries( - files: list[dict], emu_name: str, profile: dict, db: dict, standalone: bool, - all_profiles: dict | None = None, -) -> list[dict]: - """A filename-agnostic profile's placeholders, as the files they accept. - - `.bin` names no file: the core takes any dump of the right shape - in its BIOS folder, which is what the platform pack's scan carries. The - emulator pack and verify --emulator looked the placeholder up by name, - found nothing and shipped LRPS2 without a PS2 BIOS. The same scan - replaces the placeholders here. With nothing found they stay, a gap. - """ - if profile.get("bios_mode") != "agnostic" and not any(f.get("agnostic") for f in files): - return files - def folder(entry: dict) -> str: - layout = (entry.get("standalone_path") if standalone else None) or entry.get("path") or "" - return layout.rsplit("/", 1)[0] if "/" in layout else "" - - scanned = agnostic_scan_extras( - {emu_name: {**profile, "files": files}}, {emu_name}, db, - db.get("indexes", {}).get("by_name", {}), set(), "", - PlatformLaunches(standalone=frozenset({emu_name})) if standalone else PlatformLaunches(), - ) - - # A placeholder is answered by the files its own scan found in its own - # folder: PCEE2's eeprom.dat, scanned at the root, said nothing about - # pcsx2/bios/, and its COH-H images, scanned into pcsx2/bios/, say - # nothing about the console .bin beside them. - def answered(extras: list[dict]) -> set[tuple[str, str]]: - return { - (str(e.get("source_name", "")), - e["destination"].rsplit("/", 1)[0] if "/" in e["destination"] else "") - for e in extras - } - - def is_answered(f: dict, covered: set[tuple[str, str]]) -> bool: - # A companion placeholder (.rom1) is read beside its image, so - # it is answered wherever the image placeholder is. - _ext, image = _companion_of(profile, str(f.get("name", ""))) - names = {f.get("name", "")} | ({image.get("name", "")} if image else set()) - return any((n, folder(f)) in covered for n in names) - - covered = answered(scanned) - open_seeds = [ - f for f in files - if "<" in str(f.get("name", "")) and not is_answered(f, covered) - ] - scanned += _placeholder_scan( - open_seeds, emu_name, profile, db, standalone, all_profiles - ) - covered = answered(scanned) - if not scanned: - return files - concrete = [ - { - "name": extra["name"], - "path": extra["destination"], - **({"standalone_path": extra["destination"]} if standalone else {}), - "sha1": extra["sha1"], - "required": False, - **({"system": extra["source_system"]} if extra.get("source_system") else {}), - **({"region": extra["region"]} if extra.get("region") else {}), - "agnostic_scan": True, - } - for extra in scanned - ] - return [ - f for f in files - if "<" not in str(f.get("name", "")) or not is_answered(f, covered) - ] + concrete - - -def _companion_extras( - companions: list[tuple[str, dict]], - folder: str, - extras_prefix: str, - seen_dests: set[str], - profile: dict, - emu_name: str, - seed: dict, - taken: dict[str, dict] | None = None, -) -> list[dict]: - """Extras for the companions of one scanned image, placed beside it.""" - extras: list[dict] = [] - for companion_sha1, companion in companions: - companion_dest = f"{folder}/{companion['name']}" if folder else companion["name"] - companion_full = prefixed_destination(companion_dest, extras_prefix) - if companion_full in seen_dests and (taken is None or companion_full not in taken): - continue - extra = { - "name": companion["name"], - "destination": companion_dest, - "sha1": companion_sha1, - "required": False, - "hle_fallback": False, - "source_emulator": profile.get("emulator", emu_name), - "source_profile": emu_name, - "source_name": seed.get("name", ""), - "source_path": seed.get("path") or "", - "category": seed.get("category", "bios"), - "source_system": seed.get("system"), - "source_systems": entry_system_ids(seed, profile), - "region": seed.get("region"), - "selection_slot": seed.get("selection_slot"), - "agnostic_scan": True, - } - extra["claim_order"] = (4, 0, emu_name) - if take(extra, companion_full, seen_dests, taken): - extras.append(extra) - return extras - - -def _companion_of(profile: dict, name: str) -> tuple[str, dict | None]: - """The extension and the image of an entry named after a content-found image. - - ps2-0230a-20080220.rom1 beside ps2-0230a-20080220.bin (found_by: - content) is the image's companion, read as .rom1. Empty for any - other entry. - """ - stem, _, ext = name.rpartition(".") - if not stem: - return "", None - for entry in profile.get("files", []): - other = str(entry.get("name", "")) - if ( - other != name - and entry.get("found_by") == "content" - and other.rpartition(".")[0].lower() == stem.lower() - ): - return ext, entry - return "", None - - -def _image_beside( - companion_path: str, stem: str, image: dict | None, files_db: dict -) -> bool: - """Whether the folder of a companion holds an image it is read beside. - - PCSX2 opens `.rom1`, then the BIOS path with its extension - replaced (BiosTools.cpp LoadExtraRom, CDVD.cpp cdvdLoadNVRAM): the - companion's stem is the image's name or the image's own stem. The - image has to pass the image entry's test, its size and its ROM - directory, as the scan that selected it does. - """ - if image is None: - return False - directory = companion_path.rsplit("/", 1)[0] + "/" - wanted = stem.lower() - for _sha1, entry in _files_by_directory(files_db).get(directory, ()): - name = str(entry.get("name", "")) - if name.lower() != wanted and name.rpartition(".")[0].lower() != wanted: - continue - if name.lower() == companion_path.rsplit("/", 1)[-1].lower(): - continue - if shape_fits(image, entry.get("path", ""), entry.get("size", 0)): - return True - return False - - -def _companion_extensions(profile: dict, seed_name: str) -> set[str]: - """Extensions the profile declares beside a free-named BIOS entry. - - PCSX2 reads `.rom1` or the BIOS path with its extension replaced - (`.rom1`), and likewise nvm and mec (BiosTools.cpp:214-229, - CDVD.cpp:160-195). A profile states that by naming the companions after - its BIOS entry: ps2-0230a-20080220.rom1 beside ps2-0230a-20080220.bin. - """ - if _companion_of(profile, seed_name)[0]: - return set() - stem = seed_name.rsplit(".", 1)[0].lower() - exts: set[str] = set() - for entry in profile.get("files", []): - other = str(entry.get("name", "")).lower() - if other != seed_name.lower() and other.startswith(stem + "."): - exts.add(other[len(stem) + 1:]) - return exts - - -def _companions( - image_path: str, image_name: str, extensions: set[str], files_db: dict -) -> list[tuple[str, dict]]: - """Files beside a scanned image that the core opens as its companions. - - Each is named as the core spells it: PCSX2 stats `.rom1`, then the - BIOS path with its extension replaced by `rom1`, both case-sensitive on - Linux (BiosTools.cpp:214-229). SCPH-70004.ROM1 as stored is never found - beside SCPH-70004.BIN, SCPH-70004.rom1 is. - """ - if not extensions: - return [] - directory = image_path.rsplit("/", 1)[0] + "/" - stem = image_name.rsplit(".", 1)[0] - spelled = {f"{image_name}.{ext}".lower(): f"{image_name}.{ext}" for ext in extensions} - spelled.update({f"{stem}.{ext}".lower(): f"{stem}.{ext}" for ext in extensions}) - return sorted( - (sha1, {**entry, "name": spelled[str(entry.get("name", "")).lower()]}) - for sha1, entry in _files_by_directory(files_db).get(directory, ()) - if str(entry.get("name", "")).lower() in spelled - ) - - -# The database a directory index was built from, with the index: one walk -# per database instead of one per scanned image (1 023 walks of 19 041 -# entries in verify --all). -_DIRECTORY_INDEX: tuple[dict, dict[str, list[tuple[str, dict]]]] | None = None - - -def _files_by_directory(files_db: dict) -> dict[str, list[tuple[str, dict]]]: - global _DIRECTORY_INDEX - if _DIRECTORY_INDEX is None or _DIRECTORY_INDEX[0] is not files_db: - index: dict[str, list[tuple[str, dict]]] = {} - for sha1, entry in files_db.items(): - directory = entry.get("path", "").rsplit("/", 1)[0] + "/" - index.setdefault(directory, []).append((sha1, entry)) - _DIRECTORY_INDEX = (files_db, index) - return _DIRECTORY_INDEX[1] - - -def archive_prefix_extras( - profiles: dict, - relevant: set, - covered_names: set, - seen_dests: set, - extras_prefix: str, - by_name: dict, - taken: dict[str, dict] | None = None, - launches: PlatformLaunches | None = None, -) -> list[dict]: - """A second copy of an archive under the subdirectory a core reads. - - Some cores look for their romset under a directory of their own - (system/fbneo/neogeo.zip) while the platform declares it at the - root. Both paths are carried so the core's own check finds it. - """ - extras: list[dict] = [] - # Archive prefix pass: cores that store BIOS archives in a subdirectory - # (e.g. system/fbneo/neogeo.zip). When the archive is already covered at - # the root, add a copy at the prefixed path so the core's .info firmware - # check finds it. - for emu_name, profile in sorted(profiles.items()): - if not lists_files(profile): - continue - if emu_name not in relevant: - continue - # A platform that hands each core its own system directory moves the - # subfolder with it, once per directory. - views = [profile] - if core_system_dirs(emu_name, profile, launches or PlatformLaunches()) is not None: - views = [ - view for view, standalone - in platform_layouts(emu_name, profile, launches or PlatformLaunches()) - if not standalone - ] - for view in views: - extras.extend(_archive_prefix_copies( - emu_name, view, covered_names, seen_dests, extras_prefix, - by_name, taken, - )) - return extras - - -def _archive_prefix_copies( - emu_name: str, - profile: dict, - covered_names: set, - seen_dests: set, - extras_prefix: str, - by_name: dict, - taken: dict[str, dict] | None, -) -> list[dict]: - """The prefixed copies of one layout's archives.""" - extras: list[dict] = [] - prefix = profile.get("archive_prefix", "") - if not prefix: - return extras - profile_archives: dict[str, dict] = {} - for f in profile.get("files", []): - archive = f.get("archive", "") - if archive: - profile_archives.setdefault(archive, f) - for archive_name, archive_entry in sorted(profile_archives.items()): - if archive_name not in covered_names: - continue - dest = f"{prefix}/{archive_name}" - full_dest = prefixed_destination(dest, extras_prefix) - if full_dest in seen_dests and (taken is None or full_dest not in taken): - continue - if not by_name.get(archive_name): - continue - extra = { - "name": archive_name, - "destination": dest, - "required": True, - "hle_fallback": False, - "source_emulator": profile.get("emulator", emu_name), - "source_profile": emu_name, - # Keyed as the gap report keys an archive: name and path alike. - "source_name": archive_name, - "source_path": system_dir_path(archive_entry, archive_name), - "category": archive_entry.get("category", "bios"), - "source_system": archive_entry.get("system"), - "source_systems": entry_system_ids(archive_entry, profile), - "region": archive_entry.get("region"), - "selection_slot": archive_entry.get("selection_slot"), - } - members = archive_members(archive_name, profile.get("files", [])) - if members: - extra["members"] = members - if archive_entry.get("system_dir"): - extra["system_dir"] = archive_entry["system_dir"] - extra["claim_order"] = (3, 0, emu_name) - if take(extra, full_dest, seen_dests, taken): - extras.append(extra) - - return extras - - -class ExtraPlacement: - """Where a pack puts a core's file, decided once for every reader. - - The builder, and slots.py judging what a destination holds, both read - this: placed apart, slot arbitration compared RetroDECK's bios/ claims - with core claims at the root and never saw them meet. - """ - - def __init__(self, config: dict, base_dest: str, profiles: dict) -> None: - from model.systems import norm_system_id - - self.prefix = detect_extras_prefix(config, base_dest) - self.slug_based, self.sys_to_slug = _detect_slug_structure(config) - self.platform_systems = set(config.get("systems", {}).keys()) - self.native_systems = native_slug_systems(config) - self.flat = bool(config.get("firmware_folder_flat")) - self.save = save_layout(config) - # The roms root and emulator folders the platform's files describe, - # for a file a launcher runs from them (ROCKNIX's roms/pico-8, - # RetroBat's emulators/pico8). - self.outer = {root for root in OUTER_ROOTS if outer_layout(config, root)} - self.config = config - self.norm_map = ( - {norm_system_id(sid): sid for sid in self.platform_systems} - if self.slug_based - else {} - ) - self.profiles = profiles - - def place(self, entry: dict, dest: str) -> tuple[str, str] | None: - """(pack-relative destination, full destination), or None. - - ``entry`` names its profile and may name its own system. A - slug-based platform cannot place a file of a system it has no - folder for. A file the core reads below the frontend's save - directory (``root: save``) keeps its path relative to that - directory and goes below the platform's save folder, which a - platform keeping saves beside the content does not have. - """ - if entry.get("unplaced"): - return None - if entry.get("unprefixed"): - return dest, dest - if entry.get("root") in OUTER_ROOTS: - root = entry["root"] - return (dest, outer_destination(root, dest)) if root in self.outer else None - if entry.get("root") == "save": - placed = self.save_places(entry, dest) - return placed[0] if placed else None - if self.slug_based: - slug = _slug_for( - entry, self.profiles, self.platform_systems, self.norm_map, - self.sys_to_slug, self.native_systems, - ) - if not slug or self.nested(dest): - return None - dest = f"{slug}/{dest}" - return dest, prefixed_destination(dest, self.prefix) - - def places(self, entry: dict, dest: str) -> list[tuple[str, str]]: - """Every (pack-relative, full) destination the pack gives an entry. - - One for most entries. A file read below the save directory of a - platform that hands each system a save folder of its own goes once - below each system that runs the core. - """ - if entry.get("unplaced"): - return [] - if entry.get("root") == "save": - return self.save_places(entry, dest) - placed = self.place(entry, dest) - return [placed] if placed is not None else [] - - def save_places(self, entry: dict, dest: str) -> list[tuple[str, str]]: - """The destinations of a file read below the save directory.""" - if self.save is None: - return [] - names = self.core_names(entry) - sorted_by_core = self.save.sorts(names) - systems = libretro_systems(self.config, names) if self.save.by_system else [""] - placed = [] - for system in systems: - full = save_destination( - dest, entry.get("core_folder"), self.save, system, sorted_by_core - ) - if full: - placed.append((dest, full)) - return placed - - def core_names(self, entry: dict) -> set[str]: - """The names a report entry's core goes by: its profile key and the - upstream names its profile lists.""" - key = entry.get("profile") or entry.get("emulator", "") - profile: dict = self.profiles.get(key) or next( - (pp for pp in self.profiles.values() if pp.get("emulator") == key), {} - ) - return set(profile_names(str(key), profile)) - {""} - - def nested(self, dest: str) -> bool: - """True when the file would sit below a folder the frontend lists flat.""" - return self.slug_based and self.flat and "/" in dest - - def unplaced_reason(self, entry: dict, dest: str) -> str: - """Why ``place`` returned None for this entry.""" - if entry.get("unplaced"): - return str(entry["unplaced"]) - if entry.get("root") in OUTER_ROOTS: - return f"no_{entry['root']}_directory" - if entry.get("root") == "save": - if self.save is None: - return "no_save_directory" - if self.save.by_system and not libretro_systems( - self.config, self.core_names(entry) - ): - return "no_save_system" - return "no_core_folder" - return "below_platform_folder" if self.nested(dest) else "no_platform_slug" +from packs.extraplace import ( + ExtraPlacement, + another_claim, + archive_prefix_extras, + extra_dest, + prefixed_destination, + take, +) +from packs.extrascan import agnostic_scan_extras def undeclared_report( @@ -1996,450 +656,3 @@ def _report_extra(u: dict, name: str, dest: str) -> dict: if declared not in (None, "", []): extra[identity] = declared return extra - - -def take( - extra: dict, full_dest: str, seen_dests: set[str], taken: dict[str, dict] | None -) -> bool: - """Whether an extra takes its destination. A taken one records the claim.""" - if full_dest in seen_dests: - if taken is not None: - another_claim(taken.get(full_dest), extra) - return False - seen_dests.add(full_dest) - if taken is not None: - taken[full_dest] = extra - return True - - -def another_claim(extra: dict | None, claim: dict) -> None: - """Record a core that reads a destination another core's extra took. - - The pack ships one file per destination, so the first claimant's extra - stands. The others are kept on it so the manifest can name every core - the file serves. A pack built for a target without the first core packs - the next one's copy, and an installer narrowing by core must keep it. - """ - if extra is None or claim.get("source_profile") == extra.get("source_profile"): - return - claims = extra.setdefault("other_claims", []) - claims.append(claim) - claims.sort(key=lambda c: c["claim_order"]) - - -def extra_system_ids(extra: dict) -> list[str]: - """Return the narrowest system ownership preserved on a core extra.""" - explicit = extra.get("source_system") - if explicit: - return [str(explicit)] - return [str(value) for value in extra.get("source_systems", []) if value] - -def serving_system_ids(extra: dict) -> list[str]: - """Every system the extra's file serves: its own core's and those of the - other cores whose claim rides on it. One file stands per destination, so - narrowed to any of their systems the file is what that core reads. - """ - ids = list(extra_system_ids(extra)) - for claim in extra.get("other_claims", []): - ids.extend(s for s in extra_system_ids(claim) if s not in ids) - return ids - - -def kept_entries(entries: list[dict], required_only: bool) -> list[dict]: - """The entries a pack keeps: optional ones go under --required-only.""" - if not required_only: - return entries - return [e for e in entries if e.get("required") is not False] - - -def extras_for_systems(extras: list[dict], system_ids: list[str]) -> list[dict]: - """Core extras owned by one of the given systems. - - Extras carry their profile/system identity directly. Display labels are - presentation only and must never drive routing. - """ - wanted = set(system_ids) | {norm_system_id(s) for s in system_ids} - return [ - fe for fe in extras - if ( - set(serving_system_ids(fe)) - | {norm_system_id(s) for s in serving_system_ids(fe)} - ) & wanted - ] - - -def report_owned_by_systems(report: list[dict], system_ids: list[str]) -> list[dict]: - """Gap report entries whose extra a pack built with --system carries. - - The other cores whose claim rides on the entry count, as the builder - counts them: MAME 2009's taitofx1.zip went into a --system - panasonic-3do pack for MAME 2016 and was missing from the report. - """ - def owner(entry: dict) -> dict: - return {"source_system": entry.get("system"), "source_systems": entry.get("systems", [])} - - return [ - u for u in report - if extras_for_systems( - [{**owner(u), "other_claims": [owner(c) for c in u.get("other_claims", [])]}], - system_ids, - ) - ] - - -def _ships( - config: dict, - file_entry: dict, - db: dict, - zip_contents: dict | None, - data_registry: dict | None, - override: str | None, -) -> bool: - """Whether the builder packs this declaration: resolved, and not refused - by a hash frontend. A dump whose md5 Recalbox would reject is left out - of the pack, so it cannot win a regional slot over a file that ships. - - Resolved with the builder's own inputs: without the data directories, - AmberELEC's bluemsx config.ini read as missing while the pack held it. - """ - from resolve.packfiles import resolve_declaration - from resolve.acceptance import baseline_verdict - - path, status = resolve_declaration( - file_entry, db, "bios", zip_contents, data_registry, override, offline=True, - ) - if not path: - return False - return baseline_verdict( - file_entry, path, status, platform_mode(config), - config.get("hash_rule", ""), - )[1] is None - - -class RegionGroupOptions(TypedDict, total=False): - """What platform_region_groups reads besides the platform, and fills.""" - - include_all: bool - required_only: bool - extras_out: list[dict] | None - held_out: set[str] | None - undeclared: list[dict] | None - zip_contents: dict | None - data_registry: dict | None - slot_overrides: dict[str, str] | None - - -def platform_region_groups( - config: dict, - systems: dict, - emulators_dir: str, - db: dict | None, - base_dest: str, - emu_profiles: dict | None, - *, - target_cores: set[str] | None = None, - include_extras: bool = True, - **options: Unpack[RegionGroupOptions], -) -> tuple[dict[str, list[tuple[str, str]]], dict[tuple[str, str, str], str]]: - """Group a platform's pack candidates the way region filtering reads them. - - ``held_out`` receives the destinations whose file the collection holds: - a missing file is grouped so the report can withdraw it, but it never - takes the slot of a held one (resolve_region_drops). - - Returns the groups and, for every core extra, the destination it was - grouped under, keyed by (emulator, name). verify.py needs that mapping to - withdraw from its report exactly what the builder withdraws from the pack: - grouping the declared files here and the core extras there would let the - two answer differently on the same request. `extras_out` receives the - core extras that were grouped, for the install manifest. ``undeclared`` - is the gap report when the caller holds it (undeclared_report, with the - same target_cores and include_all). ``zip_contents``, ``data_registry`` - and ``slot_overrides`` (keyed by full pack destination) are the ones the - builder resolves with, so a held declaration is the one the pack ships. - """ - reject_unknown("platform_region_groups", options, RegionGroupOptions.__optional_keys__) - include_all = options.get("include_all", False) - undeclared = options.get("undeclared") - required_only = options.get("required_only", False) - held_out = options.get("held_out") - extras_out = options.get("extras_out") - zip_contents = options.get("zip_contents") - data_registry = options.get("data_registry") - slot_overrides = options.get("slot_overrides") - groups: dict[str, list[tuple[str, str]]] = {} - for sys_id, system in systems.items(): - members = groups.setdefault(sys_id, []) - # Decided over what the pack keeps: an optional winner removed - # afterwards left its slot empty. - for file_entry in kept_entries(system.get("files", []), required_only): - dest = declared_destination(file_entry) - if dest: - members.append((dest, file_entry.get("name", ""))) - full_dest = f"{base_dest}/{dest}" if base_dest else dest - if held_out is not None and db is not None and _ships( - config, file_entry, db, zip_contents, data_registry, - (slot_overrides or {}).get(full_dest), - ): - held_out.add(dest) - - extra_dests: dict[tuple[str, str, str], str] = {} - if not include_extras or db is None: - return groups, extra_dests - - absent: list[dict] = [] - extras = collect_emulator_extras( - config, - emulators_dir, - db, - set(), - base_dest, - emu_profiles, - target_cores=target_cores, - include_all=include_all, - claimants=extra_dests, - absent=absent, - undeclared=undeclared, - ) - held = {id(extra) for extra in extras} - spellings = system_spellings(systems) - region_prefix = declared_root(config) - for extra in kept_entries(extras + absent, required_only): - dest = extra_region_key(extra, region_prefix) - if not dest: - continue - name = extra.get("name", "") - extra_dests[ - ( - extra.get("source_emulator", ""), - extra.get("source_name", ""), - extra.get("source_path", ""), - ) - ] = dest - # A file a filename-agnostic scan accepts by shape competes only if - # its seed names a region: PCSX2 picks no PS2 BIOS by territory, and - # looked up by name its scph50006 took DuckStation's [japan], which - # describes DuckStation's own PS1-on-PS2 choice. - competes = not extra.get("agnostic_scan") or extra.get("region") - for group_id in extra_region_groups(extra, spellings) if competes else (): - groups.setdefault(group_id, []).append((dest, name)) - if extras_out is not None and id(extra) in held: - extras_out.append(extra) - if held_out is not None and id(extra) in held: - held_out.add(dest) - return groups, extra_dests - - -def system_spellings(systems: Iterable[str]) -> dict[str, str]: - """A platform's own spelling of each system, keyed the way ids compare. - - RetroDECK files the Master System as sega-master-system, the profiles as - sega-mastersystem. Grouped under both, the declared bios/bios_J.sms and - the core's bios_J.sms were reduced apart and a --region us pack kept the - Japanese BIOS. - """ - spellings: dict[str, str] = {} - for sys_id in sorted(systems): - spellings.setdefault(norm_system_id(sys_id), sys_id) - return spellings - - -def _region_basis(extra: dict) -> tuple[str, str]: - """What a core extra's region group is keyed on, in either mode. - - A selection slot, else the one system the file is chosen for, else the - file alone. Platform and emulator mode both read this, so the two - cannot group the same file apart. - """ - variant = extra.get("selection_slot") - if variant: - # A selection slot is one slot of one core, whatever system each - # member is filed under: PicoDrive files its US Mega CD BIOS under - # sega-segacd and the EU/JP ones under sega-megacd, and find_bios - # picks one of the twelve. - return "variant", str(variant) - systems = extra_system_ids(extra) - if len(systems) == 1: - return "system", systems[0] - # No system names the machine this file is chosen for. Filed under every - # system of a 30-system profile, CLK's American MSX ROM made the - # Enterprise group drop its German ROM. Alone, it drops nothing and is - # never dropped. - return "file", str(extra.get("destination", extra.get("name", ""))) - - -def extra_region_groups( - extra: dict, spellings: dict[str, str] | None = None -) -> list[str]: - """The region groups a core extra competes in. - - A group named after a system takes the platform's spelling of it, so the - extra competes beside the files the platform declares for that system. - """ - emulator = extra.get("source_emulator", "") - kind, value = _region_basis(extra) - if kind == "variant": - return [f"{emulator}:variant:{value}"] - if kind == "system": - return [(spellings or {}).get(norm_system_id(value), value)] - return [f"{emulator}{FILE_GROUP}{value}"] - - -def emulator_region_drops( - selected: list[tuple[str, dict]], - standalone: bool, - regions: list[str], - required_only: bool = False, - db: dict | None = None, - zip_contents: dict | None = None, - data_registry: dict | None = None, -) -> set[str]: - """Destinations an emulator-mode `--region` withdraws. - - One group per system (or explicit selection_slot) inside each profile, so - a multi-system core such as O2EM keeps a fallback BIOS for every system - instead of letting one matching system empty another. The emulator pack - and `verify --emulator` both read this, keyed by pack destination. - - With `db`, a requested-region file the collection lacks never displaces - a held one, as in platform mode: a held scph5501.bin was withdrawn for a - Japanese image nobody had collected, and the pack shipped no PlayStation - BIOS at all. ``zip_contents`` and ``data_registry`` are the ones the - emulator pack resolves with. - """ - from resolve import regions as resolve_regions - from packs.paths import resolve_destination - from resolve.validation import build_validation_index - from resolve.entryscope import filter_files_by_mode - - region_index = resolve_regions.build_region_index(dict(selected)) - region_groups: dict[str, list[tuple[str, str]]] = {} - held: set[str] | None = set() if db is not None else None - validation_index = build_validation_index(dict(selected)) if db is not None else {} - for emu_name, profile in sorted(selected): - # Decided over what the pack keeps, as on the platform side: an - # optional winner removed afterwards left its slot empty. - entries = filter_files_by_mode(profile.get("files", []), standalone) - for fe in kept_entries(entries, required_only): - dest = resolve_destination(fe, standalone) - if dest: - group_id = _emulator_region_group(emu_name, profile, fe, dest) - region_groups.setdefault(group_id, []).append( - (dest, fe.get("name", "")) - ) - if held is not None and db is not None and _emulator_ships( - fe, emu_name, profile, db, validation_index, - zip_contents, data_registry, - ): - held.add(dest) - return resolve_regions.resolve_region_drops(region_groups, region_index, regions, held) - - -class SpareOptions(TypedDict, total=False): - data_registry: dict | None - - -def emulator_required_spares( - emu_name: str, - profile: dict, - files: list[dict], - standalone: bool, - region_drops: set[str], - db: dict, - validation_index: dict, - zip_contents: dict | None, - **options: Unpack[SpareOptions], -) -> set[str]: - """The destinations an emulator --required-only pack leaves out: of each - required set, one held member stays, the first the code loads among - those the pack still carries after the region filter. An archive unit - is a member like a loose file: Kronos reads kronos/stvbios.zip, else - stvbios.zip. The pack and verify --emulator both read this.""" - from model.alternatives import groups_of, rank_in, required_groups - from resolve.archives import archive_entry - from packs.paths import archive_destination, resolve_destination - - reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__) - data_registry = options.get("data_registry") - candidates: list[dict] = [] - archives: list[str] = [] - for fe in files: - archive = fe.get("archive") - if archive and archive not in archives: - archives.append(archive) - own = archive_entry(archive, files) - if groups_of(own): - candidates.append({"dest": archive_destination( - archive, profile.get("archive_prefix", ""), - profile.get("pack_structure"), standalone, - ), "entry": own}) - candidates.extend( - {"dest": resolve_destination(fe, standalone), "entry": fe} - for fe in files if not fe.get("archive") and groups_of(fe) - ) - if not candidates: - return set() - spares = required_only_spares( - candidates, - owner=lambda _c: emu_name, - held=lambda c: _emulator_ships( - c["entry"], emu_name, profile, db, validation_index, zip_contents, data_registry, - ), - gone=lambda c: c["dest"] in region_drops, - sets=lambda c: {g: rank_in(c["entry"], g) for g in required_groups(c["entry"], profile)}, - ) - return {c["dest"] for c in candidates if id(c) in spares} - - -def _emulator_ships( - file_entry: dict, emu_name: str, profile: dict, db: dict, - validation_index: dict, zip_contents: dict | None, data_registry: dict | None, -) -> bool: - """Whether the emulator pack ships this entry: held, and not refused by - the core's own check, the test _ships applies on the platform side. - - Resolved as generate_emulator_pack resolves: without the data - directories, dolphin-mmjr2's nwc24msg.cfg read as missing while the pack - held it. - """ - from resolve.packfiles import resolve_file - from resolve.acceptance import validated_choice - from resolve.entryscope import with_archive_members - - local, status = resolve_file( - {**with_archive_members(file_entry, profile.get("files", [])), - "source_profile": emu_name}, - db, "bios", zip_contents, - dest_hint=file_entry.get("path", ""), - data_dir_registry=data_registry, - offline=True, - ) - if status in ("not_found", "user_provided") or not local: - return False - _chosen, disagreement = validated_choice( - file_entry, local, db, validation_index, "bios", None, emulators={emu_name}, - ) - return disagreement is None - - -def _emulator_region_group( - emu_name: str, profile: dict, file_entry: dict, dest: str -) -> str: - """Stable group ID for regional alternatives within an emulator profile. - - Keyed by _region_basis, the rule extra_region_groups applies on the - platform side, over the systems entry_system_ids gives the entry. A - system group carries the emulator, since an emulator pack reduces each - profile on its own. - """ - kind, value = _region_basis({ - "selection_slot": file_entry.get("selection_slot"), - "source_system": file_entry.get("system"), - "source_systems": entry_system_ids(file_entry, profile), - "destination": dest, - }) - if kind == "variant": - return f"{emu_name}:variant:{value}" - if kind == "system": - return f"{emu_name}:system:{value}" - return f"{emu_name}{FILE_GROUP}{dest}" diff --git a/scripts/packs/extrascan.py b/scripts/packs/extrascan.py new file mode 100644 index 000000000..05a01d697 --- /dev/null +++ b/scripts/packs/extrascan.py @@ -0,0 +1,626 @@ +"""Files a core finds by scanning a directory, and the companions beside an image.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from model.declarations import OUTER_ROOTS +from model.profiles import entry_system_ids, lists_files, load_emulator_profiles +from packs.extraplace import prefixed_destination, take +from resolve.content import declares_shape, shape_fits, size_fits +from resolve.launches import PlatformLaunches +from resolve.layout import system_dir_path +from resolve.localfile import resolution_is_hash_exact, resolve_local_file +from resolve.standalone import platform_layouts +from resolve.entryscope import read_by_build, read_from_save_dir + + +@dataclass(frozen=True) +class _ScanContext: + """What every seed of one agnostic scan reads and fills.""" + + db: dict + files_db: dict + by_name: dict + seen_dests: set + extras_prefix: str + taken: dict[str, dict] | None + profiles: dict + + +@dataclass(frozen=True) +class _ResolvedDirs: + """Where a profile's own files resolve, the evidence a scan anchors on.""" + + dirs: dict[int, str] + named_only: set[int] + votes: dict[str, int] + + +@dataclass(frozen=True) +class _ScanSeed: + """One agnostic entry of one layout and the folder its scan walks.""" + + emu_name: str + layout: dict + entry: dict + name: str + companion_ext: str + image: dict | None + path_prefix: str + exact_dirs: frozenset[str] + folder: str + + +def agnostic_scan_extras( + profiles: dict, + relevant: set, + db: dict, + by_name: dict, + seen_dests: set, + extras_prefix: str, + launches: PlatformLaunches | None = None, + taken: dict[str, dict] | None = None, +) -> list[dict]: + """Every interchangeable candidate a filename-agnostic core accepts. + + Such a core reads whatever sits in its BIOS directory, so the pack + carries every dump of the right shape rather than one chosen name. + The directory is the delicate part: anchoring it on a single + filename walked into another emulator's tree, so the profile's own + files have to agree before the scan follows an ambiguous name. + """ + extras: list[dict] = [] + context = _ScanContext( + db, db.get("files", {}), by_name, seen_dests, extras_prefix, taken, profiles, + ) + # Third pass: the agnostic scan. For filename-agnostic cores, include all + # DB files matching the system path prefix and size criteria. + for emu_name, profile in sorted(profiles.items()): + if not lists_files(profile): + continue + if emu_name not in relevant: + continue + is_profile_agnostic = profile.get("bios_mode") == "agnostic" + if not is_profile_agnostic and not any( + f.get("agnostic") for f in profile.get("files", []) + ): + continue + resolved = _resolved_dirs(emu_name, profile, db) + for layout, standalone in platform_layouts(emu_name, profile, launches or PlatformLaunches()): + # A layout copies each entry in order (a launcher's folder, a + # system directory): its files are looked up as the profile's + # own, or a bound layout scans nothing (KNULLI's bios/ps2). + origin = { + id(view): entry + for view, entry in zip(layout.get("files", []), profile.get("files", [])) + } + for f in layout.get("files", []): + if not is_profile_agnostic and not f.get("agnostic"): + continue + seed = _scan_seed(context, emu_name, layout, f, standalone, origin, resolved) + if seed is not None: + extras.extend(_seed_extras(context, seed)) + return extras + + +def _resolved_dirs(emu_name: str, profile: dict, db: dict) -> _ResolvedDirs: + """Where each of this profile's files resolves. + + A scan anchored on one filename walks into whatever tree that name + happens to hit: rom1.bin is a PS2 ROM and a Roland SC-55 ROM, + GameIndex.yaml belongs to four PS2 profiles and to an Android package. + One match is not evidence of a directory, two files of the same profile + agreeing is. + """ + resolved_dirs: dict[int, str] = {} + named_only: set[int] = set() + agnostic_votes: dict[str, int] = {} + for candidate in profile.get("files", []): + if not isinstance(candidate, dict): + continue + local, status = resolve_local_file( + {**candidate, "source_profile": emu_name}, + db, + dest_hint=candidate.get("path", ""), + ) + if not local or "/" not in local: + continue + directory = local.rsplit("/", 1)[0] + if directory.endswith("/.variants"): + directory = directory[: -len("/.variants")] + resolved_dirs[id(candidate)] = directory + "/" + if not (resolution_is_hash_exact(status) or status == "path_exact"): + named_only.add(id(candidate)) + agnostic_votes[directory + "/"] = ( + agnostic_votes.get(directory + "/", 0) + 1 + ) + return _ResolvedDirs(resolved_dirs, named_only, agnostic_votes) + + +def _seeds_a_scan(f: dict, layout: dict, standalone: bool) -> bool: + """Whether an agnostic entry may seed a scan of the BIOS directory.""" + # A file of the build the platform does not run seeds nothing: + # armsx2's proverb.zip is fetched by the Android app into its own + # arcade/ folder, and the libretro packs carried it at system/. + if not read_by_build(f, standalone): + return False + # The scan walks the BIOS tree: a file read below the save + # directory is placed by the gap report's pass. + if (read_from_save_dir(f, standalone) or f.get("unplaced") + or f.get("root") in OUTER_ROOTS or f.get("unprefixed")): + return False + # An agnostic BIOS mode says the BIOS filename is free, not that + # every file the emulator loads is. A free filename still has a + # known shape, and that shape is what identifies a candidate: an + # entry declaring no size takes the whole directory, which is how + # the flag icons of an Android package walked into a PS2 pack. + if f.get("category", "bios") != "bios": + return False + if not declares_shape(f): + return False + # The free name is the BIOS directory's: a shader, a sound or a + # font the emulator reads from its resources tree has a fixed + # name and must not seed a scan (yaps2 flattened 189 of them to + # the root of the RetroArch pack). + bios_dir = layout.get("bios_directory") + fpath = f.get("path") or "" + return not (bios_dir and "/" in fpath and not fpath.startswith(bios_dir)) + + +def _scan_seed( + context: _ScanContext, + emu_name: str, + layout: dict, + f: dict, + standalone: bool, + origin: dict[int, dict], + resolved: _ResolvedDirs, +) -> _ScanSeed | None: + """The scan an agnostic entry seeds, None when it seeds none.""" + fname = f.get("name", "") + if not fname or not _seeds_a_scan(f, layout, standalone): + return None + + # A companion is read under its image's name with the + # extension the code appends, in that case: only a file of + # that extension is one, spelled as the code spells it. Its + # size identifies nothing, PCSX2 reads min(size, filesize) + # (BiosTools.cpp:234), and a 4 MB bound swept every smaller + # file of the folder to the BIOS root. It sits beside its + # image, so the scan looks where the image resolves: the + # held ps2-0230a-20080220.rom1 is a DVD firmware dump filed + # under DVD Firmware/. + companion_ext, image = _companion_of(layout, fname) + + path_prefix = ( + resolved.dirs.get(id(origin.get(id(image), image)), "") if image + else resolved.dirs.get(id(origin.get(id(f), f)), "") + ) + # A placeholder (.bin) resolves to nothing and anchors no + # directory. The folders where the system's other profiles + # resolve hashed files of that shape do, those folders only: + # LRPS2 and PCEE2 are made of placeholders, and on Batocera, + # where no other libretro PS2 core anchors pcsx2/bios/, the + # pack held nothing there. A companion (.nvm) looks + # where its image is proven: RetroBat's pcsx2/bios/ had + # scph39001.bin and its .nvm only at the BIOS root. + exact_dirs: frozenset[str] = frozenset() + anchor = image if image else f + if not path_prefix and "<" in str(anchor.get("name", "")): + exact_dirs = placeholder_directories( + anchor, emu_name, layout, context.db, context.profiles + ) + if not path_prefix and not exact_dirs: + return None + # A name matching one file identifies it. A name matching several + # identifies nothing on its own, so the profile's other files have + # to agree on the directory before the scan walks it. + ambiguous = ( + id(origin.get(id(f), f)) in resolved.named_only + and len(context.by_name.get(fname, [])) > 1 + ) + if ambiguous and resolved.votes.get(path_prefix, 0) < 2: + return None + + # Into the directory the seed entry names, not the root: + # yaps2 reads its BIOS from pcsx2/bios/. + seed = f.get("path") or "" + if standalone: + seed = f.get("standalone_path") or seed + else: + seed = system_dir_path(f, seed or fname) + folder = seed.rsplit("/", 1)[0] if "/" in seed else "" + return _ScanSeed( + emu_name, layout, f, fname, companion_ext, image, path_prefix, exact_dirs, folder, + ) + + +def _scanned_name(context: _ScanContext, seed: _ScanSeed, entry: dict) -> tuple[str, str] | None: + """(path, name in the pack) of a database file the seed's scan accepts.""" + path = entry.get("path", "") + if seed.exact_dirs: + if ("/" not in path or path.rsplit("/", 1)[0] not in seed.exact_dirs + or "/.variants/" in path): + return None + elif not path.startswith(seed.path_prefix): + return None + if not seed.companion_ext and not shape_fits(seed.entry, path, entry.get("size", 0)): + return None + scan_name = entry.get("name", "") + if not scan_name: + return None + if seed.companion_ext: + stem, _, ext = scan_name.rpartition(".") + if not stem or ext.lower() != seed.companion_ext.lower(): + return None + # Read only beside the image the core selected, so a + # companion counts only next to an image the image's + # own test accepts: Namco System 246 .nvm and .mec + # dumps sit beside no PS2 BIOS. + if not _image_beside(path, stem, seed.image, context.files_db): + return None + scan_name = f"{stem}.{seed.companion_ext}" + return path, scan_name + + +def _scan_extra(seed: _ScanSeed, scan_name: str, dest: str, sha1: str) -> dict: + """The extra a scan emits for one database file.""" + f, layout, emu_name = seed.entry, seed.layout, seed.emu_name + extra = { + "name": scan_name, + "destination": dest, + # The scan already holds the entry it selected, so it + # names it by content. Emitting the filename alone + # sent the packing step back to a by-name lookup, and + # three PS2 resources came back from another + # emulator's copy of the same filename. + "sha1": sha1, + "required": False, + "hle_fallback": False, + "source_emulator": layout.get("emulator", emu_name), + "source_profile": emu_name, + "source_name": seed.name, + "source_path": f.get("path") or "", + "category": f.get("category", "bios"), + "source_system": f.get("system"), + "source_systems": entry_system_ids(f, layout), + "region": f.get("region"), + "selection_slot": f.get("selection_slot"), + "agnostic_scan": True, + } + extra["claim_order"] = (4, 0, emu_name) + return extra + + +def _seed_extras(context: _ScanContext, seed: _ScanSeed) -> list[dict]: + """The extras one seed's scan places, companions included.""" + extras: list[dict] = [] + taken = context.taken + # Scan DB for all files under this prefix matching size + for sha1, entry in context.files_db.items(): + scanned = _scanned_name(context, seed, entry) + if scanned is None: + continue + path, scan_name = scanned + dest = f"{seed.folder}/{scan_name}" if seed.folder else scan_name + full_dest = prefixed_destination(dest, context.extras_prefix) + if full_dest in context.seen_dests and (taken is None or full_dest not in taken): + continue + extra = _scan_extra(seed, scan_name, dest, sha1) + if take(extra, full_dest, context.seen_dests, taken): + extras.append(extra) + else: + # The image another core's scan placed is this core's + # too, and so are the companions it reads beside it: + # Recalbox's libretro PCSX2 opens .erom next to + # the images LRPS2 placed, which LRPS2 never reads. + held = taken.get(full_dest) if taken is not None else None + if held is None or held.get("sha1") != sha1: + continue + extras.extend(_companion_extras( + _companions( + path, scan_name, _companion_extensions(seed.layout, seed.name), + context.files_db, + ), + seed.folder, context.extras_prefix, context.seen_dests, seed.layout, + seed.emu_name, seed.entry, taken, + )) + return extras + + +def placeholder_directories( + seed: dict, emu_name: str, profile: dict, db: dict, all_profiles: dict, +) -> frozenset[str]: + """The folders that hold the dumps a placeholder entry accepts. + + Each folder where another profile of the same system resolves a hashed + file of the seed's shape by content: PCSX2 proves bios/Sony/PlayStation 2/. + Only that folder, not the ones below it (its DVD firmware). + """ + systems = set(profile.get("systems", [])) + directories: set[str] = set() + for other_name, other in all_profiles.items(): + if other_name == emu_name or not systems & set(other.get("systems", [])): + continue + for f in other.get("files", []): + if not isinstance(f, dict) or not any(f.get(h) for h in ("sha1", "md5", "sha256", "crc32")): + continue + if f.get("size") and not size_fits(seed, f["size"]): + continue + local, status = resolve_local_file({**f, "source_profile": other_name}, db) + if (local and "/" in local and resolution_is_hash_exact(status) + and shape_fits(seed, local)): + directories.add(local.rsplit("/", 1)[0]) + return frozenset(directories) + + +def _placeholder_scan( + files: list[dict], emu_name: str, profile: dict, db: dict, standalone: bool, + all_profiles: dict | None = None, +) -> list[dict]: + """The dumps a profile made of placeholders accepts, found by evidence. + + `.bin` resolves to nothing, so it anchors no directory. The folder + where other profiles of the same system resolve their hashed files of + that shape is one: PCSX2 proves bios/Sony/PlayStation 2/ by content, and + LRPS2 reads any 4-8 MB image. Only that folder, not the ones below it + (its DVD firmware). Nothing proven, nothing scanned. + """ + files_db = db.get("files", {}) + extras: list[dict] = [] + for seed in files: + name = str(seed.get("name", "")) + if "<" not in name or seed.get("category", "bios") != "bios": + continue + if not declares_shape(seed): + continue + # .nvm is read beside the image the core selected, never on + # its own: its files come with each scanned image (_companions). + if _companion_of(profile, name)[1] is not None: + continue + directories = placeholder_directories( + seed, emu_name, profile, db, + all_profiles or load_emulator_profiles("emulators"), + ) + layout = (seed.get("standalone_path") if standalone else None) or seed.get("path") or "" + folder = layout.rsplit("/", 1)[0] if "/" in layout else "" + for sha1, entry in sorted(files_db.items(), key=lambda kv: kv[1].get("path", "")): + path = entry.get("path", "") + if "/" not in path or path.rsplit("/", 1)[0] not in directories: + continue + if "/.variants/" in path or not shape_fits(seed, path, entry.get("size", 0)): + continue + scan_name = entry.get("name", "") + dest = f"{folder}/{scan_name}" if folder else scan_name + extras.append({ + "name": scan_name, + "destination": dest, + "sha1": sha1, + "source_name": name, + "source_system": seed.get("system"), + "region": seed.get("region"), + }) + extras.extend(_companion_extras( + _companions(path, scan_name, _companion_extensions(profile, name), files_db), + folder, "", set(), profile, emu_name, seed, + )) + return extras + + +def expand_agnostic_entries( + files: list[dict], emu_name: str, profile: dict, db: dict, standalone: bool, + all_profiles: dict | None = None, +) -> list[dict]: + """A filename-agnostic profile's placeholders, as the files they accept. + + `.bin` names no file: the core takes any dump of the right shape + in its BIOS folder, which is what the platform pack's scan carries. The + emulator pack and verify --emulator looked the placeholder up by name, + found nothing and shipped LRPS2 without a PS2 BIOS. The same scan + replaces the placeholders here. With nothing found they stay, a gap. + """ + if profile.get("bios_mode") != "agnostic" and not any(f.get("agnostic") for f in files): + return files + def folder(entry: dict) -> str: + layout = (entry.get("standalone_path") if standalone else None) or entry.get("path") or "" + return layout.rsplit("/", 1)[0] if "/" in layout else "" + + scanned = agnostic_scan_extras( + {emu_name: {**profile, "files": files}}, {emu_name}, db, + db.get("indexes", {}).get("by_name", {}), set(), "", + PlatformLaunches(standalone=frozenset({emu_name})) if standalone else PlatformLaunches(), + ) + + # A placeholder is answered by the files its own scan found in its own + # folder: PCEE2's eeprom.dat, scanned at the root, said nothing about + # pcsx2/bios/, and its COH-H images, scanned into pcsx2/bios/, say + # nothing about the console .bin beside them. + def answered(extras: list[dict]) -> set[tuple[str, str]]: + return { + (str(e.get("source_name", "")), + e["destination"].rsplit("/", 1)[0] if "/" in e["destination"] else "") + for e in extras + } + + def is_answered(f: dict, covered: set[tuple[str, str]]) -> bool: + # A companion placeholder (.rom1) is read beside its image, so + # it is answered wherever the image placeholder is. + _ext, image = _companion_of(profile, str(f.get("name", ""))) + names = {f.get("name", "")} | ({image.get("name", "")} if image else set()) + return any((n, folder(f)) in covered for n in names) + + covered = answered(scanned) + open_seeds = [ + f for f in files + if "<" in str(f.get("name", "")) and not is_answered(f, covered) + ] + scanned += _placeholder_scan( + open_seeds, emu_name, profile, db, standalone, all_profiles + ) + covered = answered(scanned) + if not scanned: + return files + concrete = [ + { + "name": extra["name"], + "path": extra["destination"], + **({"standalone_path": extra["destination"]} if standalone else {}), + "sha1": extra["sha1"], + "required": False, + **({"system": extra["source_system"]} if extra.get("source_system") else {}), + **({"region": extra["region"]} if extra.get("region") else {}), + "agnostic_scan": True, + } + for extra in scanned + ] + return [ + f for f in files + if "<" not in str(f.get("name", "")) or not is_answered(f, covered) + ] + concrete + + +def _companion_extras( + companions: list[tuple[str, dict]], + folder: str, + extras_prefix: str, + seen_dests: set[str], + profile: dict, + emu_name: str, + seed: dict, + taken: dict[str, dict] | None = None, +) -> list[dict]: + """Extras for the companions of one scanned image, placed beside it.""" + extras: list[dict] = [] + for companion_sha1, companion in companions: + companion_dest = f"{folder}/{companion['name']}" if folder else companion["name"] + companion_full = prefixed_destination(companion_dest, extras_prefix) + if companion_full in seen_dests and (taken is None or companion_full not in taken): + continue + extra = { + "name": companion["name"], + "destination": companion_dest, + "sha1": companion_sha1, + "required": False, + "hle_fallback": False, + "source_emulator": profile.get("emulator", emu_name), + "source_profile": emu_name, + "source_name": seed.get("name", ""), + "source_path": seed.get("path") or "", + "category": seed.get("category", "bios"), + "source_system": seed.get("system"), + "source_systems": entry_system_ids(seed, profile), + "region": seed.get("region"), + "selection_slot": seed.get("selection_slot"), + "agnostic_scan": True, + } + extra["claim_order"] = (4, 0, emu_name) + if take(extra, companion_full, seen_dests, taken): + extras.append(extra) + return extras + + +def _companion_of(profile: dict, name: str) -> tuple[str, dict | None]: + """The extension and the image of an entry named after a content-found image. + + ps2-0230a-20080220.rom1 beside ps2-0230a-20080220.bin (found_by: + content) is the image's companion, read as .rom1. Empty for any + other entry. + """ + stem, _, ext = name.rpartition(".") + if not stem: + return "", None + for entry in profile.get("files", []): + other = str(entry.get("name", "")) + if ( + other != name + and entry.get("found_by") == "content" + and other.rpartition(".")[0].lower() == stem.lower() + ): + return ext, entry + return "", None + + +def _image_beside( + companion_path: str, stem: str, image: dict | None, files_db: dict +) -> bool: + """Whether the folder of a companion holds an image it is read beside. + + PCSX2 opens `.rom1`, then the BIOS path with its extension + replaced (BiosTools.cpp LoadExtraRom, CDVD.cpp cdvdLoadNVRAM): the + companion's stem is the image's name or the image's own stem. The + image has to pass the image entry's test, its size and its ROM + directory, as the scan that selected it does. + """ + if image is None: + return False + directory = companion_path.rsplit("/", 1)[0] + "/" + wanted = stem.lower() + for _sha1, entry in _files_by_directory(files_db).get(directory, ()): + name = str(entry.get("name", "")) + if name.lower() != wanted and name.rpartition(".")[0].lower() != wanted: + continue + if name.lower() == companion_path.rsplit("/", 1)[-1].lower(): + continue + if shape_fits(image, entry.get("path", ""), entry.get("size", 0)): + return True + return False + + +def _companion_extensions(profile: dict, seed_name: str) -> set[str]: + """Extensions the profile declares beside a free-named BIOS entry. + + PCSX2 reads `.rom1` or the BIOS path with its extension replaced + (`.rom1`), and likewise nvm and mec (BiosTools.cpp:214-229, + CDVD.cpp:160-195). A profile states that by naming the companions after + its BIOS entry: ps2-0230a-20080220.rom1 beside ps2-0230a-20080220.bin. + """ + if _companion_of(profile, seed_name)[0]: + return set() + stem = seed_name.rsplit(".", 1)[0].lower() + exts: set[str] = set() + for entry in profile.get("files", []): + other = str(entry.get("name", "")).lower() + if other != seed_name.lower() and other.startswith(stem + "."): + exts.add(other[len(stem) + 1:]) + return exts + + +def _companions( + image_path: str, image_name: str, extensions: set[str], files_db: dict +) -> list[tuple[str, dict]]: + """Files beside a scanned image that the core opens as its companions. + + Each is named as the core spells it: PCSX2 stats `.rom1`, then the + BIOS path with its extension replaced by `rom1`, both case-sensitive on + Linux (BiosTools.cpp:214-229). SCPH-70004.ROM1 as stored is never found + beside SCPH-70004.BIN, SCPH-70004.rom1 is. + """ + if not extensions: + return [] + directory = image_path.rsplit("/", 1)[0] + "/" + stem = image_name.rsplit(".", 1)[0] + spelled = {f"{image_name}.{ext}".lower(): f"{image_name}.{ext}" for ext in extensions} + spelled.update({f"{stem}.{ext}".lower(): f"{stem}.{ext}" for ext in extensions}) + return sorted( + (sha1, {**entry, "name": spelled[str(entry.get("name", "")).lower()]}) + for sha1, entry in _files_by_directory(files_db).get(directory, ()) + if str(entry.get("name", "")).lower() in spelled + ) + + +# The database a directory index was built from, with the index: one walk +# per database instead of one per scanned image (1 023 walks of 19 041 +# entries in verify --all). +_DIRECTORY_INDEX: tuple[dict, dict[str, list[tuple[str, dict]]]] | None = None + + +def _files_by_directory(files_db: dict) -> dict[str, list[tuple[str, dict]]]: + global _DIRECTORY_INDEX + if _DIRECTORY_INDEX is None or _DIRECTORY_INDEX[0] is not files_db: + index: dict[str, list[tuple[str, dict]]] = {} + for sha1, entry in files_db.items(): + directory = entry.get("path", "").rsplit("/", 1)[0] + "/" + index.setdefault(directory, []).append((sha1, entry)) + _DIRECTORY_INDEX = (files_db, index) + return _DIRECTORY_INDEX[1] diff --git a/scripts/packs/manifestbuild.py b/scripts/packs/manifestbuild.py index 04710f211..34aae4d03 100644 --- a/scripts/packs/manifestbuild.py +++ b/scripts/packs/manifestbuild.py @@ -21,12 +21,8 @@ from packs.datatrees import ( pack_markers, tree_readers, ) -from packs.extras import ( - collect_emulator_extras, - extra_region_key, - save_entry_fields, - save_manifest_dest, -) +from packs.extras import collect_emulator_extras +from packs.extraplace import extra_region_key, save_entry_fields, save_manifest_dest from packs.manifestcores import ( downloaded_cores, manifest_core_entries, diff --git a/scripts/packs/manifestcores.py b/scripts/packs/manifestcores.py index 07ea224bf..443a12848 100644 --- a/scripts/packs/manifestcores.py +++ b/scripts/packs/manifestcores.py @@ -12,16 +12,15 @@ from model.alternatives import core_file_spares from model.declarations import OUTER_ROOTS, ROMS_ROOT, declared_root from model.profiles import core_key_index, upstream_profile_index from model.targets import list_available_targets, load_target_config -from packs.extras import ( - ExtraResolver, +from packs.extraresolver import ExtraResolver +from packs.extraplace import ( detect_extras_prefix, - extra_system_ids, extra_full_destination, extra_region_key, - platform_region_groups, save_entry_fields, save_manifest_dest, ) +from packs.extraregions import extra_system_ids, platform_region_groups from packs.manifestentry import ( ClaimContext, attach_claims, diff --git a/scripts/packs/manifestentry.py b/scripts/packs/manifestentry.py index 7dbcfcdbd..a13db412b 100644 --- a/scripts/packs/manifestentry.py +++ b/scripts/packs/manifestentry.py @@ -14,13 +14,13 @@ from model.declarations import OUTER_ROOTS, declared_root from model.profiles import profile_names from model.largefiles import asset_name, load_registered_paths, published_asset_name from packs.executable import ships_executable -from packs.extras import ( +from packs.extraplace import ( detect_extras_prefix, - extra_system_ids, extra_full_destination, extra_region_key, save_manifest_dest, ) +from packs.extraregions import extra_system_ids from resolve.packfiles import resolve_file from resolve.acceptance import validated_choice diff --git a/scripts/packs/manifestselect.py b/scripts/packs/manifestselect.py index 13ce792a1..a1e3a301c 100644 --- a/scripts/packs/manifestselect.py +++ b/scripts/packs/manifestselect.py @@ -21,13 +21,13 @@ from resolve import regions as resolve_regions from resolve import slot as slot_mod from model.systems import norm_system_id from core.paths import declared_destination -from packs.extras import ( +from packs.extraregions import ( kept_entries, serving_system_ids, extra_region_groups, - extra_region_key, system_spellings, ) +from packs.extraplace import extra_region_key @dataclass(frozen=True) diff --git a/scripts/packs/packplan.py b/scripts/packs/packplan.py index 68aa04499..8f92182b5 100644 --- a/scripts/packs/packplan.py +++ b/scripts/packs/packplan.py @@ -12,7 +12,8 @@ from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from packs import slots from packs.archive import PackRecord -from packs.extras import platform_region_groups, undeclared_report +from packs.extraregions import platform_region_groups +from packs.extras import undeclared_report from packs.naming import pack_narrowings, platform_pack_name from packs.packcounts import PackCounts from resolve import regions as resolve_regions, slot as slot_mod diff --git a/scripts/packs/platformcheck.py b/scripts/packs/platformcheck.py index e7f2f9cd4..3de8ae652 100644 --- a/scripts/packs/platformcheck.py +++ b/scripts/packs/platformcheck.py @@ -18,7 +18,7 @@ from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from packs import slots from packs.archive import PACK_DOCUMENTS -from packs.extras import platform_region_groups +from packs.extraregions import platform_region_groups from packs.integrity import same_members from packs.naming import pack_variant from packs.packhashes import native_hash_errors @@ -165,7 +165,7 @@ def _builder_extras( refuses, is left free, since the builder then places a core's file there: taken by the refused file, that core file was never compared. """ - from packs.extras import ExtraResolver, hidden_extras + from packs.extraresolver import ExtraResolver, hidden_extras from resolve.validation import build_validation_index from resolve.acceptance import destination_owners diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index be280d32b..f5d37b37a 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -17,11 +17,9 @@ from packs.archive import ( ) from packs.declsettle import DeclarationJudge from packs.naming import system_display_name -from packs.extras import ( - ExtraResolver, - collect_emulator_extras, - extras_for_systems as _extras_for_systems, -) +from packs.extraresolver import ExtraResolver +from packs.extras import collect_emulator_extras +from packs.extraregions import extras_for_systems as _extras_for_systems from packs.naming import file_name_part, pack_narrowings, platform_pack_stem from packs.packcounts import PackCounts, pack_counts from packs.platformreport import print_platform_pack, print_split_packs diff --git a/scripts/packs/platformzip.py b/scripts/packs/platformzip.py index 136008882..290eddc75 100644 --- a/scripts/packs/platformzip.py +++ b/scripts/packs/platformzip.py @@ -28,13 +28,9 @@ from packs.archive import ( ) from packs.datatrees import core_data_trees, data_directory_members, pack_markers from packs.declsettle import DeclarationJudge, Settlement -from packs.extras import ( - collect_emulator_extras, - detect_extras_prefix, - extra_full_destination, - extra_region_key, - extras_for_systems as _extras_for_systems, -) +from packs.extras import collect_emulator_extras +from packs.extraplace import detect_extras_prefix, extra_full_destination, extra_region_key +from packs.extraregions import extras_for_systems as _extras_for_systems from packs.packplan import PlatformPlan from packs.paths import flat_arcname, platform_destination, save_layout from packs.readme import build_agnostic_rename_readme, build_readme, save_place diff --git a/scripts/packs/slots.py b/scripts/packs/slots.py index 9f96c5324..95813f418 100644 --- a/scripts/packs/slots.py +++ b/scripts/packs/slots.py @@ -24,7 +24,7 @@ from resolve.validation import content_alternatives from resolve.entryscope import outside_gap_scope, read_from_save_dir, with_archive_members if TYPE_CHECKING: - from packs.extras import ExtraPlacement + from packs.extraplace import ExtraPlacement # A profile entry can prove a slot without declaring a hash: Dolphin names no @@ -165,7 +165,7 @@ def profile_claims( standalone_cores = standalone_cores or PlatformLaunches() placement = None if config is not None: - from packs.extras import ExtraPlacement + from packs.extraplace import ExtraPlacement placement = ExtraPlacement(config, base_dest, profiles) claims: list[Claim] = [] diff --git a/tests/test_agnostic_scan.py b/tests/test_agnostic_scan.py index cbba58ee3..eaee8a835 100644 --- a/tests/test_agnostic_scan.py +++ b/tests/test_agnostic_scan.py @@ -22,6 +22,7 @@ from pathlib import Path from model.profiles import load_emulator_profiles, emulator_profiles_cache from resolve.localfile import resolve_local_file from packs import extras as packextras +from packs import extraplace SIZE = 1024 @@ -292,7 +293,7 @@ class ArchivePrefixCopies(unittest.TestCase): ], } } - return packextras.archive_prefix_extras( + return extraplace.archive_prefix_extras( profiles, {"fbneo"}, {"neogeo.zip"}, set(), "", by_name ) @@ -313,7 +314,7 @@ class ArchivePrefixCopies(unittest.TestCase): "system": "arcade"}], } } - extras = packextras.archive_prefix_extras( + extras = extraplace.archive_prefix_extras( profiles, {"fbneo"}, {"neogeo.zip"}, {"fbneo/neogeo.zip"}, "", {"neogeo.zip": ["abc"]}, ) diff --git a/tests/test_agnostic_scope.py b/tests/test_agnostic_scope.py index 18de138f9..5c79f0395 100644 --- a/tests/test_agnostic_scope.py +++ b/tests/test_agnostic_scope.py @@ -22,7 +22,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class AgnosticScan(unittest.TestCase): def test_only_the_bios_directory_seeds_and_finds_keep_its_folder(self): - from packs.extras import agnostic_scan_extras + from packs.extrascan import agnostic_scan_extras with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() @@ -61,7 +61,7 @@ class AgnosticScan(unittest.TestCase): folder where another profile of the system resolves a hashed dump of that shape is the evidence, that folder only. """ - from packs.extras import agnostic_scan_extras + from packs.extrascan import agnostic_scan_extras with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 7fc42c678..4a505fd3c 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -36,7 +36,7 @@ from orchestrate import checks, consistency, results, runner from scripts.resolve import regionaudit, regions from scripts.resolve.localfile import resolve_local_file from scripts.core.ziptools import safe_extract_zip -from scripts.packs.extras import _emulator_region_group +from scripts.packs.extraregions import _emulator_region_group from scripts.packs.platformcheck import verify_pack_against_platform from scripts.packs.targets import generate_target_manifests @@ -1580,7 +1580,7 @@ class OneBaselineVerdict(unittest.TestCase): gives: a gitignored file absent from bios/ read as missing in verify while the pack shipped its cached release asset.""" for module, name in (("verify.py", "_resolve_for_platform"), - ("packs/extras.py", "_ships")): + ("packs/extraregions.py", "_ships")): source = script_source(module) function = next( node for node in ast.parse(source).body @@ -1889,7 +1889,7 @@ class RegionRegressions(unittest.TestCase): under none of its four systems: emulator mode grouped them and dropped pac-n1.bin for --region us, platform mode isolated each and kept it.""" - from packs.extras import extra_region_groups + from packs.extraregions import extra_region_groups profile = {"systems": ["nec-pc-engine", "nec-pc-engine-cd", "nec-supergrafx", "pioneer-laseractive"]} @@ -1911,7 +1911,7 @@ class RegionRegressions(unittest.TestCase): platform side. Emulator mode read only `system:`, so --emulator --region us kept the Japanese file --platform --region us dropped.""" from model.profiles import entry_system_ids - from packs.extras import emulator_region_drops, extra_region_groups + from packs.extraregions import emulator_region_drops, extra_region_groups profile = {"systems": ["sys-a", "sys-b"], "files": [ {"name": "us.bin", "systems": ["sys-a"], "region": ["north-america"]}, @@ -3634,7 +3634,7 @@ class ARegionDroppedExtraBlocksNothing(unittest.TestCase): def test_the_report_skips_what_the_region_pass_drops(self): from unittest import mock - from scripts.packs import extras as packextras + from scripts.packs import extraresolver with tempfile.TemporaryDirectory() as directory: other = Path(directory) / "FOO.ROM" @@ -3649,12 +3649,12 @@ class ARegionDroppedExtraBlocksNothing(unittest.TestCase): config = {"case_insensitive_fs": True, "base_destination": ""} def report(region_drops): - with mock.patch.object(packextras, "collect_emulator_extras", + with mock.patch.object(extraresolver, "collect_emulator_extras", return_value=extras), \ - mock.patch.object(packextras, "resolve_local_file", + mock.patch.object(extraresolver, "resolve_local_file", side_effect=lambda fe, *a, **k: ( copies[fe["name"]], "name_exact")): - return packextras.hidden_extras( + return extraresolver.hidden_extras( config, "emulators", {"files": {}}, {}, {}, None, region_drops ) @@ -5287,7 +5287,7 @@ class CompanionsComeFromADirectoryIndex(unittest.TestCase): """_companions walked the whole database per scanned image.""" def test_same_answer_one_walk(self): - from scripts.packs import extras as packextras + from scripts.packs import extrascan files_db = { "a": {"path": "bios/Sony/PS2/ps2.bin", "name": "ps2.bin"}, @@ -5295,10 +5295,10 @@ class CompanionsComeFromADirectoryIndex(unittest.TestCase): "c": {"path": "bios/Sony/PS2/ps2.nvm", "name": "ps2.nvm"}, "d": {"path": "bios/Other/ps2.nvm", "name": "ps2.nvm"}, } - found = packextras._companions("bios/Sony/PS2/ps2.bin", "ps2.bin", {"rom1", "nvm"}, files_db) + found = extrascan._companions("bios/Sony/PS2/ps2.bin", "ps2.bin", {"rom1", "nvm"}, files_db) self.assertEqual([sha1 for sha1, _ in found], ["b", "c"]) - index = packextras._files_by_directory(files_db) - self.assertIs(packextras._files_by_directory(files_db), index) + index = extrascan._files_by_directory(files_db) + self.assertIs(extrascan._files_by_directory(files_db), index) @@ -5693,7 +5693,7 @@ class BundledFilesAreNotToSource(unittest.TestCase): entry = {"name": "n64.psh", "required": True, "in_repo": True, "emulator": "daedalusx64", "category": "bios", "bundled": True} - with mock.patch("packs.extras.unplaceable_extras", return_value={}): + with mock.patch("packs.extraresolver.unplaceable_extras", return_value={}): packs_coverage._mark_unplaced({}, [entry], {}) self.assertFalse(entry["in_pack"]) self.assertIn("installed with its emulator", entry["omitted"]) @@ -6350,7 +6350,7 @@ class RommNeoGeoFoldersGetTheirBios(unittest.TestCase): # into neogeoaes/, and FBNeo's CPS3 sets already sat in colecovision/: # a system the platform lacks has no folder, and a mirror-only # folder attracts no system-less file. - from scripts.packs.extras import _slug_for + from scripts.packs.extraplace import _slug_for config_systems = {"arcade", "snk-neogeo-aes", "nintendo-ds"} sys_to_slug = {"arcade": "arcade", "snk-neogeo-aes": "neogeoaes", diff --git a/tests/test_bios_companions.py b/tests/test_bios_companions.py index 20e793968..a434c2638 100644 --- a/tests/test_bios_companions.py +++ b/tests/test_bios_companions.py @@ -15,7 +15,7 @@ import unittest from pathlib import Path import yaml -from packs.extras import _companion_extensions, _companions +from packs.extrascan import _companion_extensions, _companions REPO_ROOT = Path(__file__).resolve().parents[1] @@ -66,7 +66,7 @@ class Companions(unittest.TestCase): import os import tempfile - from packs.extras import agnostic_scan_extras + from packs.extrascan import agnostic_scan_extras profile = { "emulator": "PCSX2", "bios_mode": "agnostic", "files": [ @@ -117,7 +117,7 @@ class Companions(unittest.TestCase): import os import tempfile - from packs.extras import agnostic_scan_extras + from packs.extrascan import agnostic_scan_extras def profile(name: str, ext: str) -> dict: return {"emulator": name, "bios_mode": "agnostic", "files": [ diff --git a/tests/test_content_checks.py b/tests/test_content_checks.py index eb9a2347e..98f012876 100644 --- a/tests/test_content_checks.py +++ b/tests/test_content_checks.py @@ -23,6 +23,7 @@ from model.profiles import emulator_profiles_cache, load_emulator_profiles from resolve.content import content_fits, size_fits, size_refusal, _masked_sha1_verdict from resolve.localfile import resolve_local_file from packs import extras as packextras +from packs import extrascan from core.romdir import romdir_accepts, walk from resolve.validation import build_validation_index, check_file_validation @@ -354,7 +355,7 @@ class ScannerVerifyManifestAgree(unittest.TestCase): def test_emulator_pack_and_verify_expansion(self): demo = self.profiles["demo"] - expanded = packextras.expand_agnostic_entries( + expanded = extrascan.expand_agnostic_entries( demo["files"], "demo", demo, self.db, False, self.profiles, ) names = {f["name"] for f in expanded if f.get("agnostic_scan")} diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index 213bf810f..787e42419 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -314,7 +314,7 @@ class PackCarriesADirectory(DirectoryFixture): class UnansweredDirectoryDestination(unittest.TestCase): def test_a_directory_gap_is_named_by_its_path(self): - from packs.extras import extra_dest + from packs.extraplace import extra_dest tree = {"name": "registered/", "type": "directory", "path": "nand/system/Contents/registered/"} diff --git a/tests/test_e2e.py b/tests/test_e2e.py index b30964d0c..67f32228e 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -6604,7 +6604,7 @@ struct BurnDriver BurnDrvneogeo = { --region compared nothing.""" import hashlib - from packs.extras import platform_region_groups + from packs.extraregions import platform_region_groups files, by_name = {}, {} for name in ("core_us.bin", "core_jp.bin"): @@ -6642,7 +6642,7 @@ struct BurnDriver BurnDrvneogeo = { --region us pack kept the declared Japanese BIOS.""" import hashlib - from packs.extras import platform_region_groups + from packs.extraregions import platform_region_groups files, by_name = {}, {} for name in ("bios_U.sms", "bios_J.sms"): diff --git a/tests/test_hidden_extras.py b/tests/test_hidden_extras.py index 36228ad8d..4e5b6cfb3 100644 --- a/tests/test_hidden_extras.py +++ b/tests/test_hidden_extras.py @@ -43,7 +43,7 @@ class OneRule(unittest.TestCase): def test_builder_and_report_read_it(self): self.assertIn("placement_block(", script_source("packs/archive.py")) - for module in ("generate_pack.py", "packs/extras.py"): + for module in ("generate_pack.py", "packs/extraresolver.py"): source = script_source(module) self.assertIn("Placed(", source, module) self.assertIn(".block(", source, module) @@ -180,7 +180,7 @@ class TheReplayResolvesAsTheBuilder(unittest.TestCase): def test_an_unresolved_extra_blocks_nothing(self): from unittest import mock - from packs import extras as packextras + from packs import extraresolver extras = [ {"destination": "box.bin/inner.rom", "name": "inner.rom", @@ -196,8 +196,8 @@ class TheReplayResolvesAsTheBuilder(unittest.TestCase): ) placed: set[str] = set() - with mock.patch.object(packextras, "collect_emulator_extras", return_value=extras): - hidden = packextras.hidden_extras( + with mock.patch.object(extraresolver, "collect_emulator_extras", return_value=extras): + hidden = extraresolver.hidden_extras( {"systems": {}}, "emulators", {"files": {}}, {}, {}, placed=placed, resolver=Resolver(), ) diff --git a/tests/test_launcher_layer.py b/tests/test_launcher_layer.py index a72069eb7..e3a2cda47 100644 --- a/tests/test_launcher_layer.py +++ b/tests/test_launcher_layer.py @@ -468,9 +468,10 @@ class LauncherLayerTest(unittest.TestCase): self.assertIn( "find_undeclared_files(", inspect.getsource(packextras.undeclared_report) ) + extras_family = ("extras", "extraplace", "extrascan", "extraregions", "extraresolver") for name, source in ( ("generate_pack", script_source("generate_pack.py")), - ("packs.extras", inspect.getsource(packextras)), + *((f"packs.{module}", script_source(f"packs/{module}.py")) for module in extras_family), ("verify", script_source("verify.py")), ): with self.subTest(module=name): diff --git a/tests/test_mame_devices.py b/tests/test_mame_devices.py index 00ecc8e94..0e7c08706 100644 --- a/tests/test_mame_devices.py +++ b/tests/test_mame_devices.py @@ -626,7 +626,8 @@ class APickReadsTheEntrySystems(unittest.TestCase): self.assertTrue(entry_serves_systems({}, profile, ["snk-neogeo-mvs"])) def test_the_gap_report_and_the_extras_carry_them(self): - from packs.extras import collect_emulator_extras, extra_system_ids + from packs.extras import collect_emulator_extras + from packs.extraregions import extra_system_ids from packs.gaps import find_undeclared_files profile = { diff --git a/tests/test_pack_counts.py b/tests/test_pack_counts.py index fe0274194..f224374c4 100644 --- a/tests/test_pack_counts.py +++ b/tests/test_pack_counts.py @@ -669,7 +669,8 @@ class CoreCopiesKeepTheirCategory(unittest.TestCase): copies, game data, under core files.""" def test_a_copy_counts_as_its_entry_says(self): - from packs.extras import collect_emulator_extras, hidden_extras + from packs.extras import collect_emulator_extras + from packs.extraresolver import hidden_extras with tempfile.TemporaryDirectory() as tmp: held = Path(tmp) / "x.dat" diff --git a/tests/test_region.py b/tests/test_region.py index a9b86ab5f..249ffc3a0 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -16,7 +16,7 @@ from model import profiles as model_profiles from model.profiles import emulator_profiles_cache from model import region from resolve import regions as resolve_regions -from packs.extras import emulator_region_drops +from packs.extraregions import emulator_region_drops class TestVocabulary(unittest.TestCase): @@ -699,14 +699,14 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): def test_the_report_withdraws_what_the_builder_withdraws(self): from model import profiles as model_profiles from model.profiles import emulator_profiles_cache - from packs import extras as packs_extras + from packs import extraregions from packs import coverage tmp, root, db, config = self._fixture() try: emulator_profiles_cache.clear() profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) - groups, extra_dests = packs_extras.platform_region_groups( + groups, extra_dests = extraregions.platform_region_groups( config, config["systems"], str(root / "emulators"), db, "", profiles, ) @@ -798,16 +798,16 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): Every module is read, not only the two that once held a copy: the builder was split into several modules and a grouping can move with - it. packs/extras.py holds the two shared passes, platform and emulator. + it. packs/extraregions.py holds the two shared passes, platform and emulator. """ scripts = Path(__file__).resolve().parent.parent / "scripts" for path in sorted(scripts.rglob("*.py")): - if path == scripts / "packs" / "extras.py": + if path == scripts / "packs" / "extraregions.py": continue with self.subTest(module=path.name): self.assertNotIn( "region_groups.setdefault(", path.read_text(encoding="utf-8"), - "region grouping belongs to packextras: platform_region_groups " + "region grouping belongs to packs.extraregions: platform_region_groups " "or emulator_region_drops", ) @@ -817,7 +817,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): entered the site workflow's trigger paths for one function.""" source = script_source("verify.py") self.assertNotIn("from generate_pack import platform_region_groups", source) - self.assertIn("from packs.extras import platform_region_groups", source) + self.assertIn("from packs.extraregions import platform_region_groups", source) def test_emulator_report_keeps_what_the_emulator_pack_keeps(self): """O2EM: --region us left the Videopac BIOSes in the pack, not in the report.""" diff --git a/tests/test_region_agnostic_scan.py b/tests/test_region_agnostic_scan.py index d4dba731f..56cd2aaca 100644 --- a/tests/test_region_agnostic_scan.py +++ b/tests/test_region_agnostic_scan.py @@ -29,7 +29,7 @@ class ScanCopiesStay(unittest.TestCase): from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packs.extras import platform_region_groups + from packs.extraregions import platform_region_groups db = load_database("database.json") profiles = load_emulator_profiles("emulators") diff --git a/tests/test_region_groups.py b/tests/test_region_groups.py index 2837c8156..b8d25ab10 100644 --- a/tests/test_region_groups.py +++ b/tests/test_region_groups.py @@ -12,7 +12,7 @@ import tests import unittest from pathlib import Path -from packs.extras import extra_region_groups, system_spellings +from packs.extraregions import extra_region_groups, system_spellings REPO_ROOT = Path(__file__).resolve().parent.parent @@ -50,7 +50,7 @@ class TheEnterpriseKeepsItsRom(unittest.TestCase): from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packs.extras import platform_region_groups + from packs.extraregions import platform_region_groups db = load_database(str(REPO_ROOT / "database.json")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -113,7 +113,7 @@ class ALosingClaimIsKeyedLikeTheWinner(unittest.TestCase): from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packs.extras import platform_region_groups + from packs.extraregions import platform_region_groups previous = os.getcwd() os.chdir(REPO_ROOT) diff --git a/tests/test_region_held.py b/tests/test_region_held.py index bf8c6a2f9..af72d7197 100644 --- a/tests/test_region_held.py +++ b/tests/test_region_held.py @@ -17,7 +17,7 @@ import tempfile import unittest from pathlib import Path -from packs.extras import _ships +from packs.extraregions import _ships REPO_ROOT = Path(__file__).resolve().parents[1] @@ -91,7 +91,7 @@ class ADataDirectoryCopyIsHeld(unittest.TestCase): ) def test_emulator_entry_from_a_data_tree(self): - from packs.extras import _emulator_ships + from packs.extraregions import _emulator_ships from resolve.validation import build_validation_index profile = self.profiles["dolphin-mmjr2"] diff --git a/tests/test_region_required_only.py b/tests/test_region_required_only.py index b85f53e59..6553fd6d9 100644 --- a/tests/test_region_required_only.py +++ b/tests/test_region_required_only.py @@ -15,7 +15,7 @@ import ast import unittest from pathlib import Path -from packs.extras import platform_region_groups +from packs.extraregions import platform_region_groups REPO_ROOT = Path(__file__).resolve().parents[1] @@ -49,7 +49,7 @@ class EmulatorModeToo(unittest.TestCase): the optional US cards won the group, then --required-only removed them.""" def test_the_required_card_survives(self): - from packs.extras import emulator_region_drops + from packs.extraregions import emulator_region_drops profile = {"systems": ["nec-pc-engine"], "files": [ {"name": "syscard3.pce", "required": True, "region": ["japan"]}, diff --git a/tests/test_system_ids.py b/tests/test_system_ids.py index d373c0181..b45276d21 100644 --- a/tests/test_system_ids.py +++ b/tests/test_system_ids.py @@ -16,7 +16,8 @@ from pathlib import Path from model.systems import SYSTEM_ALIASES, norm_system_id from model.profiles import load_emulator_profiles -from packs.extras import _names_content, _slug_for +from packs.extras import _names_content +from packs.extraplace import _slug_for REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_system_pack_extras.py b/tests/test_system_pack_extras.py index c292c8046..ece3ea695 100644 --- a/tests/test_system_pack_extras.py +++ b/tests/test_system_pack_extras.py @@ -13,7 +13,7 @@ from tests.sources import script_source import unittest from pathlib import Path -from packs.extras import extras_for_systems as _extras_for_systems +from packs.extraregions import extras_for_systems as _extras_for_systems REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index 7014a1428..46e11ae67 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -450,7 +450,7 @@ class ASystemReportCountsTheClaimsThePackCounts(unittest.TestCase): read only the entry's own system.""" def test_a_claim_riding_on_an_entry_selects_it(self): - from packs.extras import extras_for_systems, report_owned_by_systems + from packs.extraregions import extras_for_systems, report_owned_by_systems entry = { "name": "taitofx1.zip", "system": "arcade", "systems": ["arcade"], diff --git a/tests/test_unplaced_extras.py b/tests/test_unplaced_extras.py index f38ee6097..5fa384a4b 100644 --- a/tests/test_unplaced_extras.py +++ b/tests/test_unplaced_extras.py @@ -22,7 +22,7 @@ from model.platforms import _platform_config_cache, load_platform_config from model.profiles import load_emulator_profiles, emulator_profiles_cache from collection.indexes import build_indexes from packs import manifest as packs_manifest -from packs.extras import platform_region_groups +from packs.extraregions import platform_region_groups from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_validated_choice.py b/tests/test_validated_choice.py index a9c6afecc..ecda013c3 100644 --- a/tests/test_validated_choice.py +++ b/tests/test_validated_choice.py @@ -114,7 +114,7 @@ class ValidatedChoice(unittest.TestCase): ) } self.assertLessEqual({"build_platform_pack", "manifest_core_entries"}, resolvers) - extras = ast.parse((REPO_ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8")) + extras = ast.parse((REPO_ROOT / "scripts" / "packs" / "extraresolver.py").read_text(encoding="utf-8")) resolve = next( node for node in ast.walk(extras) if isinstance(node, ast.FunctionDef) and node.name == "resolve" @@ -143,7 +143,7 @@ class ValidatedChoice(unittest.TestCase): and getattr(call.func.value, "id", None) == "extra_resolver" for call in ast.walk(builder) )) - extras = ast.parse((REPO_ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8")) + extras = ast.parse((REPO_ROOT / "scripts" / "packs" / "extraresolver.py").read_text(encoding="utf-8")) resolve = next( node for node in ast.walk(extras) if isinstance(node, ast.FunctionDef) and node.name == "resolve" @@ -309,25 +309,24 @@ class AlternativesAreLookedUpBySlot(unittest.TestCase): def test_same_answer_one_pass_per_profile(self): from unittest import mock - from packs import extras as packextras - from resolve import acceptance as verdicts - from resolve.acceptance import extra_alternatives + from packs import extraresolver + from resolve import acceptance files = [{"name": "DUKE3D.GRP", "size": n} for n in (1, 2)] + [ {"name": "a.bin", "path": "dir/a.bin"}, {"name": "a.bin"}, "not an entry", ] profiles = {"raze": {"files": files}} - resolver = packextras.ExtraResolver({}, "bios", None, None, {}, None, profiles=profiles) + resolver = extraresolver.ExtraResolver({}, "bios", None, None, {}, None, profiles=profiles) extras = [ {"source_profile": "raze", "name": "DUKE3D.GRP"}, {"source_profile": "raze", "name": "a.bin", "source_path": "dir/a.bin"}, {"source_profile": "raze", "source_name": "a.bin", "name": "renamed"}, {"source_profile": "other", "name": "a.bin"}, ] - with mock.patch.object(verdicts, "slot_index", side_effect=verdicts.slot_index) as built: + with mock.patch.object(acceptance, "slot_index", side_effect=acceptance.slot_index) as built: for fe in extras: self.assertEqual(resolver.alternatives(fe), - extra_alternatives(fe, profiles)) + acceptance.extra_alternatives(fe, profiles)) self.assertEqual(built.call_count, 2) diff --git a/tests/test_validation_scope.py b/tests/test_validation_scope.py index 3ea88d4cd..ecf62ebfa 100644 --- a/tests/test_validation_scope.py +++ b/tests/test_validation_scope.py @@ -23,7 +23,8 @@ class ValidationIndexScope(unittest.TestCase): pattern = re.compile(r"build_validation_index\(\s*(emu_)?profiles\s*\)") for name in ( "verify.py", "generate_pack.py", "packs/integrity.py", "packs/packhashes.py", - "packs/platformcheck.py", "packs/extras.py", + "packs/platformcheck.py", "packs/extras.py", "packs/extraplace.py", "packs/extrascan.py", + "packs/extraregions.py", "packs/extraresolver.py", ): source = script_source(name) with self.subTest(module=name): diff --git a/wiki/adding-a-platform.md b/wiki/adding-a-platform.md index 3b00fe287..ab3d62e53 100644 --- a/wiki/adding-a-platform.md +++ b/wiki/adding-a-platform.md @@ -390,7 +390,7 @@ describes. `firmware_folder_flat: true` is set where the frontend reads a system's firmware folder without descending into it (RomM 5.4.1, `backend/handler/filesystem/base_handler.py:1002`, `recursive=False`). On such a platform, a core file whose destination has a -subfolder is left out of the pack (`nested` in `scripts/packs/extras.py`), since no +subfolder is left out of the pack (`nested` in `scripts/packs/extraplace.py`), since no core would receive it. ### Platform YAML header