From 2d79a2e1b52638ab4fd003df7eb692cb6c9a0fe5 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:41:42 +0100 Subject: [PATCH] refactor: split resolve_local_file stages --- scripts/acquire/fetch.py | 2 +- scripts/collection/aliases.py | 2 +- scripts/collection/scan.py | 2 +- scripts/packs/crossref.py | 2 +- scripts/packs/integrity.py | 2 +- scripts/probes/entries.py | 2 +- scripts/resolve/collisions.py | 3 +- scripts/resolve/localfile.py | 645 +------------------------ scripts/resolve/lookup.py | 257 ++++++++++ scripts/resolve/namestages.py | 406 ++++++++++++++++ scripts/scraper/romset_dat_importer.py | 2 +- tests/test_archive_recipes.py | 2 +- tests/test_casefold_cache.py | 5 +- tests/test_held_record.py | 2 +- tests/test_name_tiebreak.py | 4 +- tests/test_variant_copies.py | 2 +- 16 files changed, 690 insertions(+), 650 deletions(-) create mode 100644 scripts/resolve/lookup.py create mode 100644 scripts/resolve/namestages.py diff --git a/scripts/acquire/fetch.py b/scripts/acquire/fetch.py index 4d587f0ef..e713e1595 100644 --- a/scripts/acquire/fetch.py +++ b/scripts/acquire/fetch.py @@ -15,7 +15,7 @@ from acquire.placement import ACQUIRE_DIR, Placement, keep_acquired, place_file from core import upstream from core.hashing import parse_hash_list from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT -from resolve.localfile import held_record_for +from resolve.lookup import held_record_for from resolve.review import load_platform_hashes, load_profile_hashes MAX_DOWNLOAD = 100 * 1024 * 1024 # 100MB per file diff --git a/scripts/collection/aliases.py b/scripts/collection/aliases.py index d6468844a..eb34635eb 100644 --- a/scripts/collection/aliases.py +++ b/scripts/collection/aliases.py @@ -5,7 +5,7 @@ from __future__ import annotations from dataclasses import dataclass, field from collection.declared import Declarations, hash_values -from resolve.localfile import variant_base_name +from resolve.lookup import variant_base_name def _primary_names(entries: list) -> set[str]: diff --git a/scripts/collection/scan.py b/scripts/collection/scan.py index ab5e62cb4..c412e53da 100644 --- a/scripts/collection/scan.py +++ b/scripts/collection/scan.py @@ -7,7 +7,7 @@ from pathlib import Path from core.collectionfiles import collection_files from core.hashing import compute_hashes -from resolve.localfile import variant_base_name +from resolve.lookup import variant_base_name # Every digest database.json publishes per file, in the order compute_hashes # returns them. The schema requires all five, so a cache entry missing any of diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index 48df291ee..054fe58fc 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -21,7 +21,7 @@ from resolve.content import content_fits, name_match_size_ok from resolve.directories import directory_members from resolve.launcherlayer import LauncherLayer, held_record from resolve.layout import system_dir_path -from resolve.localfile import held_record_for +from resolve.lookup import held_record_for from resolve.ownership import foreign_tree, owner_tokens from resolve.launches import PlatformLaunches from resolve.standalone import platform_layouts diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index e83062405..fe33429cd 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -42,7 +42,7 @@ from packs.paths import flat_arcname from resolve.nativemode import reads_file_contents from resolve import regions as resolve_regions from packs import slots -from resolve.localfile import held_record_for +from resolve.lookup import held_record_for from resolve.packfiles import resolve_declaration, resolve_file from resolve.categories import BIOS, EntryCategories from resolve.gamedata import without_game_data diff --git a/scripts/probes/entries.py b/scripts/probes/entries.py index 43efa9da9..d0e2be0f8 100644 --- a/scripts/probes/entries.py +++ b/scripts/probes/entries.py @@ -38,7 +38,7 @@ def held_file(entry: dict, db: dict, root: Path) -> Path | None: def held_variants(entry: dict, db: dict, root: Path, primary: Path) -> list[Path]: """The .variants/ copies standing in for the primary held_file chose, in the checkout at root.""" - from resolve.localfile import variant_copies + from resolve.lookup import variant_copies hint = entry.get("path") if isinstance(entry.get("path"), str) else "" stored = primary.relative_to(root) if primary.is_relative_to(root) else primary diff --git a/scripts/resolve/collisions.py b/scripts/resolve/collisions.py index e22d1e220..910526849 100644 --- a/scripts/resolve/collisions.py +++ b/scripts/resolve/collisions.py @@ -9,7 +9,8 @@ from dataclasses import dataclass, field from core.hashing import compute_hashes, declared_hashes, parse_hash_list from core.paths import comparable_destination from core.ziptools import check_inside_zip -from resolve.localfile import resolve_local_file, variant_base_name +from resolve.localfile import resolve_local_file +from resolve.lookup import variant_base_name from model.database import record_at from model.declarations import declared_slot from resolve.packfiles import preferred_entries diff --git a/scripts/resolve/localfile.py b/scripts/resolve/localfile.py index edf4a10b4..1916a2a9e 100644 --- a/scripts/resolve/localfile.py +++ b/scripts/resolve/localfile.py @@ -4,53 +4,35 @@ from __future__ import annotations import functools import os -import re -import zipfile from collections.abc import Iterator -from dataclasses import dataclass -from typing import Any -from core.hashing import cut_md5_owner, md5_composite, parse_hash_list -from core.memo import DerivedView -from core.ziptools import check_inside_zip +from core.hashing import cut_md5_owner, parse_hash_list from model.database import get_mame_clone_map from model.profiles import CONTENT_CHECKS -from resolve.archives import ( - covering_archives, - holding_members, - warn_unreadable_archive, - contents_members, -) from resolve.content import ( adler32_fits, content_fits, declared_hash_verdict, - declares_shape, name_match_size_ok, shape_fits, ) from resolve.datadirs import data_dir_tail, resolve_in_data_dirs from resolve.ownership import ( affinity_tokens, - engine_tree, foreign_tree, - maker_folder, own_tree, owner_tokens, - other_maker, system_makers, ) - - -def _fold_names(by_name: dict) -> dict[str, list[str]]: - """A casefolded view of the by_name index.""" - folded: dict[str, list[str]] = {} - for name, sha1s in by_name.items(): - folded.setdefault(name.casefold(), []).extend(sha1s) - return folded - - -_casefold_name_index = DerivedView(_fold_names) +from resolve.lookup import Resolution, _Lookup, _entry_hint, _lookup, _record_match_status +from resolve.namestages import ( + _by_name, + _by_zip_contents, + _named_candidates, + _named_md5_match, + _ranked_mismatch, + _zipped_named, +) HASH_EXACT_RESOLUTION_STATUSES = frozenset( @@ -94,18 +76,6 @@ def _resolve_agnostic( return None -_VARIANT_SUFFIX = re.compile(r"\.[0-9a-f]{8}$") - - -def variant_base_name(name: str) -> str: - """The name a .variants/ copy stands in for: naomi2.zip.da79eca4 -> naomi2.zip. - - Only an eight-hex-digit suffix is a variant tag. A variant stored under - its plain name (.variants/aes.zip) already is that name. - """ - return _VARIANT_SUFFIX.sub("", name) - - def _rank_tail_candidates( candidates: list[str], start: int, tail: str, files_db: dict, owners: set[str], asker: frozenset[str] = frozenset(), @@ -152,259 +122,6 @@ def _rank_tail_candidates( ) -def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str]: - """Same-named candidates, the likeliest first. - - A name step without a tie-break took whichever path sorted first: the - TheXTech coin.ogg for Syobon Action, a Hurrican sound for ARMSX2, the - 1 MB CM-32L PCM ROM for ScummVM's 512 KB MT32_PCM.ROM. A size the entry - declares orders the candidates first (ordering rejects nothing, so an - unvalidated size keeps its informative status). Then the destination's - directories and the profile that asks name where its own copy lives. The - order is otherwise kept. - """ - if len(paths) < 2: - return paths - hint = dest_hint or file_entry.get("path") or file_entry.get("destination") or "" - wanted = affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "") - owners = owner_tokens(file_entry) - sized = declares_shape(file_entry) - - def score(path: str) -> tuple[int, bool, bool, bool, int]: - fits = 0 - if sized and os.path.exists(path): - fits = int(shape_fits(file_entry, path)) - tokens = affinity_tokens(path.rsplit("/", 1)[0]) - # The owner's own copy ranks above any shared tree segment: NetherSX2's - # shaders/common/ beat armsx2's own fxaa.fx on two directory tokens. - # Another emulator's own tree ranks below everything else. - # A game's folder under Game Engines/ holds that game's data: for a - # name-only match, a neutral copy goes first. hypseus-singe, - # flycast-dojo, lindbergh-loader and vvvvvv took C-Dogs' 98-line - # gamecontrollerdb.txt by index order. - return ( - fits, bool(owners & tokens), not foreign_tree(path, owners | wanted), - not engine_tree(path, owners | wanted), len(wanted & tokens), - ) - - return sorted(paths, key=score, reverse=True) - - -Resolution = tuple[str, str] - - -@dataclass(frozen=True) -class _Lookup: - """One entry as resolve_local_file reads it: its names and declared hashes.""" - - file_entry: dict - db: dict - dest_hint: str - name: str - zipped_file: str | None - names_to_try: list[str] - own_names: list[str] - md5_list: list[str] - sha1_candidates: list[str] - sha256_candidates: list[str] - crc_candidates: dict[str, None] - declared_size: Any - files_db: dict - by_name: dict - by_path_suffix: dict - composite_only: bool - - @property - def has_strong_hash(self) -> bool: - return bool( - self.sha1_candidates or self.sha256_candidates or self.md5_list or self.crc_candidates - ) - - -def _lookup_names(name: str, aliases: list, dest_hint: str) -> tuple[list[str], list[str]]: - """The names an entry answers to, and the part of them that is its own.""" - names_to_try = [name] + [a for a in aliases if a != name] - - # When name contains a path separator (e.g. "res/tilemap.bin"), also - # try the basename since by_name indexes filenames without directories - if "/" in name: - name_base = name.rsplit("/", 1)[-1] - if name_base and name_base not in names_to_try: - names_to_try.append(name_base) - - # When dest_hint contains a path, also try its basename as a name - # (handles emulator profiles where name: is descriptive and path: is - # the actual filename, e.g. name: "MDA font ROM", path: "mda.rom") - own_names = list(names_to_try) - if dest_hint: - hint_base = dest_hint.rsplit("/", 1)[-1] if "/" in dest_hint else dest_hint - if hint_base and hint_base not in names_to_try: - names_to_try.append(hint_base) - return names_to_try, own_names - - -def _lookup( - file_entry: dict, db: dict, dest_hint: str, md5_list: list[str], *, composite_only: bool -) -> _Lookup: - """Read the names and every declared hash of an entry once.""" - sha1 = file_entry.get("sha1") - name = file_entry.get("name", "") - names_to_try, own_names = _lookup_names(name, file_entry.get("aliases", []), dest_hint) - sha1_candidates = [ - str(value).strip().lower() - for value in (sha1 if isinstance(sha1, list) else [sha1] if sha1 else []) - if str(value).strip() - ] - sha256_raw = file_entry.get("sha256") - sha256_values = sha256_raw if isinstance(sha256_raw, list) else [sha256_raw] - sha256_candidates = [ - candidate.strip().lower() - for value in sha256_values - if value - for candidate in str(value).split(",") - if len(candidate.strip()) == 64 - ] - # One value, a list, or a comma-separated string, like the other hashes. - crc_values = file_entry.get("crc32") or [] - # Kept in the order declared, which is the order a lookup tries them. - crc_candidates = dict.fromkeys( - candidate.strip().lower().removeprefix("0x") - for value in (crc_values if isinstance(crc_values, list) else [crc_values]) - for candidate in str(value).split(",") - if candidate.strip() - ) - indexes = db.get("indexes", {}) - return _Lookup( - file_entry=file_entry, - db=db, - dest_hint=dest_hint, - name=name, - zipped_file=file_entry.get("zipped_file"), - names_to_try=names_to_try, - own_names=own_names, - md5_list=md5_list, - sha1_candidates=sha1_candidates, - sha256_candidates=sha256_candidates, - crc_candidates=crc_candidates, - declared_size=file_entry.get("size"), - files_db=db.get("files", {}), - by_name=indexes.get("by_name", {}), - by_path_suffix=indexes.get("by_path_suffix", {}), - composite_only=composite_only, - ) - - -def _record_match_status(q: _Lookup, match_sha1: str) -> str | None: - """Return hash evidence when a DB record satisfies every declaration.""" - entry = q.files_db.get(match_sha1) - if not entry: - return None - statuses: list[str] = [] - if q.sha1_candidates: - if match_sha1.lower() not in q.sha1_candidates: - return None - statuses.append("sha1_exact") - if q.sha256_candidates: - if str(entry.get("sha256", "")).lower() not in q.sha256_candidates: - return None - statuses.append("sha256_exact") - # With zipped_file the MD5 identifies the member, not the container. - if q.md5_list and not q.zipped_file: - actual_md5 = str(entry.get("md5", "")).lower() - if actual_md5 not in q.md5_list: - return None - statuses.append("md5_exact") - if q.crc_candidates: - if str(entry.get("crc32", "")).lower() not in q.crc_candidates: - return None - if q.declared_size is not None: - allowed_sizes = ( - q.declared_size if isinstance(q.declared_size, list) else [q.declared_size] - ) - if entry.get("size") not in allowed_sizes: - return None - statuses.append("crc32_exact") - return statuses[0] if statuses else None - - -def held_record_for(file_entry: dict, db: dict) -> str | None: - """The sha1 of a record every declared hash agrees with, from the database. - - The resolver's hash steps without the disk check, for a caller asking - whether the collection holds the content: sha1, sha256, md5 (a cut one - standing for the held md5 it starts), then crc32 only without a stronger - hash, bounded by the declared size. - """ - indexes = db.get("indexes", {}) - by_md5 = indexes.get("by_md5", {}) - md5_list = [ - (cut_md5_owner(value, by_md5) or value) if len(value) < 32 else value - for value in parse_hash_list(file_entry.get("md5")) - ] - q = _lookup( - file_entry, db, "", md5_list, - composite_only=file_entry.get("zip_digest") == "composite", - ) - candidates = [ - *q.sha1_candidates, - *(indexes.get("by_sha256", {}).get(v) for v in q.sha256_candidates), - ] - if not (q.zipped_file or q.composite_only): - candidates += [by_md5.get(v) for v in md5_list] - if not (q.sha1_candidates or q.sha256_candidates or q.md5_list or q.zipped_file): - candidates += [indexes.get("by_crc32", {}).get(v) for v in q.crc_candidates] - return next( - (c for c in candidates if c and c in q.files_db and _record_match_status(q, c)), - None, - ) - - -def variant_copies( - file_entry: dict, db: dict, primary: str, dest_hint: str = "" -) -> list[str]: - """The .variants/ copies that stand in for the primary an entry resolved to. - - A primary's alternates are filed in its own directory's .variants/ under - its file name or one the entry answers to: the same name under another - system (the PC-98 font.rom beside QUASI88's PC-88 one) is another file. - A copy passes the shape the entry's code checks and, when the entry - declares hashes, agrees with every one of them, as the resolver requires. - """ - q = _lookup( - file_entry, db, _entry_hint(file_entry, dest_hint), [ - (cut_md5_owner(value, db.get("indexes", {}).get("by_md5", {})) or value) - if len(value) < 32 else value - for value in parse_hash_list(file_entry.get("md5")) - ], - composite_only=file_entry.get("zip_digest") == "composite", - ) - primary = os.path.normpath(primary) - folder = os.path.dirname(primary) - # A primary that is itself a .variants/ copy shares that directory. - home = folder if os.path.basename(folder) == ".variants" else os.path.join(folder, ".variants") - primary_name = variant_base_name(os.path.basename(primary)) - names = [primary_name, *(n for n in q.names_to_try if n != primary_name)] - hashed = bool( - q.sha1_candidates or q.sha256_candidates or q.crc_candidates - or (q.md5_list and not q.zipped_file) - ) - out: list[str] = [] - for name in names: - for match_sha1 in q.by_name.get(name, ()): - path = q.files_db.get(match_sha1, {}).get("path", "") - if ( - os.path.dirname(os.path.normpath(path)) == home - and os.path.normpath(path) != primary - and variant_base_name(os.path.basename(path)) in names - and (not hashed or _record_match_status(q, match_sha1)) - and _name_size_ok(q, match_sha1) - and os.path.exists(path) - and path not in out - ): - out.append(path) - return out - - def _held_record(q: _Lookup, match_sha1: str) -> Resolution | None: """The record's path and evidence, when it satisfies the entry and is on disk.""" path = q.files_db[match_sha1]["path"] @@ -604,337 +321,6 @@ def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution return None -def _name_size_ok(q: _Lookup, match_sha1: str) -> bool: - """Whether a record found by name has the shape the entry's code checks.""" - record = q.files_db.get(match_sha1, {}) - return name_match_size_ok(q.file_entry, record.get("size")) and adler32_fits( - q.file_entry, record.get("path", ""), q.db - ) and content_fits(q.file_entry, record.get("path", "")) - - -def _exact_name_candidates(q: _Lookup) -> list[str]: - """The held files answering to the entry's names, exact casing.""" - candidates: list[str] = [] - # The entry's own names first, the destination's basename only when - # none of them answers. melonDS Nightly's dsi_nand.bin is read at - # dsi/nand.bin: with the DSi image absent from the checkout, the - # basename let the Wii nand.bin outrank the entry's own DSi variant. - # A name whose held file no declaration proves, while declarations - # of that name prove another dump beside it, means that dump: the - # DSi devkit boot ROMs filed as dsi_bios7.bin went to RetroBat. - by_proven_name = q.db.get("indexes", {}).get("by_proven_name", {}) - for tier in (q.own_names, q.names_to_try[len(q.own_names):]): - for try_name in tier: - for match_sha1 in ( - by_proven_name.get(try_name) or q.by_name.get(try_name, []) - ): - if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): - path = q.files_db[match_sha1]["path"] - if os.path.exists(path) and path not in candidates: - candidates.append(path) - if candidates: - break - return candidates - - -def _add_variant_primaries(q: _Lookup, candidates: list[str]) -> None: - """Add the primaries that variants answering the exact casing stand in for.""" - # Only variants answer the exact casing, but the primary they - # stand in for may be stored under another one: x1 asked for - # IPLROM.X1 and got Recalbox's second md5 while iplrom.x1, the - # dump every platform pins, sat in the same directory. A primary - # counts here only in a variant's own directory and under its own - # file name: an alias (iplrom.x1t names a font in System.dat) or - # another machine's font.rom is not that file. - homes = {p.split("/.variants/", 1)[0] for p in candidates} - folded = _casefold_name_index(q.by_name) - for try_name in q.names_to_try: - wanted = try_name.rsplit("/", 1)[-1].casefold() - for match_sha1 in folded.get(try_name.casefold(), []): - path = q.files_db.get(match_sha1, {}).get("path", "") - if ( - "/.variants/" not in path - and os.path.dirname(path) in homes - and os.path.basename(path).casefold() == wanted - and _name_size_ok(q, match_sha1) - and os.path.exists(path) - and path not in candidates - ): - candidates.append(path) - - -def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str]) -> None: - """Add the held files answering to the entry's names in another casing.""" - # Case-insensitive fallback: upstream platforms disagree on - # casing (VEC_MineStorm.vec vs VEC_Minestorm.vec). Two casings - # can name two contents (FONT.ROM and font.rom), so this only - # runs when no casing matches exactly, or when only another - # emulator's tree does: xm6typeg got XM6 Utility's synthesized - # SCSIINROM.DAT while the X68000 dump sat as scsiinrom.dat. - # Another casing in another emulator's tree proves nothing: - # reminiscence's music module reunion took skyline's - # zoneinfo/Indian/Reunion. - folded = _casefold_name_index(q.by_name) - for try_name in q.names_to_try: - for match_sha1 in folded.get(try_name.casefold(), []): - if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): - path = q.files_db[match_sha1]["path"] - if foreign_tree(path, owners): - continue - if os.path.exists(path) and path not in candidates: - candidates.append(path) - - -def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> list[str]: - """The candidates filed under the system's maker, or its shadowed aliases.""" - candidates = [p for p in candidates if not other_maker(p, makers, q.db)] - if candidates: - return candidates - # The name belongs to another maker's file here. An emulator - # of this system may still read it as an alias of one of its - # own files, an alias by_name leaves out because a primary - # already carries the name: QUASI88 reads DISK.ROM as - # n88sub.rom. - shadowed = q.db.get("indexes", {}).get("by_shadowed_alias", {}) - for try_name in q.own_names: - for match_sha1 in shadowed.get(try_name, []): - path = q.files_db.get(match_sha1, {}).get("path", "") - if ( - maker_folder(path, str(q.db.get("bios_dir") or "bios")) - in makers - and _name_size_ok(q, match_sha1) - and os.path.exists(path) - and path not in candidates - ): - candidates.append(path) - return candidates - - -def _choose_by_name( - q: _Lookup, - candidates: list[str], - owners: set[str], - exact_foreign: bool, - data_dir_registry: dict | None, -) -> Resolution | None: - """The best of the files a name step found, or the data directory's own.""" - if q.zipped_file: - candidates = [p for p in candidates if ".zip" in os.path.basename(p)] - members = q.file_entry.get("members") or contents_members(q.file_entry) - if members or (len(candidates) > 1 and q.name.casefold().endswith(".zip")): - # Another emulator's own copy takes no part in the ranking: - # Demul's naomi.zip holds more NAOMI BIOS rows than any MAME - # set and broke the superset the MAME cores were served. - candidates = [ - p for p in candidates if not foreign_tree(p, owners) - ] or candidates - if members: - candidates = holding_members(candidates, members) - elif len(candidates) > 1 and q.name.casefold().endswith(".zip"): - candidates = covering_archives(candidates) - candidates = _by_affinity(candidates, q.file_entry, q.dest_hint) - best = candidates[0] if candidates else "" - # A copy outside another emulator's tree comes first: the - # affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served - # upstream PCSX2 the patches.zip of ARMSX2. - candidates = [ - p for p in candidates if not foreign_tree(p, owners) - ] or candidates - primary = [p for p in candidates if "/.variants/" not in p] - if not (primary or candidates): - return None - chosen = primary[0] if primary else candidates[0] - # The best of them is another emulator's own copy, served or - # set aside: the name says nothing about this profile's file, - # and a data directory it reads may hold it. Dolphin got - # Dolphin-MMJR's codehandler.bin while data/dolphin-sys held - # its own, and blueMSX got the 16 KB RS232.ROM once msx-emu's - # 8 KB copy was set aside, while data/bluemsx held its own, - # and MSX2P.ROM of another dump once only msx-emu answered - # the exact casing. - if data_dir_registry and (exact_foreign or foreign_tree(best, owners)): - hit, _mismatch = resolve_in_data_dirs( - q.names_to_try, data_dir_registry, - functools.partial( - declared_hash_verdict, - has_strong_hash=False, - sha1_candidates=set(), - sha256_candidates=set(), - md5_list=[], - crc_candidates=set(), - zipped_file=q.zipped_file, - declared_size=q.declared_size, - file_entry=q.file_entry, - db=q.db, - ), - ) - if hit: - return hit - return chosen, "name_exact" - - -def _by_name( - q: _Lookup, makers: frozenset[str], data_dir_registry: dict | None -) -> tuple[Resolution | None, bool]: - """Any file with that name or alias (existence check). - - The second value says the name proved nothing, which makes the entry - unsourceable for the steps after this one. - """ - candidates = _exact_name_candidates(q) - if candidates and all("/.variants/" in p for p in candidates): - _add_variant_primaries(q, candidates) - owners = owner_tokens(q.file_entry) - # Only another emulator's tree answers the exact casing: what it - # holds there says nothing about this entry's file. - exact_foreign = bool(candidates) and all( - foreign_tree(p, owners) for p in candidates - ) - if not candidates or exact_foreign: - _add_casefold_candidates(q, candidates, owners) - # A platform entry names no profile, but a system that lists its - # cores says whose files it asks for. A name only another emulator's - # tree answers is no evidence, and the data directories hold those - # emulators' trees too: EmuELEC's VVVVVV data.zip was served xrick's - # archive of the same name, then xrick's data directory copy. - core_owners = { - token - for core in q.file_entry.get("platform_cores") or () - for token in affinity_tokens(str(core)) - } - if ( - not owners - and core_owners - and candidates - and all(foreign_tree(p, core_owners) for p in candidates) - ): - return None, True - if makers and candidates: - candidates = _same_maker(q, candidates, makers) - if not candidates: - return None, False - return _choose_by_name(q, candidates, owners, exact_foreign, data_dir_registry), False - - -def _named_candidates(q: _Lookup, makers: frozenset[str]) -> list[tuple[str, str, int | None]]: - """Every held file of the entry's names: path, md5, size.""" - named: list[tuple[str, str, int | None]] = [] - seen_paths = set() - for try_name in q.names_to_try: - for match_sha1 in q.by_name.get(try_name, []): - if match_sha1 in q.files_db: - entry = q.files_db[match_sha1] - path = entry["path"] - if os.path.exists(path) and path not in seen_paths: - seen_paths.add(path) - named.append( - (path, entry.get("md5", ""), entry.get("size")) - ) - - if q.zipped_file: - named = [c for c in named if ".zip" in os.path.basename(c[0])] - # Another maker's file is no mismatch of this one, it is another file. - named = [c for c in named if not other_maker(c[0], makers, q.db)] - # A size the emulator itself verifies settles a name collision, so a - # candidate that fits is preferred over one that does not: "ROM" answers - # both an Apple IIgs image and a Macintosh one. It ranks rather than - # excludes, because a present file of the wrong size is reported as - # present and untested, and dropping it would report it as absent. - sized = [ - c for c in named - if name_match_size_ok(q.file_entry, c[2]) and content_fits(q.file_entry, c[0]) - ] - if sized: - named = sized - return named - - -def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution | None: - """A named file whose md5, or archive composite, is a declared one. - - Sorts *named* in place for a composite-only entry, as the steps after - this one read it. - """ - md5_set = set(q.md5_list) - if not md5_set or q.sha1_candidates or q.sha256_candidates or q.crc_candidates: - return None - if q.composite_only: - named.sort(key=lambda c: "/.variants/" in c[0]) - for path, db_md5, _size in named: - if ".zip" in os.path.basename(path): - try: - composite = md5_composite(path).lower() - # A zipped_file md5 is the member's: one member of - # another name has the same composite, and Batocera - # looks the member up by name. - if composite in md5_set and ( - not q.zipped_file - or check_inside_zip(path, q.zipped_file, composite) == "ok" - ): - return path, "md5_composite_exact" - except (zipfile.BadZipFile, OSError) as exc: - warn_unreadable_archive(path, exc) - if db_md5.lower() in md5_set and not q.composite_only: - return path, "md5_exact" - return None - - -def _zipped_named( - q: _Lookup, named: list[tuple[str, str, int | None]], zipped_file: str -) -> Resolution | None: - """When zipped_file is set, only accept candidates that contain it.""" - valid = [] - for path, m, size in named: - try: - with zipfile.ZipFile(path) as zf: - inner_names = {n.casefold() for n in zf.namelist()} - if zipped_file.casefold() in inner_names: - valid.append((path, m, size)) - except (zipfile.BadZipFile, OSError) as exc: - warn_unreadable_archive(path, exc) - # The archive whose member carries the declared md5 is the one: - # neogeo.zip is held twice, each with its own sfix.sfix, and the - # first by name was returned as a mismatch while the other matched. - for path, _m, _size in sorted(valid, key=lambda c: "/.variants/" in c[0]): - if any(check_inside_zip(path, zipped_file, md5) == "ok" for md5 in q.md5_list): - return path, "zip_exact" - if valid: - primary = [c[0] for c in valid if "/.variants/" not in c[0]] - return (primary[0] if primary else valid[0][0]), "hash_mismatch" - # No candidate contains the zipped_file: fall through to step 5 - return None - - -def _ranked_mismatch(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution: - """The named file the entry would take, reported as a hash mismatch.""" - ordered = _by_affinity([c[0] for c in named], q.file_entry, q.dest_hint) - primary = [c for c in ordered if "/.variants/" not in c] - return (primary[0] if primary else ordered[0]), "hash_mismatch" - - -def _by_zip_contents(q: _Lookup, zip_contents: dict | None) -> Resolution | None: - """zipped_file content match via pre-built index. - - Last resort: matches inner ROM MD5 across ALL ZIPs in the repo, so only - used when name-based resolution failed entirely. - """ - if not ( - q.zipped_file - and q.md5_list - and zip_contents - and not (q.sha1_candidates or q.sha256_candidates or q.crc_candidates) - ): - return None - for md5_candidate in q.md5_list: - if md5_candidate in zip_contents: - zip_sha1 = zip_contents[md5_candidate] - if zip_sha1 in q.files_db: - path = q.files_db[zip_sha1]["path"] - if os.path.exists(path): - return path, "zip_exact" - return None - - def _by_mame_clone( q: _Lookup, zip_contents: dict | None, depth: int, data_dir_registry: dict | None ) -> Resolution | None: @@ -1015,17 +401,6 @@ def _resolve_layout( return next((found for found in answers if found[0] is not None), answers[0]) -def _entry_hint(file_entry: dict, dest_hint: str) -> str: - """The destination tail the collection indexes the entry under.""" - # A platform that hands each core a system directory of its own (MinUI's - # Bios//) writes that folder in front of the core's path. The tail - # the collection indexes is the core's path alone. - system_dir = file_entry.get("system_dir") - if system_dir and dest_hint.startswith(f"{system_dir}/"): - dest_hint = dest_hint[len(system_dir) + 1:] - return dest_hint - - def _name_as_hint(name: str, dest_hint: str) -> str: """A name written with its directory is the destination when no path is given.""" # gam4980/E.BIN resolved by its basename took another model's OS diff --git a/scripts/resolve/lookup.py b/scripts/resolve/lookup.py new file mode 100644 index 000000000..cb2e98e7d --- /dev/null +++ b/scripts/resolve/lookup.py @@ -0,0 +1,257 @@ +"""The lookup a resolution runs on: the database indexes, record matching and the variant copies of a name.""" + +from __future__ import annotations + +import os +import re +from dataclasses import dataclass +from typing import Any + +from core.hashing import cut_md5_owner, parse_hash_list +from resolve.content import adler32_fits, content_fits, name_match_size_ok + + +_VARIANT_SUFFIX = re.compile(r"\.[0-9a-f]{8}$") + + +def variant_base_name(name: str) -> str: + """The name a .variants/ copy stands in for: naomi2.zip.da79eca4 -> naomi2.zip. + + Only an eight-hex-digit suffix is a variant tag. A variant stored under + its plain name (.variants/aes.zip) already is that name. + """ + return _VARIANT_SUFFIX.sub("", name) + + +Resolution = tuple[str, str] + + +@dataclass(frozen=True) +class _Lookup: + """One entry as resolve_local_file reads it: its names and declared hashes.""" + + file_entry: dict + db: dict + dest_hint: str + name: str + zipped_file: str | None + names_to_try: list[str] + own_names: list[str] + md5_list: list[str] + sha1_candidates: list[str] + sha256_candidates: list[str] + crc_candidates: dict[str, None] + declared_size: Any + files_db: dict + by_name: dict + by_path_suffix: dict + composite_only: bool + + @property + def has_strong_hash(self) -> bool: + return bool( + self.sha1_candidates or self.sha256_candidates or self.md5_list or self.crc_candidates + ) + + +def _lookup_names(name: str, aliases: list, dest_hint: str) -> tuple[list[str], list[str]]: + """The names an entry answers to, and the part of them that is its own.""" + names_to_try = [name] + [a for a in aliases if a != name] + + # When name contains a path separator (e.g. "res/tilemap.bin"), also + # try the basename since by_name indexes filenames without directories + if "/" in name: + name_base = name.rsplit("/", 1)[-1] + if name_base and name_base not in names_to_try: + names_to_try.append(name_base) + + # When dest_hint contains a path, also try its basename as a name + # (handles emulator profiles where name: is descriptive and path: is + # the actual filename, e.g. name: "MDA font ROM", path: "mda.rom") + own_names = list(names_to_try) + if dest_hint: + hint_base = dest_hint.rsplit("/", 1)[-1] if "/" in dest_hint else dest_hint + if hint_base and hint_base not in names_to_try: + names_to_try.append(hint_base) + return names_to_try, own_names + + +def _lookup( + file_entry: dict, db: dict, dest_hint: str, md5_list: list[str], *, composite_only: bool +) -> _Lookup: + """Read the names and every declared hash of an entry once.""" + sha1 = file_entry.get("sha1") + name = file_entry.get("name", "") + names_to_try, own_names = _lookup_names(name, file_entry.get("aliases", []), dest_hint) + sha1_candidates = [ + str(value).strip().lower() + for value in (sha1 if isinstance(sha1, list) else [sha1] if sha1 else []) + if str(value).strip() + ] + sha256_raw = file_entry.get("sha256") + sha256_values = sha256_raw if isinstance(sha256_raw, list) else [sha256_raw] + sha256_candidates = [ + candidate.strip().lower() + for value in sha256_values + if value + for candidate in str(value).split(",") + if len(candidate.strip()) == 64 + ] + # One value, a list, or a comma-separated string, like the other hashes. + crc_values = file_entry.get("crc32") or [] + # Kept in the order declared, which is the order a lookup tries them. + crc_candidates = dict.fromkeys( + candidate.strip().lower().removeprefix("0x") + for value in (crc_values if isinstance(crc_values, list) else [crc_values]) + for candidate in str(value).split(",") + if candidate.strip() + ) + indexes = db.get("indexes", {}) + return _Lookup( + file_entry=file_entry, + db=db, + dest_hint=dest_hint, + name=name, + zipped_file=file_entry.get("zipped_file"), + names_to_try=names_to_try, + own_names=own_names, + md5_list=md5_list, + sha1_candidates=sha1_candidates, + sha256_candidates=sha256_candidates, + crc_candidates=crc_candidates, + declared_size=file_entry.get("size"), + files_db=db.get("files", {}), + by_name=indexes.get("by_name", {}), + by_path_suffix=indexes.get("by_path_suffix", {}), + composite_only=composite_only, + ) + + +def _record_match_status(q: _Lookup, match_sha1: str) -> str | None: + """Return hash evidence when a DB record satisfies every declaration.""" + entry = q.files_db.get(match_sha1) + if not entry: + return None + statuses: list[str] = [] + if q.sha1_candidates: + if match_sha1.lower() not in q.sha1_candidates: + return None + statuses.append("sha1_exact") + if q.sha256_candidates: + if str(entry.get("sha256", "")).lower() not in q.sha256_candidates: + return None + statuses.append("sha256_exact") + # With zipped_file the MD5 identifies the member, not the container. + if q.md5_list and not q.zipped_file: + actual_md5 = str(entry.get("md5", "")).lower() + if actual_md5 not in q.md5_list: + return None + statuses.append("md5_exact") + if q.crc_candidates: + if str(entry.get("crc32", "")).lower() not in q.crc_candidates: + return None + if q.declared_size is not None: + allowed_sizes = ( + q.declared_size if isinstance(q.declared_size, list) else [q.declared_size] + ) + if entry.get("size") not in allowed_sizes: + return None + statuses.append("crc32_exact") + return statuses[0] if statuses else None + + +def held_record_for(file_entry: dict, db: dict) -> str | None: + """The sha1 of a record every declared hash agrees with, from the database. + + The resolver's hash steps without the disk check, for a caller asking + whether the collection holds the content: sha1, sha256, md5 (a cut one + standing for the held md5 it starts), then crc32 only without a stronger + hash, bounded by the declared size. + """ + indexes = db.get("indexes", {}) + by_md5 = indexes.get("by_md5", {}) + md5_list = [ + (cut_md5_owner(value, by_md5) or value) if len(value) < 32 else value + for value in parse_hash_list(file_entry.get("md5")) + ] + q = _lookup( + file_entry, db, "", md5_list, + composite_only=file_entry.get("zip_digest") == "composite", + ) + candidates = [ + *q.sha1_candidates, + *(indexes.get("by_sha256", {}).get(v) for v in q.sha256_candidates), + ] + if not (q.zipped_file or q.composite_only): + candidates += [by_md5.get(v) for v in md5_list] + if not (q.sha1_candidates or q.sha256_candidates or q.md5_list or q.zipped_file): + candidates += [indexes.get("by_crc32", {}).get(v) for v in q.crc_candidates] + return next( + (c for c in candidates if c and c in q.files_db and _record_match_status(q, c)), + None, + ) + + +def variant_copies( + file_entry: dict, db: dict, primary: str, dest_hint: str = "" +) -> list[str]: + """The .variants/ copies that stand in for the primary an entry resolved to. + + A primary's alternates are filed in its own directory's .variants/ under + its file name or one the entry answers to: the same name under another + system (the PC-98 font.rom beside QUASI88's PC-88 one) is another file. + A copy passes the shape the entry's code checks and, when the entry + declares hashes, agrees with every one of them, as the resolver requires. + """ + q = _lookup( + file_entry, db, _entry_hint(file_entry, dest_hint), [ + (cut_md5_owner(value, db.get("indexes", {}).get("by_md5", {})) or value) + if len(value) < 32 else value + for value in parse_hash_list(file_entry.get("md5")) + ], + composite_only=file_entry.get("zip_digest") == "composite", + ) + primary = os.path.normpath(primary) + folder = os.path.dirname(primary) + # A primary that is itself a .variants/ copy shares that directory. + home = folder if os.path.basename(folder) == ".variants" else os.path.join(folder, ".variants") + primary_name = variant_base_name(os.path.basename(primary)) + names = [primary_name, *(n for n in q.names_to_try if n != primary_name)] + hashed = bool( + q.sha1_candidates or q.sha256_candidates or q.crc_candidates + or (q.md5_list and not q.zipped_file) + ) + out: list[str] = [] + for name in names: + for match_sha1 in q.by_name.get(name, ()): + path = q.files_db.get(match_sha1, {}).get("path", "") + if ( + os.path.dirname(os.path.normpath(path)) == home + and os.path.normpath(path) != primary + and variant_base_name(os.path.basename(path)) in names + and (not hashed or _record_match_status(q, match_sha1)) + and _name_size_ok(q, match_sha1) + and os.path.exists(path) + and path not in out + ): + out.append(path) + return out + + +def _name_size_ok(q: _Lookup, match_sha1: str) -> bool: + """Whether a record found by name has the shape the entry's code checks.""" + record = q.files_db.get(match_sha1, {}) + return name_match_size_ok(q.file_entry, record.get("size")) and adler32_fits( + q.file_entry, record.get("path", ""), q.db + ) and content_fits(q.file_entry, record.get("path", "")) + + +def _entry_hint(file_entry: dict, dest_hint: str) -> str: + """The destination tail the collection indexes the entry under.""" + # A platform that hands each core a system directory of its own (MinUI's + # Bios//) writes that folder in front of the core's path. The tail + # the collection indexes is the core's path alone. + system_dir = file_entry.get("system_dir") + if system_dir and dest_hint.startswith(f"{system_dir}/"): + dest_hint = dest_hint[len(system_dir) + 1:] + return dest_hint diff --git a/scripts/resolve/namestages.py b/scripts/resolve/namestages.py new file mode 100644 index 000000000..cc28e8553 --- /dev/null +++ b/scripts/resolve/namestages.py @@ -0,0 +1,406 @@ +"""The name stages of resolve_local_file: candidates by name, alias and case, an md5 under a name, zip contents.""" + +from __future__ import annotations + +import functools +import os +import zipfile + +from core.hashing import md5_composite +from core.memo import DerivedView +from core.ziptools import check_inside_zip +from resolve.archives import ( + contents_members, + covering_archives, + holding_members, + warn_unreadable_archive, +) +from resolve.content import ( + content_fits, + declared_hash_verdict, + declares_shape, + name_match_size_ok, + shape_fits, +) +from resolve.datadirs import resolve_in_data_dirs +from resolve.lookup import Resolution, _Lookup, _name_size_ok +from resolve.ownership import ( + affinity_tokens, + engine_tree, + foreign_tree, + maker_folder, + other_maker, + owner_tokens, +) + + +def _fold_names(by_name: dict) -> dict[str, list[str]]: + """A casefolded view of the by_name index.""" + folded: dict[str, list[str]] = {} + for name, sha1s in by_name.items(): + folded.setdefault(name.casefold(), []).extend(sha1s) + return folded + + +_casefold_name_index = DerivedView(_fold_names) + + +def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str]: + """Same-named candidates, the likeliest first. + + A name step without a tie-break took whichever path sorted first: the + TheXTech coin.ogg for Syobon Action, a Hurrican sound for ARMSX2, the + 1 MB CM-32L PCM ROM for ScummVM's 512 KB MT32_PCM.ROM. A size the entry + declares orders the candidates first (ordering rejects nothing, so an + unvalidated size keeps its informative status). Then the destination's + directories and the profile that asks name where its own copy lives. The + order is otherwise kept. + """ + if len(paths) < 2: + return paths + hint = dest_hint or file_entry.get("path") or file_entry.get("destination") or "" + wanted = affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "") + owners = owner_tokens(file_entry) + sized = declares_shape(file_entry) + + def score(path: str) -> tuple[int, bool, bool, bool, int]: + fits = 0 + if sized and os.path.exists(path): + fits = int(shape_fits(file_entry, path)) + tokens = affinity_tokens(path.rsplit("/", 1)[0]) + # The owner's own copy ranks above any shared tree segment: NetherSX2's + # shaders/common/ beat armsx2's own fxaa.fx on two directory tokens. + # Another emulator's own tree ranks below everything else. + # A game's folder under Game Engines/ holds that game's data: for a + # name-only match, a neutral copy goes first. hypseus-singe, + # flycast-dojo, lindbergh-loader and vvvvvv took C-Dogs' 98-line + # gamecontrollerdb.txt by index order. + return ( + fits, bool(owners & tokens), not foreign_tree(path, owners | wanted), + not engine_tree(path, owners | wanted), len(wanted & tokens), + ) + + return sorted(paths, key=score, reverse=True) + + +def _exact_name_candidates(q: _Lookup) -> list[str]: + """The held files answering to the entry's names, exact casing.""" + candidates: list[str] = [] + # The entry's own names first, the destination's basename only when + # none of them answers. melonDS Nightly's dsi_nand.bin is read at + # dsi/nand.bin: with the DSi image absent from the checkout, the + # basename let the Wii nand.bin outrank the entry's own DSi variant. + # A name whose held file no declaration proves, while declarations + # of that name prove another dump beside it, means that dump: the + # DSi devkit boot ROMs filed as dsi_bios7.bin went to RetroBat. + by_proven_name = q.db.get("indexes", {}).get("by_proven_name", {}) + for tier in (q.own_names, q.names_to_try[len(q.own_names):]): + for try_name in tier: + for match_sha1 in ( + by_proven_name.get(try_name) or q.by_name.get(try_name, []) + ): + if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + path = q.files_db[match_sha1]["path"] + if os.path.exists(path) and path not in candidates: + candidates.append(path) + if candidates: + break + return candidates + + +def _add_variant_primaries(q: _Lookup, candidates: list[str]) -> None: + """Add the primaries that variants answering the exact casing stand in for.""" + # Only variants answer the exact casing, but the primary they + # stand in for may be stored under another one: x1 asked for + # IPLROM.X1 and got Recalbox's second md5 while iplrom.x1, the + # dump every platform pins, sat in the same directory. A primary + # counts here only in a variant's own directory and under its own + # file name: an alias (iplrom.x1t names a font in System.dat) or + # another machine's font.rom is not that file. + homes = {p.split("/.variants/", 1)[0] for p in candidates} + folded = _casefold_name_index(q.by_name) + for try_name in q.names_to_try: + wanted = try_name.rsplit("/", 1)[-1].casefold() + for match_sha1 in folded.get(try_name.casefold(), []): + path = q.files_db.get(match_sha1, {}).get("path", "") + if ( + "/.variants/" not in path + and os.path.dirname(path) in homes + and os.path.basename(path).casefold() == wanted + and _name_size_ok(q, match_sha1) + and os.path.exists(path) + and path not in candidates + ): + candidates.append(path) + + +def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str]) -> None: + """Add the held files answering to the entry's names in another casing.""" + # Case-insensitive fallback: upstream platforms disagree on + # casing (VEC_MineStorm.vec vs VEC_Minestorm.vec). Two casings + # can name two contents (FONT.ROM and font.rom), so this only + # runs when no casing matches exactly, or when only another + # emulator's tree does: xm6typeg got XM6 Utility's synthesized + # SCSIINROM.DAT while the X68000 dump sat as scsiinrom.dat. + # Another casing in another emulator's tree proves nothing: + # reminiscence's music module reunion took skyline's + # zoneinfo/Indian/Reunion. + folded = _casefold_name_index(q.by_name) + for try_name in q.names_to_try: + for match_sha1 in folded.get(try_name.casefold(), []): + if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + path = q.files_db[match_sha1]["path"] + if foreign_tree(path, owners): + continue + if os.path.exists(path) and path not in candidates: + candidates.append(path) + + +def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> list[str]: + """The candidates filed under the system's maker, or its shadowed aliases.""" + candidates = [p for p in candidates if not other_maker(p, makers, q.db)] + if candidates: + return candidates + # The name belongs to another maker's file here. An emulator + # of this system may still read it as an alias of one of its + # own files, an alias by_name leaves out because a primary + # already carries the name: QUASI88 reads DISK.ROM as + # n88sub.rom. + shadowed = q.db.get("indexes", {}).get("by_shadowed_alias", {}) + for try_name in q.own_names: + for match_sha1 in shadowed.get(try_name, []): + path = q.files_db.get(match_sha1, {}).get("path", "") + if ( + maker_folder(path, str(q.db.get("bios_dir") or "bios")) + in makers + and _name_size_ok(q, match_sha1) + and os.path.exists(path) + and path not in candidates + ): + candidates.append(path) + return candidates + + +def _choose_by_name( + q: _Lookup, + candidates: list[str], + owners: set[str], + exact_foreign: bool, + data_dir_registry: dict | None, +) -> Resolution | None: + """The best of the files a name step found, or the data directory's own.""" + if q.zipped_file: + candidates = [p for p in candidates if ".zip" in os.path.basename(p)] + members = q.file_entry.get("members") or contents_members(q.file_entry) + if members or (len(candidates) > 1 and q.name.casefold().endswith(".zip")): + # Another emulator's own copy takes no part in the ranking: + # Demul's naomi.zip holds more NAOMI BIOS rows than any MAME + # set and broke the superset the MAME cores were served. + candidates = [ + p for p in candidates if not foreign_tree(p, owners) + ] or candidates + if members: + candidates = holding_members(candidates, members) + elif len(candidates) > 1 and q.name.casefold().endswith(".zip"): + candidates = covering_archives(candidates) + candidates = _by_affinity(candidates, q.file_entry, q.dest_hint) + best = candidates[0] if candidates else "" + # A copy outside another emulator's tree comes first: the + # affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served + # upstream PCSX2 the patches.zip of ARMSX2. + candidates = [ + p for p in candidates if not foreign_tree(p, owners) + ] or candidates + primary = [p for p in candidates if "/.variants/" not in p] + if not (primary or candidates): + return None + chosen = primary[0] if primary else candidates[0] + # The best of them is another emulator's own copy, served or + # set aside: the name says nothing about this profile's file, + # and a data directory it reads may hold it. Dolphin got + # Dolphin-MMJR's codehandler.bin while data/dolphin-sys held + # its own, and blueMSX got the 16 KB RS232.ROM once msx-emu's + # 8 KB copy was set aside, while data/bluemsx held its own, + # and MSX2P.ROM of another dump once only msx-emu answered + # the exact casing. + if data_dir_registry and (exact_foreign or foreign_tree(best, owners)): + hit, _mismatch = resolve_in_data_dirs( + q.names_to_try, data_dir_registry, + functools.partial( + declared_hash_verdict, + has_strong_hash=False, + sha1_candidates=set(), + sha256_candidates=set(), + md5_list=[], + crc_candidates=set(), + zipped_file=q.zipped_file, + declared_size=q.declared_size, + file_entry=q.file_entry, + db=q.db, + ), + ) + if hit: + return hit + return chosen, "name_exact" + + +def _by_name( + q: _Lookup, makers: frozenset[str], data_dir_registry: dict | None +) -> tuple[Resolution | None, bool]: + """Any file with that name or alias (existence check). + + The second value says the name proved nothing, which makes the entry + unsourceable for the steps after this one. + """ + candidates = _exact_name_candidates(q) + if candidates and all("/.variants/" in p for p in candidates): + _add_variant_primaries(q, candidates) + owners = owner_tokens(q.file_entry) + # Only another emulator's tree answers the exact casing: what it + # holds there says nothing about this entry's file. + exact_foreign = bool(candidates) and all( + foreign_tree(p, owners) for p in candidates + ) + if not candidates or exact_foreign: + _add_casefold_candidates(q, candidates, owners) + # A platform entry names no profile, but a system that lists its + # cores says whose files it asks for. A name only another emulator's + # tree answers is no evidence, and the data directories hold those + # emulators' trees too: EmuELEC's VVVVVV data.zip was served xrick's + # archive of the same name, then xrick's data directory copy. + core_owners = { + token + for core in q.file_entry.get("platform_cores") or () + for token in affinity_tokens(str(core)) + } + if ( + not owners + and core_owners + and candidates + and all(foreign_tree(p, core_owners) for p in candidates) + ): + return None, True + if makers and candidates: + candidates = _same_maker(q, candidates, makers) + if not candidates: + return None, False + return _choose_by_name(q, candidates, owners, exact_foreign, data_dir_registry), False + + +def _named_candidates(q: _Lookup, makers: frozenset[str]) -> list[tuple[str, str, int | None]]: + """Every held file of the entry's names: path, md5, size.""" + named: list[tuple[str, str, int | None]] = [] + seen_paths = set() + for try_name in q.names_to_try: + for match_sha1 in q.by_name.get(try_name, []): + if match_sha1 in q.files_db: + entry = q.files_db[match_sha1] + path = entry["path"] + if os.path.exists(path) and path not in seen_paths: + seen_paths.add(path) + named.append( + (path, entry.get("md5", ""), entry.get("size")) + ) + + if q.zipped_file: + named = [c for c in named if ".zip" in os.path.basename(c[0])] + # Another maker's file is no mismatch of this one, it is another file. + named = [c for c in named if not other_maker(c[0], makers, q.db)] + # A size the emulator itself verifies settles a name collision, so a + # candidate that fits is preferred over one that does not: "ROM" answers + # both an Apple IIgs image and a Macintosh one. It ranks rather than + # excludes, because a present file of the wrong size is reported as + # present and untested, and dropping it would report it as absent. + sized = [ + c for c in named + if name_match_size_ok(q.file_entry, c[2]) and content_fits(q.file_entry, c[0]) + ] + if sized: + named = sized + return named + + +def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution | None: + """A named file whose md5, or archive composite, is a declared one. + + Sorts *named* in place for a composite-only entry, as the steps after + this one read it. + """ + md5_set = set(q.md5_list) + if not md5_set or q.sha1_candidates or q.sha256_candidates or q.crc_candidates: + return None + if q.composite_only: + named.sort(key=lambda c: "/.variants/" in c[0]) + for path, db_md5, _size in named: + if ".zip" in os.path.basename(path): + try: + composite = md5_composite(path).lower() + # A zipped_file md5 is the member's: one member of + # another name has the same composite, and Batocera + # looks the member up by name. + if composite in md5_set and ( + not q.zipped_file + or check_inside_zip(path, q.zipped_file, composite) == "ok" + ): + return path, "md5_composite_exact" + except (zipfile.BadZipFile, OSError) as exc: + warn_unreadable_archive(path, exc) + if db_md5.lower() in md5_set and not q.composite_only: + return path, "md5_exact" + return None + + +def _zipped_named( + q: _Lookup, named: list[tuple[str, str, int | None]], zipped_file: str +) -> Resolution | None: + """When zipped_file is set, only accept candidates that contain it.""" + valid = [] + for path, m, size in named: + try: + with zipfile.ZipFile(path) as zf: + inner_names = {n.casefold() for n in zf.namelist()} + if zipped_file.casefold() in inner_names: + valid.append((path, m, size)) + except (zipfile.BadZipFile, OSError) as exc: + warn_unreadable_archive(path, exc) + # The archive whose member carries the declared md5 is the one: + # neogeo.zip is held twice, each with its own sfix.sfix, and the + # first by name was returned as a mismatch while the other matched. + for path, _m, _size in sorted(valid, key=lambda c: "/.variants/" in c[0]): + if any(check_inside_zip(path, zipped_file, md5) == "ok" for md5 in q.md5_list): + return path, "zip_exact" + if valid: + primary = [c[0] for c in valid if "/.variants/" not in c[0]] + return (primary[0] if primary else valid[0][0]), "hash_mismatch" + # No candidate contains the zipped_file: fall through to step 5 + return None + + +def _ranked_mismatch(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution: + """The named file the entry would take, reported as a hash mismatch.""" + ordered = _by_affinity([c[0] for c in named], q.file_entry, q.dest_hint) + primary = [c for c in ordered if "/.variants/" not in c] + return (primary[0] if primary else ordered[0]), "hash_mismatch" + + +def _by_zip_contents(q: _Lookup, zip_contents: dict | None) -> Resolution | None: + """zipped_file content match via pre-built index. + + Last resort: matches inner ROM MD5 across ALL ZIPs in the repo, so only + used when name-based resolution failed entirely. + """ + if not ( + q.zipped_file + and q.md5_list + and zip_contents + and not (q.sha1_candidates or q.sha256_candidates or q.crc_candidates) + ): + return None + for md5_candidate in q.md5_list: + if md5_candidate in zip_contents: + zip_sha1 = zip_contents[md5_candidate] + if zip_sha1 in q.files_db: + path = q.files_db[zip_sha1]["path"] + if os.path.exists(path): + return path, "zip_exact" + return None diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index e309b2f1b..4d04797ef 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -48,7 +48,7 @@ from model.platforms import load_platform_config from core.cli import add_repo_inputs, run_cli from model.database import load_database from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot -from resolve.localfile import variant_base_name +from resolve.lookup import variant_base_name from .base_scraper import BlobMismatchError, fetch_github_latest_version from .dat_fetch import fetch_pack, mame_label from .listxml import ( diff --git a/tests/test_archive_recipes.py b/tests/test_archive_recipes.py index b93f17657..05c6b93df 100644 --- a/tests/test_archive_recipes.py +++ b/tests/test_archive_recipes.py @@ -159,7 +159,7 @@ class HeldArchivesMatchTheirRecipes(unittest.TestCase): bios = REPO_ROOT / "bios" if not bios.is_dir() or not (REPO_ROOT / "recipes").is_dir(): self.skipTest("bios/ or recipes/ is not present") - from resolve.localfile import variant_base_name + from resolve.lookup import variant_base_name from core.hashing import md5_composite_of allowed = _allowed_members() diff --git a/tests/test_casefold_cache.py b/tests/test_casefold_cache.py index 1fbbd1090..56ab8326d 100644 --- a/tests/test_casefold_cache.py +++ b/tests/test_casefold_cache.py @@ -7,7 +7,7 @@ import tests import unittest from pathlib import Path -from resolve.localfile import _casefold_name_index +from resolve.namestages import _casefold_name_index REPO_ROOT = Path(__file__).resolve().parents[1] @@ -54,7 +54,8 @@ class APrimaryUnderAnotherCasing(unittest.TestCase): self.by_name.setdefault(name, []).append(sha1) def _resolve(self, name: str) -> str: - from resolve.localfile import _casefold_name_index, resolve_local_file + from resolve.namestages import _casefold_name_index + from resolve.localfile import resolve_local_file _casefold_name_index.clear() db = {"files": self.files, "indexes": {"by_name": self.by_name, "by_md5": {}, diff --git a/tests/test_held_record.py b/tests/test_held_record.py index aa6d2881a..90d97982a 100644 --- a/tests/test_held_record.py +++ b/tests/test_held_record.py @@ -18,7 +18,7 @@ from pathlib import Path from model.database import declared_records, record_for_hash, records_for_hash from packs.crossref import entry_source from packs.integrity import _repo_satisfies_declaration -from resolve.localfile import held_record_for +from resolve.lookup import held_record_for from resolve.acceptance import _variant_candidates SHA_A, SHA_B = "a" * 40, "b" * 40 diff --git a/tests/test_name_tiebreak.py b/tests/test_name_tiebreak.py index 16d4b4d01..02751bd88 100644 --- a/tests/test_name_tiebreak.py +++ b/tests/test_name_tiebreak.py @@ -13,7 +13,7 @@ import tempfile import unittest from pathlib import Path -from resolve.localfile import _by_affinity +from resolve.namestages import _by_affinity REPO_ROOT = Path(__file__).resolve().parents[1] @@ -36,7 +36,7 @@ class DeclaredSizeOrders(unittest.TestCase): class OwnerOutranksSharedTree(unittest.TestCase): def test_the_owners_copy_beats_two_matching_segments(self): """armsx2's fxaa.fx lost to NetherSX2's under shaders/common/.""" - from resolve.localfile import _by_affinity + from resolve.namestages import _by_affinity paths = [ "bios/Other/nethersx2/assets/shaders/common/fxaa.fx", diff --git a/tests/test_variant_copies.py b/tests/test_variant_copies.py index 4c88114c7..fb73a0f7e 100644 --- a/tests/test_variant_copies.py +++ b/tests/test_variant_copies.py @@ -16,7 +16,7 @@ import unittest from pathlib import Path from probes.entries import held_file, held_variants -from resolve.localfile import variant_copies +from resolve.lookup import variant_copies def _record(root: Path, path: str, body: bytes) -> tuple[str, dict]: