diff --git a/scripts/acquire/provenance.py b/scripts/acquire/provenance.py index f03403e37..42aef5001 100644 --- a/scripts/acquire/provenance.py +++ b/scripts/acquire/provenance.py @@ -13,7 +13,7 @@ from core.paths import REPO_ROOT from core.ziptools import is_archive_path, zip_members from model.dbpaths import on_disk from resolve.content import size_fits -from resolve.validation import installed_everywhere +from resolve.entryscope import installed_everywhere HASH_FIELDS = ("sha1", "md5", "sha256") diff --git a/scripts/exporter/doubled.py b/scripts/exporter/doubled.py index 8bd435280..85ad8862f 100644 --- a/scripts/exporter/doubled.py +++ b/scripts/exporter/doubled.py @@ -23,7 +23,7 @@ from model.declarations import declared_components from model.profiles import lists_files from resolve.collisions import accepted_by_all, find_collisions from resolve.content import size_fits -from resolve.validation import opens_by_name, outside_gap_scope +from resolve.entryscope import opens_by_name, outside_gap_scope def _names(entry: dict) -> set[str]: diff --git a/scripts/packs/bundledonly.py b/scripts/packs/bundledonly.py index 5678ed0b9..3a953b727 100644 --- a/scripts/packs/bundledonly.py +++ b/scripts/packs/bundledonly.py @@ -10,7 +10,7 @@ from model.platforms import load_platform_config from model.registry import list_registered_platforms from packs.consumers import FileConsumers from resolve.directories import expand_directory_entries -from resolve.validation import installed_everywhere +from resolve.entryscope import installed_everywhere def _entries(profile: dict, db: dict) -> list[dict]: diff --git a/scripts/packs/consumers.py b/scripts/packs/consumers.py index d0efc097c..aeb0f9a6f 100644 --- a/scripts/packs/consumers.py +++ b/scripts/packs/consumers.py @@ -13,7 +13,8 @@ from packs.supplemental import content_matches, declared_content, supplemental_l from resolve.archives import archive_entry from resolve.directories import expand_directory_entries from resolve.localfile import resolve_local_file -from resolve.validation import inner_rom_check, with_archive_members +from resolve.acceptance import inner_rom_check +from resolve.entryscope import with_archive_members def held_copy( diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py index 5afddec63..7e38d6976 100644 --- a/scripts/packs/coverage.py +++ b/scripts/packs/coverage.py @@ -33,12 +33,10 @@ from resolve.categories import BIOS, EntryCategories from resolve.cores import platform_scope_systems, resolve_platform_cores from resolve.launcherconfig import launcher_unproven from resolve.nativemode import digest_algorithm, platform_mode, reads_file_contents -from resolve.validation import ( - accepted_hashes, - build_validation_index, +from resolve.validation import accepted_hashes, build_validation_index, build_ground_truth +from resolve.acceptance import ( agnostic_substitute, baseline_verdict, - build_ground_truth, destination_owners, validated_choice, ) diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index a663ede45..48df291ee 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -25,7 +25,7 @@ from resolve.localfile import held_record_for from resolve.ownership import foreign_tree, owner_tokens from resolve.launches import PlatformLaunches from resolve.standalone import platform_layouts -from resolve.validation import ( +from resolve.entryscope import ( case_folded_slots, declaration_settles, installed_everywhere, @@ -127,7 +127,7 @@ def _record_needing_platforms( """ from resolve.cores import resolve_platform_cores from resolve.standalone import platform_launches - from resolve.validation import filter_files_by_mode + from resolve.entryscope import filter_files_by_mode missing = [ (emu_name, gap) for emu_name, data in report.items() diff --git a/scripts/packs/datatrees.py b/scripts/packs/datatrees.py index c75f9169a..a5fb3ed51 100644 --- a/scripts/packs/datatrees.py +++ b/scripts/packs/datatrees.py @@ -21,7 +21,7 @@ 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 from resolve.standalone import platform_layouts, platform_launches -from resolve.validation import deliverable, read_from_system_dir +from resolve.entryscope import deliverable, read_from_system_dir if TYPE_CHECKING: from typing_extensions import Unpack diff --git a/scripts/packs/declsettle.py b/scripts/packs/declsettle.py index c4627c17a..f753f41a3 100644 --- a/scripts/packs/declsettle.py +++ b/scripts/packs/declsettle.py @@ -6,7 +6,7 @@ from dataclasses import dataclass from resolve.nativemode import digest_algorithm, reads_file_contents from resolve.packfiles import resolve_declaration -from resolve.validation import agnostic_substitute, baseline_verdict, validated_choice +from resolve.acceptance import agnostic_substitute, baseline_verdict, validated_choice @dataclass(frozen=True) diff --git a/scripts/packs/emulatorcheck.py b/scripts/packs/emulatorcheck.py index e88f5b901..f7303e7be 100644 --- a/scripts/packs/emulatorcheck.py +++ b/scripts/packs/emulatorcheck.py @@ -32,12 +32,9 @@ from packs.verdicts import ( emulator_severity, storage_verdict, ) -from resolve.validation import ( - build_validation_index, - build_ground_truth, - validated_choice, - with_archive_members, -) +from resolve.validation import build_validation_index, build_ground_truth +from resolve.acceptance import validated_choice +from resolve.entryscope import with_archive_members # The repository's platforms wherever the script runs from, for library calls diff --git a/scripts/packs/emulatorentries.py b/scripts/packs/emulatorentries.py index fa2330fb7..07e954d1d 100644 --- a/scripts/packs/emulatorentries.py +++ b/scripts/packs/emulatorentries.py @@ -9,7 +9,7 @@ from packs.extras import emulator_required_spares, 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 -from resolve.validation import deliverable +from resolve.entryscope import deliverable @dataclass(frozen=True) diff --git a/scripts/packs/emulatorpack.py b/scripts/packs/emulatorpack.py index 0dab1a46d..1a91d76a8 100644 --- a/scripts/packs/emulatorpack.py +++ b/scripts/packs/emulatorpack.py @@ -46,11 +46,9 @@ from packs.naming import ( ) from resolve import packfiles as packresolve from resolve.packfiles import download_external, resolve_file -from resolve.validation import ( - build_validation_index, - validated_choice, - with_archive_members, -) +from resolve.validation import build_validation_index +from resolve.acceptance import validated_choice +from resolve.entryscope import with_archive_members if TYPE_CHECKING: from typing_extensions import Unpack diff --git a/scripts/packs/extras.py b/scripts/packs/extras.py index feb6a0d0b..01fa17d89 100644 --- a/scripts/packs/extras.py +++ b/scripts/packs/extras.py @@ -29,7 +29,7 @@ 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.validation import deliverable, read_by_build, read_from_save_dir, read_from_system_dir +from resolve.entryscope import deliverable, read_by_build, read_from_save_dir, 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 @@ -315,7 +315,7 @@ class ExtraResolver: 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.validation import slot_index + from resolve.acceptance import slot_index key = fe.get("source_profile") or "" index = self._slots.get(key) @@ -328,7 +328,7 @@ class ExtraResolver: 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.validation import core_size_refusal, validated_choice + from resolve.acceptance import core_size_refusal, validated_choice local_path, status = resolve_file( fe, self.db, self.bios_dir, self.zip_contents, @@ -2103,7 +2103,7 @@ def _ships( AmberELEC's bluemsx config.ini read as missing while the pack held it. """ from resolve.packfiles import resolve_declaration - from resolve.validation import baseline_verdict + from resolve.acceptance import baseline_verdict path, status = resolve_declaration( file_entry, db, "bios", zip_contents, data_registry, override, offline=True, @@ -2309,7 +2309,8 @@ def emulator_region_drops( """ from resolve import regions as resolve_regions from packs.paths import resolve_destination - from resolve.validation import build_validation_index, filter_files_by_mode + 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]]] = {} @@ -2402,7 +2403,8 @@ def _emulator_ships( held it. """ from resolve.packfiles import resolve_file - from resolve.validation import validated_choice, with_archive_members + 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", [])), diff --git a/scripts/packs/gaps.py b/scripts/packs/gaps.py index f8cb07a99..d0b81d7ba 100644 --- a/scripts/packs/gaps.py +++ b/scripts/packs/gaps.py @@ -20,18 +20,17 @@ from resolve.localfile import resolve_local_file from resolve.nativemode import hash_mismatch_excludes_file, platform_mode from resolve.ownership import foreign_tree, owner_tokens from resolve.standalone import platform_layouts, platform_launches -from resolve.validation import ( - parse_validation, +from resolve.validation import parse_validation +from resolve.entryscope import ( case_folded_slots, - core_size_refusal, declaration_settles, installed_with_emulator, outside_gap_scope, read_from_save_dir, - same_slot_entries, unread_on, with_archive_members, ) +from resolve.acceptance import core_size_refusal, same_slot_entries # Cross-reference: undeclared files used by cores diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index 66d0f07f5..e83062405 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -18,8 +18,11 @@ from packs.paths import MEDIA_MARKER, has_path_conflict from core.ziptools import build_zip_contents_index, is_archive_path, zip_members from core.ziptools import safe_member_parts from resolve.nativemode import digest_algorithm, platform_mode -from resolve.validation import ( - baseline_verdict, digest_verdict, inner_rom_check, inner_rom_data_check, +from resolve.acceptance import ( + baseline_verdict, + digest_verdict, + inner_rom_check, + inner_rom_data_check, ) from resolve.nativemode import hash_mismatch_excludes_file import sys @@ -547,7 +550,8 @@ def _builder_extras( there: taken by the refused file, that core file was never compared. """ from packs.extras import ExtraResolver, hidden_extras - from resolve.validation import build_validation_index, destination_owners + from resolve.validation import build_validation_index + from resolve.acceptance import destination_owners config, emu_profiles = expect.config, expect.emu_profiles data_registry = expect.opts.data_registry diff --git a/scripts/packs/manifest.py b/scripts/packs/manifest.py index 2495fab2e..b8b5343e1 100644 --- a/scripts/packs/manifest.py +++ b/scripts/packs/manifest.py @@ -60,10 +60,8 @@ from resolve.cores import platform_scope_systems, resolve_platform_cores as _pla from resolve.gamedata import GAME_DATA, is_game_data, platform_game_data, without_game_data from resolve.nativemode import platform_mode from resolve.packfiles import preferred_entries as _preferred_entries -from resolve.validation import ( - build_validation_index, - destination_owners, -) +from resolve.validation import build_validation_index +from resolve.acceptance import destination_owners if TYPE_CHECKING: from typing_extensions import Unpack diff --git a/scripts/packs/manifestentry.py b/scripts/packs/manifestentry.py index b1e1adeca..7dbcfcdbd 100644 --- a/scripts/packs/manifestentry.py +++ b/scripts/packs/manifestentry.py @@ -22,7 +22,7 @@ from packs.extras import ( save_manifest_dest, ) from resolve.packfiles import resolve_file -from resolve.validation import validated_choice +from resolve.acceptance import validated_choice # Manifest generation (JSON inventory for install.py) diff --git a/scripts/packs/paths.py b/scripts/packs/paths.py index fc5f98fdf..3153c7caa 100644 --- a/scripts/packs/paths.py +++ b/scripts/packs/paths.py @@ -10,7 +10,7 @@ from collections.abc import Iterable from dataclasses import dataclass from core.paths import comparable_destination, declared_destination, sanitize_pack_path -from resolve.validation import read_from_save_dir +from resolve.entryscope import read_from_save_dir def under_base(path: str, base_dest: str) -> str: diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index ea49e5e3c..166327132 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -67,13 +67,8 @@ from resolve.packfiles import ( preferred_entries as _preferred_entries, resolve_file, ) -from resolve.validation import ( - build_validation_index, - parse_validation, - destination_owners, - existence_discrepancy, - extra_alternatives, -) +from resolve.validation import build_validation_index, parse_validation +from resolve.acceptance import destination_owners, existence_discrepancy, extra_alternatives if TYPE_CHECKING: from typing_extensions import Unpack diff --git a/scripts/packs/slots.py b/scripts/packs/slots.py index 90a3bfb48..9f96c5324 100644 --- a/scripts/packs/slots.py +++ b/scripts/packs/slots.py @@ -20,12 +20,8 @@ from resolve.localfile import resolution_is_hash_exact, resolve_local_file from resolve.packfiles import preferred_entries from resolve.launches import PlatformLaunches from resolve.standalone import platform_layouts, platform_launches -from resolve.validation import ( - content_alternatives, - outside_gap_scope, - read_from_save_dir, - with_archive_members, -) +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 diff --git a/scripts/packs/verdicts.py b/scripts/packs/verdicts.py index 538c6786b..97908df63 100644 --- a/scripts/packs/verdicts.py +++ b/scripts/packs/verdicts.py @@ -5,13 +5,8 @@ from __future__ import annotations from core.hashing import compute_hashes, md5sum, parse_hash_list from core.ziptools import check_inside_zip from resolve.nativemode import SIZE_AND_ANY_HASH, reads_file_contents -from resolve.validation import ( - accepted_hashes, - check_file_validation, - existence_discrepancy, - frontend_digest_matches, - validated_choice, -) +from resolve.validation import accepted_hashes, check_file_validation +from resolve.acceptance import existence_discrepancy, frontend_digest_matches, validated_choice # Status model: aligned with Batocera BiosStatus (batocera-systems:967-969) diff --git a/scripts/probes/campaign.py b/scripts/probes/campaign.py index 16be386a5..879ae4bc8 100644 --- a/scripts/probes/campaign.py +++ b/scripts/probes/campaign.py @@ -329,7 +329,7 @@ class Campaign: return result.record def system_entries(self, profile: dict, system: str) -> list[tuple[int, dict]]: - from resolve.validation import filter_files_by_mode + from resolve.entryscope import filter_files_by_mode libretro = filter_files_by_mode(profile.get("files") or [], standalone=False) keep = {id(e) for e in libretro} diff --git a/scripts/probes/packprobe.py b/scripts/probes/packprobe.py index f60991d46..d474cca12 100644 --- a/scripts/probes/packprobe.py +++ b/scripts/probes/packprobe.py @@ -36,7 +36,7 @@ from probes.packlayout import ( ) from resolve.cores import resolve_platform_cores from resolve.standalone import platform_launches -from resolve.validation import filter_files_by_mode +from resolve.entryscope import filter_files_by_mode PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml" diff --git a/scripts/probes/regioncheck.py b/scripts/probes/regioncheck.py index 0359a3255..172af3874 100644 --- a/scripts/probes/regioncheck.py +++ b/scripts/probes/regioncheck.py @@ -18,7 +18,7 @@ from probes.content import Content, content_root, load_content, load_file, ready from probes.cores import cached_nightly from probes.entries import entry_dest, held_file, regions_of from probes.host import CONTENT_FILE, Unavailable, main_cache, run_when_idle -from resolve.validation import read_by_build +from resolve.entryscope import read_by_build VARIANTS = ("full", "own", "others", "pack") diff --git a/scripts/resolve/acceptance.py b/scripts/resolve/acceptance.py new file mode 100644 index 000000000..e6ae29396 --- /dev/null +++ b/scripts/resolve/acceptance.py @@ -0,0 +1,464 @@ +"""The verdict on a held file: the variant a check accepts, the frontend digest, the choice among owners.""" + +from __future__ import annotations + +import os +import zipfile +from collections.abc import Callable, Iterator, Mapping, Sequence +from typing import TYPE_CHECKING, TypedDict + +from core.hashing import compute_hashes, lists_hashes, md5_composite, parse_hash_list +from core.paths import BIOS_DIR +from core.ziptools import check_inside_zip, check_inside_zip_data +from model.database import records_for_hash +from resolve.content import content_fits, declared_content_checks, name_match_size_ok, shape_fits +from resolve.nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file +from resolve.validation import Refusal, check_file_validation + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def _platform_accepted(file_entry: dict, platform_digest: str) -> set[str]: + """The values of the digest the frontend compares that the entry declares.""" + declared = file_entry.get(platform_digest) or "" + if platform_digest == "md5": + return set(parse_hash_list(declared)) + if isinstance(declared, str) and declared: + return {declared.lower()} + if isinstance(declared, list): + return {str(value).lower() for value in declared} + return set() + + +def _variant_candidates(expected: dict, db: dict, fname: str) -> Iterator[str]: + """The sha1 of each held file that may stand for a name, best evidence first. + + Any one accepted value names a candidate: the index merges what several + emulators accept, and their own checks then judge each file. + """ + # Sorted: the index holds sets, whose order follows the per-process + # string hash, and the first passing candidate is the one shipped. + for hash_type in ("sha1", "md5", "crc32", "sha256"): + for value in sorted(expected.get(hash_type) or []): + yield from records_for_hash(db, hash_type, value) + yield from db.get("indexes", {}).get("by_name", {}).get(fname, []) + + +def find_validated_variant( + file_entry: dict, + db: dict, + current_path: str, + validation_index: dict, + bios_dir: str = BIOS_DIR, + platform_digest: str | None = None, + emulators: set[str] | None = None, + strict: bool = False, +) -> str | None: + """A held file the emulator's own checks accept, in place of current_path. + + Candidates come first from the hashes the emulator declares, which finds + a dump stored under another name, then from the files sharing the name. + platform_digest is the hash the frontend compares ("md5", "sha1") or None + when it reads no bytes: a candidate must then also carry a value the + entry declares, since the frontend would reject anything else. The + report and the packs read this one function, so the file a report counts + as satisfying the emulator is the file a pack ships. + """ + fname = file_entry.get("name", "") + if not fname or fname not in validation_index: + return None + accepted: set[str] = set() + if platform_digest: + if file_entry.get("zipped_file"): + return None + accepted = _platform_accepted(file_entry, platform_digest) + + files_db = db.get("files", {}) + current_real = os.path.realpath(current_path) + seen: set[str] = set() + + for sha1 in _variant_candidates(validation_index[fname], db, fname): + entry = files_db.get(sha1) or {} + path = entry.get("path", "") + if not path or not os.path.exists(path): + continue + real = os.path.realpath(path) + if real == current_real or real in seen: + continue + seen.add(real) + if accepted and str(entry.get(platform_digest, "")).lower() not in accepted: + continue + if check_file_validation( + path, fname, validation_index, bios_dir, emulators, strict + ) is None: + return path + return None + + +def agnostic_substitute( + file_entry: dict, sys_id: str, db: dict, platform_profiles: dict[str, dict] +) -> tuple[str, str] | None: + """(path, directory) of a held file a filename-agnostic core can boot. + + A core with `bios_mode: agnostic` (PCSX2 picks any image in its BIOS + folder) is served by any image of the right size, renamed to what the + platform declares. That only satisfies a frontend that checks existence: + a digest frontend compares the bytes. Only the platform's own cores are + asked, and the pack and verify read this one answer. An entry that + declares a content hash names one file: no substitute stands for it. + """ + if lists_hashes(file_entry): + return None + by_name = db.get("indexes", {}).get("by_name", {}) + files_db = db.get("files", {}) + for profile in platform_profiles.values(): + if profile.get("bios_mode") != "agnostic": + continue + if sys_id not in set(profile.get("systems", [])): + continue + for entry in profile.get("files", []): + for sha1 in by_name.get(entry.get("name", ""), []): + path = files_db.get(sha1, {}).get("path", "") + if not path: + continue + prefix = path.rsplit("/", 1)[0] + "/" + for candidate in files_db.values(): + held = candidate.get("path", "") + if ( + held.startswith(prefix) + and os.path.exists(held) + and shape_fits(entry, held, candidate.get("size", 0)) + ): + return held, prefix + break + return None + + +def frontend_digest_matches( + file_entry: dict, local_path: str | None, algorithm: str, rule: str = "" +) -> bool: + """Whether the frontend's own digest accepts the file. + + resolve_local_file calls a file `hash_mismatch` when any declared hash + disagrees, but a frontend compares one digest. verify_entry_md5 reads it + too: Recalbox hashes a ZIP by its members. Batocera compares the whole + md5 string (batocera-systems:1088), so a value cut short accepts nothing. Under SIZE_AND_ANY_HASH (RomM) the declared size must + match and then any one of md5, sha1 and crc32 does: a mistyped hash next + to a right one does not withhold the file, a wrong size does. + """ + if not local_path: + return False + + def composite() -> str | None: + if ".zip" not in os.path.basename(local_path): + return None + try: + return md5_composite(local_path) + except (zipfile.BadZipFile, OSError): + return None + + return digest_verdict( + file_entry, os.path.getsize(local_path), lambda: compute_hashes(local_path), + algorithm, rule, composite, + ) + + +def digest_verdict( + file_entry: dict, + size: int, + hashes: Callable[[], dict[str, str]], + algorithm: str, + rule: str = "", + composite: Callable[[], str | None] = lambda: None, +) -> bool: + """The frontend's acceptance rule over content given by its size, its + digests and, for an archive, its member digest. + + One rule for a file on disk and for a member of a built pack: the pack + check once compared only the md5 and refused, under RomM's rule, the + revision the builder had rightly shipped on its sha1 and size. + """ + if rule == SIZE_AND_ANY_HASH: + # RomM reads an absent size as 0: such an entry never verifies. + if size != int(file_entry.get("size") or 0): + return False + digests = hashes() + return any( + digests[field].lower() == str(file_entry[field]).strip().lower() + for field in ("md5", "sha1", "crc32") + if file_entry.get(field) + ) + if algorithm == "md5": + declared = parse_hash_list(file_entry.get("md5")) + else: + value = file_entry.get(algorithm) + values = value if isinstance(value, list) else [value] + declared = [str(v).strip().lower() for v in values if v] + if not declared: + return False + actual = hashes()[algorithm].lower() + if algorithm != "md5": + return actual in declared + # Recalbox hashes a .zip by its members only (Bios.cpp:64-68), so the + # container's own md5 answers nothing there. + composite_only = file_entry.get("zip_digest") == "composite" + if not composite_only and actual in declared: + return True + member_digest = composite() + if not member_digest: + return False + return member_digest.lower() in declared + + +def inner_rom_check(file_entry: dict, local_path: str) -> str: + """How an archive answers an entry that pins a ROM inside it. + + Batocera, RetroBat and ROCKNIX hash a member of the ZIP, never the ZIP: + the resolver hands back the archive as a mismatch and this decides it. + Returns check_inside_zip's answer for the first accepted MD5 that + matches, else for the last one tried. The pack and the install manifest + both read it, so a file one of them ships is a file the other lists. + """ + return _first_accepted_md5( + file_entry, + lambda md5: check_inside_zip(local_path, file_entry["zipped_file"], md5), + ) + + +def inner_rom_data_check(file_entry: dict, data: bytes) -> str: + """inner_rom_check on the bytes of an archive, as a pack holds it.""" + return _first_accepted_md5( + file_entry, + lambda md5: check_inside_zip_data(data, file_entry["zipped_file"], md5), + ) + + +def _first_accepted_md5(file_entry: dict, check: Callable[[str], str]) -> str: + # With no md5 declared, checkInsideZip still runs and needs the member. + result = "not_in_zip" + for candidate in parse_hash_list(file_entry.get("md5")) or [""]: + result = check(candidate) + if result == "ok": + break + return result + + +def baseline_verdict( + file_entry: dict, + local_path: str | None, + status: str, + verification_mode: str, + rule: str = "", +) -> tuple[str, str | None]: + """The status a platform entry ships under, or why a hash platform refuses it. + + Batocera hashes the member, never the ZIP: a zipped_file entry is checked + inside the archive whatever the outer resolution said, as verify does. A + frontend that hashes one digest accepts a file whose other declared + hashes disagree. The pack builder and the install manifest both read + this, so the one-line installer never places a file the pack refused. + Existence platforms never read the bytes: nothing is refused here. + """ + if not hash_mismatch_excludes_file(verification_mode): + return status, None + member = file_entry.get("zipped_file") + if member and local_path: + result = inner_rom_check(file_entry, local_path) + if result == "ok": + return "zip_exact", None + if result == "not_in_zip": + return status, f"{member} not found inside ZIP" + if result == "error": + return status, "cannot read ZIP" + return status, f"{member} MD5 mismatch inside ZIP" + if rule == SIZE_AND_ANY_HASH and local_path: + # A hash found by the resolver does not settle it: the size the + # frontend compares first can still be declared otherwise. + if frontend_digest_matches(file_entry, local_path, "", rule): + return status, None + return status, "size or hash mismatch" + if status != "hash_mismatch": + return status, None + if frontend_digest_matches(file_entry, local_path, digest_algorithm(verification_mode)): + return "frontend_digest_exact", None + return status, "hash mismatch" + + +def destination_owners(profiles: dict) -> dict[str, list[tuple[str, str]]]: + """For each file name, the path tail each emulator reads it under.""" + owners: dict[str, list[tuple[str, str]]] = {} + for emu_name, profile in profiles.items(): + for f in profile.get("files", []): + name = str(f.get("name") or "") + if not name: + continue + for declared in {f.get("path"), f.get("standalone_path")} - {None, ""} or {name}: + owners.setdefault(name.lower(), []).append( + (str(declared).replace("\\", "/").lower(), emu_name) + ) + return owners + + +def _owners_of(destination: str, name: str, owners: dict) -> set[str]: + """Emulators whose declared path is the longest tail of the destination.""" + destination = destination.replace("\\", "/").lower() + matching = [ + (tail, emu) for tail, emu in owners.get(name.lower(), []) + if destination == tail or destination.endswith("/" + tail) + ] + if not matching: + return set() + longest = max(len(tail) for tail, _emu in matching) + return {emu for tail, emu in matching if len(tail) == longest} + + +class Judges(TypedDict, total=False): + """The cores that judge a file in validated_choice, each by its own entries.""" + + emulators: set[str] | None + + +def validated_choice( + file_entry: dict, + local_path: str | None, + db: dict, + validation_index: dict, + bios_dir: str, + platform_digest: str | None, + destination: str = "", + owners: dict | None = None, + **judging: Unpack[Judges], +) -> tuple[str | None, str | None]: + """The file a platform destination ships, and the disagreement if any. + + A frontend's own check can pass while an emulator it runs rejects the + file. A held variant both accept replaces it. The pack and the install + manifest both read this, so they name the same file. A destination + another emulator declares more precisely is that emulator's: ZEsarUX's + 48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom. + """ + unknown = sorted(set(judging) - set(Judges.__annotations__)) + if unknown: + raise TypeError(f"validated_choice() got an unexpected keyword argument '{unknown[0]}'") + emulators = judging.get("emulators") + if not local_path or not validation_index: + return local_path, None + name = file_entry.get("name", "") + rules = validation_index.get(name) + judges: set[str] | None = emulators + if rules and judges is None and owners and destination: + owning = _owners_of(destination, name, owners) + if not owning & set(rules["emulators"]): + # No core that checks this name reads this destination: PC-98's + # bios.rom rules have no say over roms/ibmpcjr/bios.rom. + return local_path, None + # The cores that read this destination judge it, each by its own + # entries. + judges = owning & set(rules["emulators"]) + + def check(path: str, strict: bool) -> tuple[str, list[str]] | None: + return check_file_validation(path, name, validation_index, bios_dir, judges, strict) + + def variant(strict: bool) -> str | None: + return find_validated_variant( + file_entry, db, local_path, validation_index, bios_dir, + platform_digest=platform_digest, emulators=judges, strict=strict, + ) + + if not check(local_path, True): + return local_path, None + # A held file every check passes, warn-level ones included, comes first, + # then the file itself when only a warning fails (the core runs it), + # then a held file the core at least runs. + better = variant(True) + if better: + return better, None + failed = check(local_path, False) + if not failed: + return local_path, None + better = variant(False) + if better: + return better, None + reason, failing = failed + said = f"{', '.join(failing)} says {reason}" + return local_path, Refusal(said, reason.accepted) if isinstance(reason, Refusal) else said + + +def existence_discrepancy(file_entry: dict, local_path: str, platform_display: str) -> str: + """What an existence platform is told when its declared hash contradicts + the file it loads: the file is kept, the gap is said out loud. The pack + and verify both print this one line.""" + declared = file_entry.get("md5", "") or file_entry.get("sha1", "") + actual = compute_hashes(local_path) + return ( + f"packed per {platform_display} existence check: declared hash {declared}, " + f"file md5 {actual['md5']} sha1 {actual['sha1']}" + ) + + +def same_slot_entries(files: list, name: str, path: str) -> list[dict]: + """The entries of one profile that name the same file at the same path. + + A profile lists every version its code takes under one name (each GRP + of Raze's table, eduke32's demo and retail NWINTER.GRP): any of them + fills the slot. + """ + return [ + entry for entry in files or [] + if isinstance(entry, dict) and entry.get("name") == name + and (entry.get("path") or name) == path + ] + + +def slot_index(files: list) -> dict[tuple[str, str], list[dict]]: + """A profile's entries keyed by (name, path), as same_slot_entries + matches them: one pass, then one lookup per extra.""" + index: dict[tuple[str, str], list[dict]] = {} + for entry in files or []: + if isinstance(entry, dict) and isinstance(entry.get("name"), str): + name = entry["name"] + index.setdefault((name, entry.get("path") or name), []).append(entry) + return index + + +def extra_alternatives(fe: dict, profiles: Mapping | None) -> list[dict]: + """The versions the extra's own profile accepts at the extra's slot.""" + if not profiles: + return [] + profile = profiles.get(fe.get("source_profile") or "", {}) + name = fe.get("source_name") or fe.get("name", "") + return same_slot_entries( + profile.get("files") or [], name, fe.get("source_path") or name + ) + + +def core_size_refusal( + file_entry: dict, local_path: str | None, alternatives: Sequence[dict] = (), +) -> str | None: + """Why the core refuses this copy by the size its own code checks, or None. + + The one rule the builder, the install manifest and verify read for a + core's file. An existence platform never opens the bytes, so a copy whose + hash disagrees still ships to it, but a core that measures the file turns + one of the wrong size away: Basilisk II stops on the Apple IIGS' 128 KB + ROM (main_unix.cpp:692), so packing that file for it serves nothing. + ``alternatives`` are the other versions the profile accepts at the same + slot: a copy any of them takes is not refused. + """ + if not local_path or not os.path.isfile(local_path): + return None + size = os.path.getsize(local_path) + sized = [entry for entry in (file_entry, *alternatives) if name_match_size_ok(entry, size)] + if any(content_fits(entry, local_path) for entry in sized): + return None + if sized: + tests = sorted({check for entry in sized for check in declared_content_checks(entry)}) + return f"the core's {', '.join(tests)} test turns it away" + declared = file_entry.get("size") + bounds = [] if declared is None else [str(declared)] + multiple = file_entry.get("size_multiple") + if multiple or any(file_entry.get(k) is not None for k in ("min_size", "max_size")): + window = f"{file_entry.get('min_size', 0)} to {file_entry.get('max_size', 'any')}" + bounds.append(f"{window} in multiples of {multiple}" if multiple else window) + return f"{size} bytes, the core checks for {' or '.join(bounds)}" diff --git a/scripts/resolve/directories.py b/scripts/resolve/directories.py index 1e26750b7..317513a05 100644 --- a/scripts/resolve/directories.py +++ b/scripts/resolve/directories.py @@ -3,7 +3,7 @@ from __future__ import annotations from core.memo import DerivedView -from resolve.validation import read_by_build +from resolve.entryscope import read_by_build # The members found under each tail, kept per by_path_suffix index. diff --git a/scripts/resolve/entryscope.py b/scripts/resolve/entryscope.py new file mode 100644 index 000000000..8972b787b --- /dev/null +++ b/scripts/resolve/entryscope.py @@ -0,0 +1,241 @@ +"""Where an entry is read and whether a build delivers it: system or save dir, build mode, gap scope.""" + +from __future__ import annotations + +from collections.abc import Mapping + +from core.paths import sanitize_pack_path +from resolve.archives import archive_members +from resolve.content import name_match_size_ok + + +def read_from_system_dir(file_entry: dict, standalone: bool = False) -> bool: + """Whether the emulator reads this entry from the system directory. + + A file loaded from the save, content or working directory is not in the + BIOS tree: no platform lists it, and the truth model must not ask a + platform to declare it. Packs place one read below the save directory + there (read_from_save_dir), never in the BIOS tree. Two builds can read one file from two + places: libretro Dolphin keeps its User tree in the save directory, the + standalone app in its own folder, so ``load_from`` can be keyed by build. + """ + load_from = _load_from(file_entry, standalone) + return not load_from or load_from == "system_dir" + + +def _load_from(file_entry: dict, standalone: bool) -> str: + """The ``load_from`` value that applies to one build.""" + load_from = file_entry.get("load_from", "") + if isinstance(load_from, dict): + load_from = load_from.get("standalone" if standalone else "libretro", "") + return load_from or "" + + +def read_from_save_dir(file_entry: dict, standalone: bool = False) -> bool: + """Whether the libretro build reads this entry below the frontend's save + directory, the one RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY returns. + + ``path`` is then relative to that directory. A standalone app has no + frontend to hand it one: its files are placed by ``standalone_path``. + """ + return not standalone and _load_from(file_entry, False) == "save_dir" + + +def entry_root(file_entry: dict, standalone: bool = False) -> str: + """The frontend directory an entry's ``path`` is relative to: ``save`` + for a file the libretro build reads below the save directory, else + ``system``.""" + return "save" if read_from_save_dir(file_entry, standalone) else "system" + + +def outside_gap_scope(file_entry: dict, is_standalone: bool) -> bool: + """Whether an entry is a file the platform's pack would carry for this build. + + Read by the gap report and by verify's undeclared-file pass, so both set + aside the same entries: a placeholder standing for a family of files, a + file the user imports through the UI (``path: null``), an entry of the + build the platform does not run, a file read outside the system and + save directories, and a filename-agnostic entry the builder scans for + itself. A file the libretro build reads below the save directory is in + scope: the pack places it there (``entry_root``). + """ + name = file_entry.get("name", "") + if "<" in name or ">" in name or "*" in name: + return True + if "path" in file_entry and file_entry["path"] is None: + return True + if not read_by_build(file_entry, is_standalone): + return True + return not ( + read_from_system_dir(file_entry, is_standalone) + or read_from_save_dir(file_entry, is_standalone) + ) or bool(file_entry.get("agnostic")) + + +def case_folded_slots( + config: dict, declarations: Mapping[str, list[tuple[int | None, str]]], +) -> frozenset[str]: + """The slots a platform whose filesystem folds case fills, any spelling. + + On RetroBat the 32X_G_BIOS.BIN it declares is the file BlastEm opens as + 32X_G_BIOS.bin. On Lakka bios.col and BIOS.col are two files: nothing. + """ + if not config.get("case_insensitive_fs", False): + return frozenset() + return frozenset( + where for places in declarations.values() for _size, where in places if where + ) + + +def declaration_settles( + file_entry: dict, + fname: str, + declared_names: Mapping[str, list[tuple[int | None, str]]] | set[str], + dest: str = "", + folded_slots: frozenset[str] = frozenset(), + declared_contents: Mapping[str, set[str]] | None = None, +) -> bool: + """Whether a platform declaration meets a core's requirement. + + An entry the core finds by content (``found_by: content`` on the entry) + is met by any declaration of a file it accepts by hash, in the folder it + scans: atari800 takes RetroDECK's ROM_BASIC_A by its CRC32, so its own + label for that ROM is not one more file to ship. + + A platform declaring the name the core reads has met the requirement + where the declaration fills the entry's own slot, whose content the slot + arbitration decides, or elsewhere at a size the core accepts: the builder + copies that file to the core's path. Galaksija's 4 KiB ROM1.BIN does not + stand for DOSBox's 32 KiB SC-55 one. The builder copies nothing for an + alias, so an alias answers only where the core reads it: quasi88 reads + n88sub.rom or disk.rom in quasi88/, and System.dat names quasi88/disk.rom. + RetroDECK's root MSX.ROM is not CLK's MSX/MSX.ROM, and RetroBat's 16 KiB + MSX DISK.ROM at the root is not the 256-byte Disk II ROM gsplus also + accepts as c600.rom. The archive answers by its name. A bare set of names + carries no slot or size and answers by name. + + Read by verify and by the gap report, which settled on the name alone + and left DOSBox's SC-55 ROMs off the gaps page. ``folded_slots`` + (case_folded_slots) are slots a declaration fills in another spelling on + a filesystem that folds case: the core opens that file there. + """ + if file_entry.get("archive") in declared_names: + return True + slot = sanitize_pack_path(dest or fname).lower() + directory = slot if dest.endswith("/") else slot.rpartition("/")[0] + if declared_contents and file_entry.get("found_by") == "content": + for field in ("md5", "sha1", "crc32"): + values = file_entry.get(field) or [] + for value in values if isinstance(values, list) else str(values).split(","): + folders = declared_contents.get(f"{field}:{str(value).strip().lower()}") + if folders and directory in folders: + return True + if not dest.endswith("/") and slot in folded_slots: + return True + for name in (fname, *file_entry.get("aliases", [])): + if name not in declared_names: + continue + if not isinstance(declared_names, Mapping): + return True + if name == fname: + if any( + where == slot or name_match_size_ok(file_entry, size) + for size, where in declared_names[name] + ): + return True + continue + read_at = f"{directory}/{name}".lower() if directory else name.lower() + if any( + where == read_at and name_match_size_ok(file_entry, size) + for size, where in declared_names[name] + ): + return True + return False + + +def with_archive_members(entry: dict, files: list[dict]) -> dict: + """A loose entry resolved as the archive its profile reads members from. + + gngeopi declares neogeo.zip and, apart, the ROMs it opens inside it. The + members decide which same-named copy is the archive: resolved by name + alone, the loose entry took another copy than the archive pass and the + profile blocked its own archive. + """ + if entry.get("archive"): + return entry + members = archive_members(entry.get("name", ""), files) + return {**entry, "members": members} if members else entry + + +def opens_by_name(file_entry: dict, profile: dict, standalone: bool = False) -> bool: + """Whether the code opens this entry by its name. + + A core that scans a folder and identifies firmware by content + (DuckStation by MD5, bios.cpp:208) gives its entries names that are + labels. `found_by` says which, on the file or the profile, keyed by + build when the two builds differ. + """ + for source in (file_entry, profile): + value = source.get("found_by") + if isinstance(value, dict): + value = value.get("standalone" if standalone else "libretro") + if value: + return value != "content" + return True + + +def read_by_build(entry: dict, standalone: bool) -> bool: + """Whether the build that runs (standalone or libretro) reads the entry.""" + return entry.get("mode") != ("libretro" if standalone else "standalone") + + +def filter_files_by_mode(files: list[dict], standalone: bool) -> list[dict]: + """Filter file entries by libretro/standalone mode.""" + return [f for f in files if read_by_build(f, standalone)] + + +def installed_with_emulator(entry: dict, platform: str = "") -> bool: + """Whether the emulator as this platform installs it already brings the entry. + + `bundled` describes the emulator's own release. A platform package can + differ both ways: Batocera's hcl package installs the binary alone and + sends users to fetch the data (`not_bundled_on`), while its blueMSX core + package copies the machines and databases beside the core + (`installed_on`). + """ + if platform and platform in (entry.get("installed_on") or []): + return True + return bool(entry.get("bundled")) and platform not in (entry.get("not_bundled_on") or []) + + +def installed_everywhere(entry: dict) -> bool: + """Whether the emulator brings the entry on every setup, for a view that names none. + + An entry a platform package leaves out (`not_bundled_on`) is a file that + setup's users still need: touchHLE panics without its fonts on ROCKNIX. + """ + return bool(entry.get("bundled")) and not entry.get("not_bundled_on") + + +def unread_on(entry: dict, platform: str) -> bool: + """Whether this platform's launcher points the emulator at other files. + + RetroBat starts standalone BlastEm with absolute paths to its own BIOS + names in the config it writes, so the defaults the emulator would read + (cdbios.bin, colecovision_bios.col) are never opened there. + """ + return bool(platform) and platform in (entry.get("unread_on") or []) + + +def deliverable(entries: list[dict], standalone: bool, platform: str = "") -> list[dict]: + """The entries of one build a pack has to bring. + + A file or tree installed with the emulator is already on the user's + machine: shipping it again only weighs the pack. `bundled` is scoped by + `mode` like any entry, so PPSSPP's assets, shipped by the standalone + release and not by the libretro core, still reach a RetroArch pack. + """ + return [ + e for e in filter_files_by_mode(entries, standalone) + if not installed_with_emulator(e, platform) and not unread_on(e, platform) + ] diff --git a/scripts/resolve/packfiles.py b/scripts/resolve/packfiles.py index 8e64bd3b2..bfbe46f71 100644 --- a/scripts/resolve/packfiles.py +++ b/scripts/resolve/packfiles.py @@ -23,7 +23,7 @@ from resolve.content import declared_hash_verdict, record_answers_declaration from resolve.localfile import resolution_is_hash_exact, resolve_local_file from core.paths import REPO_ROOT, declared_destination from core.ziptools import is_archive_path, readable_zip_member_crcs -from resolve.validation import inner_rom_check +from resolve.acceptance import inner_rom_check # CLI-wide network policy. Public helpers can override it explicitly, while # every CLI mode inherits --offline (including large-file release fallback). OFFLINE = False diff --git a/scripts/resolve/review.py b/scripts/resolve/review.py index fd53f496f..c63a1be10 100644 --- a/scripts/resolve/review.py +++ b/scripts/resolve/review.py @@ -22,7 +22,7 @@ from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from model.registry import list_registered_platforms from resolve.nativemode import digest_algorithm, platform_mode -from resolve.validation import frontend_digest_matches, inner_rom_check +from resolve.acceptance import frontend_digest_matches, inner_rom_check if TYPE_CHECKING: from typing_extensions import Unpack diff --git a/scripts/resolve/sendable.py b/scripts/resolve/sendable.py index 41e48e67b..d9a5888cd 100644 --- a/scripts/resolve/sendable.py +++ b/scripts/resolve/sendable.py @@ -5,7 +5,7 @@ from __future__ import annotations import re from resolve.gamedata import is_game_data -from resolve.validation import installed_everywhere +from resolve.entryscope import installed_everywhere # A name the code builds from the content (.txt, *.ini) is a # pattern, not a file anyone can upload. diff --git a/scripts/resolve/truth.py b/scripts/resolve/truth.py index 02d08fcc5..3c0780f18 100644 --- a/scripts/resolve/truth.py +++ b/scripts/resolve/truth.py @@ -20,7 +20,7 @@ from resolve.reconcile import contradicts, shares_hash from model.alternatives import groups_of from model.database import record_for_hash from core.hashing import HASH_FIELDS, compute_hashes, declared_hashes, lists_hashes, parse_hash_list -from resolve.validation import ( +from resolve.entryscope import ( filter_files_by_mode, installed_with_emulator, opens_by_name, diff --git a/scripts/resolve/validation.py b/scripts/resolve/validation.py index 2c0beff10..20fb641ed 100644 --- a/scripts/resolve/validation.py +++ b/scripts/resolve/validation.py @@ -8,32 +8,21 @@ truth data for reporting. from __future__ import annotations import os -import zipfile -from collections.abc import Callable, Collection, Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, TypedDict +from collections.abc import Collection, Mapping, Sequence from resolve.content import ( adler32_of, content_fits, - declared_content_checks, - name_match_size_ok, parse_validation, - shape_fits, merged_size_refusal, size_refusal, SizeRefusal, ) -from resolve.archives import archive_members -from model.database import records_for_hash from model.profiles import CONTENT_CHECKS, entry_system_ids, lists_files from core.hashing import compute_hashes, parse_hash_list -from core.paths import BIOS_DIR, sanitize_pack_path -from core.hashing import lists_hashes, md5_composite -from resolve.nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file -from core.ziptools import check_inside_zip, check_inside_zip_data +from core.paths import BIOS_DIR -if TYPE_CHECKING: - from typing_extensions import Unpack +from resolve.entryscope import opens_by_name # Validation types that require console-specific cryptographic keys. # verify.py cannot reproduce these: size checks still apply if combined. @@ -605,680 +594,3 @@ def _merged_hash_failure( emus = _emulators_for_check("adler32", pe) return _adler32_refusal(actual_adler, entry["adler32"]), emus return None - - -def read_from_system_dir(file_entry: dict, standalone: bool = False) -> bool: - """Whether the emulator reads this entry from the system directory. - - A file loaded from the save, content or working directory is not in the - BIOS tree: no platform lists it, and the truth model must not ask a - platform to declare it. Packs place one read below the save directory - there (read_from_save_dir), never in the BIOS tree. Two builds can read one file from two - places: libretro Dolphin keeps its User tree in the save directory, the - standalone app in its own folder, so ``load_from`` can be keyed by build. - """ - load_from = _load_from(file_entry, standalone) - return not load_from or load_from == "system_dir" - - -def _load_from(file_entry: dict, standalone: bool) -> str: - """The ``load_from`` value that applies to one build.""" - load_from = file_entry.get("load_from", "") - if isinstance(load_from, dict): - load_from = load_from.get("standalone" if standalone else "libretro", "") - return load_from or "" - - -def read_from_save_dir(file_entry: dict, standalone: bool = False) -> bool: - """Whether the libretro build reads this entry below the frontend's save - directory, the one RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY returns. - - ``path`` is then relative to that directory. A standalone app has no - frontend to hand it one: its files are placed by ``standalone_path``. - """ - return not standalone and _load_from(file_entry, False) == "save_dir" - - -def entry_root(file_entry: dict, standalone: bool = False) -> str: - """The frontend directory an entry's ``path`` is relative to: ``save`` - for a file the libretro build reads below the save directory, else - ``system``.""" - return "save" if read_from_save_dir(file_entry, standalone) else "system" - - -def outside_gap_scope(file_entry: dict, is_standalone: bool) -> bool: - """Whether an entry is a file the platform's pack would carry for this build. - - Read by the gap report and by verify's undeclared-file pass, so both set - aside the same entries: a placeholder standing for a family of files, a - file the user imports through the UI (``path: null``), an entry of the - build the platform does not run, a file read outside the system and - save directories, and a filename-agnostic entry the builder scans for - itself. A file the libretro build reads below the save directory is in - scope: the pack places it there (``entry_root``). - """ - name = file_entry.get("name", "") - if "<" in name or ">" in name or "*" in name: - return True - if "path" in file_entry and file_entry["path"] is None: - return True - if not read_by_build(file_entry, is_standalone): - return True - return not ( - read_from_system_dir(file_entry, is_standalone) - or read_from_save_dir(file_entry, is_standalone) - ) or bool(file_entry.get("agnostic")) - - -def case_folded_slots( - config: dict, declarations: Mapping[str, list[tuple[int | None, str]]], -) -> frozenset[str]: - """The slots a platform whose filesystem folds case fills, any spelling. - - On RetroBat the 32X_G_BIOS.BIN it declares is the file BlastEm opens as - 32X_G_BIOS.bin. On Lakka bios.col and BIOS.col are two files: nothing. - """ - if not config.get("case_insensitive_fs", False): - return frozenset() - return frozenset( - where for places in declarations.values() for _size, where in places if where - ) - - -def declaration_settles( - file_entry: dict, - fname: str, - declared_names: Mapping[str, list[tuple[int | None, str]]] | set[str], - dest: str = "", - folded_slots: frozenset[str] = frozenset(), - declared_contents: Mapping[str, set[str]] | None = None, -) -> bool: - """Whether a platform declaration meets a core's requirement. - - An entry the core finds by content (``found_by: content`` on the entry) - is met by any declaration of a file it accepts by hash, in the folder it - scans: atari800 takes RetroDECK's ROM_BASIC_A by its CRC32, so its own - label for that ROM is not one more file to ship. - - A platform declaring the name the core reads has met the requirement - where the declaration fills the entry's own slot, whose content the slot - arbitration decides, or elsewhere at a size the core accepts: the builder - copies that file to the core's path. Galaksija's 4 KiB ROM1.BIN does not - stand for DOSBox's 32 KiB SC-55 one. The builder copies nothing for an - alias, so an alias answers only where the core reads it: quasi88 reads - n88sub.rom or disk.rom in quasi88/, and System.dat names quasi88/disk.rom. - RetroDECK's root MSX.ROM is not CLK's MSX/MSX.ROM, and RetroBat's 16 KiB - MSX DISK.ROM at the root is not the 256-byte Disk II ROM gsplus also - accepts as c600.rom. The archive answers by its name. A bare set of names - carries no slot or size and answers by name. - - Read by verify and by the gap report, which settled on the name alone - and left DOSBox's SC-55 ROMs off the gaps page. ``folded_slots`` - (case_folded_slots) are slots a declaration fills in another spelling on - a filesystem that folds case: the core opens that file there. - """ - if file_entry.get("archive") in declared_names: - return True - slot = sanitize_pack_path(dest or fname).lower() - directory = slot if dest.endswith("/") else slot.rpartition("/")[0] - if declared_contents and file_entry.get("found_by") == "content": - for field in ("md5", "sha1", "crc32"): - values = file_entry.get(field) or [] - for value in values if isinstance(values, list) else str(values).split(","): - folders = declared_contents.get(f"{field}:{str(value).strip().lower()}") - if folders and directory in folders: - return True - if not dest.endswith("/") and slot in folded_slots: - return True - for name in (fname, *file_entry.get("aliases", [])): - if name not in declared_names: - continue - if not isinstance(declared_names, Mapping): - return True - if name == fname: - if any( - where == slot or name_match_size_ok(file_entry, size) - for size, where in declared_names[name] - ): - return True - continue - read_at = f"{directory}/{name}".lower() if directory else name.lower() - if any( - where == read_at and name_match_size_ok(file_entry, size) - for size, where in declared_names[name] - ): - return True - return False - - -def with_archive_members(entry: dict, files: list[dict]) -> dict: - """A loose entry resolved as the archive its profile reads members from. - - gngeopi declares neogeo.zip and, apart, the ROMs it opens inside it. The - members decide which same-named copy is the archive: resolved by name - alone, the loose entry took another copy than the archive pass and the - profile blocked its own archive. - """ - if entry.get("archive"): - return entry - members = archive_members(entry.get("name", ""), files) - return {**entry, "members": members} if members else entry - - -def opens_by_name(file_entry: dict, profile: dict, standalone: bool = False) -> bool: - """Whether the code opens this entry by its name. - - A core that scans a folder and identifies firmware by content - (DuckStation by MD5, bios.cpp:208) gives its entries names that are - labels. `found_by` says which, on the file or the profile, keyed by - build when the two builds differ. - """ - for source in (file_entry, profile): - value = source.get("found_by") - if isinstance(value, dict): - value = value.get("standalone" if standalone else "libretro") - if value: - return value != "content" - return True - - -def read_by_build(entry: dict, standalone: bool) -> bool: - """Whether the build that runs (standalone or libretro) reads the entry.""" - return entry.get("mode") != ("libretro" if standalone else "standalone") - - -def filter_files_by_mode(files: list[dict], standalone: bool) -> list[dict]: - """Filter file entries by libretro/standalone mode.""" - return [f for f in files if read_by_build(f, standalone)] - - -def installed_with_emulator(entry: dict, platform: str = "") -> bool: - """Whether the emulator as this platform installs it already brings the entry. - - `bundled` describes the emulator's own release. A platform package can - differ both ways: Batocera's hcl package installs the binary alone and - sends users to fetch the data (`not_bundled_on`), while its blueMSX core - package copies the machines and databases beside the core - (`installed_on`). - """ - if platform and platform in (entry.get("installed_on") or []): - return True - return bool(entry.get("bundled")) and platform not in (entry.get("not_bundled_on") or []) - - -def installed_everywhere(entry: dict) -> bool: - """Whether the emulator brings the entry on every setup, for a view that names none. - - An entry a platform package leaves out (`not_bundled_on`) is a file that - setup's users still need: touchHLE panics without its fonts on ROCKNIX. - """ - return bool(entry.get("bundled")) and not entry.get("not_bundled_on") - - -def unread_on(entry: dict, platform: str) -> bool: - """Whether this platform's launcher points the emulator at other files. - - RetroBat starts standalone BlastEm with absolute paths to its own BIOS - names in the config it writes, so the defaults the emulator would read - (cdbios.bin, colecovision_bios.col) are never opened there. - """ - return bool(platform) and platform in (entry.get("unread_on") or []) - - -def deliverable(entries: list[dict], standalone: bool, platform: str = "") -> list[dict]: - """The entries of one build a pack has to bring. - - A file or tree installed with the emulator is already on the user's - machine: shipping it again only weighs the pack. `bundled` is scoped by - `mode` like any entry, so PPSSPP's assets, shipped by the standalone - release and not by the libretro core, still reach a RetroArch pack. - """ - return [ - e for e in filter_files_by_mode(entries, standalone) - if not installed_with_emulator(e, platform) and not unread_on(e, platform) - ] - - -def _platform_accepted(file_entry: dict, platform_digest: str) -> set[str]: - """The values of the digest the frontend compares that the entry declares.""" - declared = file_entry.get(platform_digest) or "" - if platform_digest == "md5": - return set(parse_hash_list(declared)) - if isinstance(declared, str) and declared: - return {declared.lower()} - if isinstance(declared, list): - return {str(value).lower() for value in declared} - return set() - - -def _variant_candidates(expected: dict, db: dict, fname: str) -> Iterator[str]: - """The sha1 of each held file that may stand for a name, best evidence first. - - Any one accepted value names a candidate: the index merges what several - emulators accept, and their own checks then judge each file. - """ - # Sorted: the index holds sets, whose order follows the per-process - # string hash, and the first passing candidate is the one shipped. - for hash_type in ("sha1", "md5", "crc32", "sha256"): - for value in sorted(expected.get(hash_type) or []): - yield from records_for_hash(db, hash_type, value) - yield from db.get("indexes", {}).get("by_name", {}).get(fname, []) - - -def find_validated_variant( - file_entry: dict, - db: dict, - current_path: str, - validation_index: dict, - bios_dir: str = BIOS_DIR, - platform_digest: str | None = None, - emulators: set[str] | None = None, - strict: bool = False, -) -> str | None: - """A held file the emulator's own checks accept, in place of current_path. - - Candidates come first from the hashes the emulator declares, which finds - a dump stored under another name, then from the files sharing the name. - platform_digest is the hash the frontend compares ("md5", "sha1") or None - when it reads no bytes: a candidate must then also carry a value the - entry declares, since the frontend would reject anything else. The - report and the packs read this one function, so the file a report counts - as satisfying the emulator is the file a pack ships. - """ - fname = file_entry.get("name", "") - if not fname or fname not in validation_index: - return None - accepted: set[str] = set() - if platform_digest: - if file_entry.get("zipped_file"): - return None - accepted = _platform_accepted(file_entry, platform_digest) - - files_db = db.get("files", {}) - current_real = os.path.realpath(current_path) - seen: set[str] = set() - - for sha1 in _variant_candidates(validation_index[fname], db, fname): - entry = files_db.get(sha1) or {} - path = entry.get("path", "") - if not path or not os.path.exists(path): - continue - real = os.path.realpath(path) - if real == current_real or real in seen: - continue - seen.add(real) - if accepted and str(entry.get(platform_digest, "")).lower() not in accepted: - continue - if check_file_validation( - path, fname, validation_index, bios_dir, emulators, strict - ) is None: - return path - return None - - -def agnostic_substitute( - file_entry: dict, sys_id: str, db: dict, platform_profiles: dict[str, dict] -) -> tuple[str, str] | None: - """(path, directory) of a held file a filename-agnostic core can boot. - - A core with `bios_mode: agnostic` (PCSX2 picks any image in its BIOS - folder) is served by any image of the right size, renamed to what the - platform declares. That only satisfies a frontend that checks existence: - a digest frontend compares the bytes. Only the platform's own cores are - asked, and the pack and verify read this one answer. An entry that - declares a content hash names one file: no substitute stands for it. - """ - if lists_hashes(file_entry): - return None - by_name = db.get("indexes", {}).get("by_name", {}) - files_db = db.get("files", {}) - for profile in platform_profiles.values(): - if profile.get("bios_mode") != "agnostic": - continue - if sys_id not in set(profile.get("systems", [])): - continue - for entry in profile.get("files", []): - for sha1 in by_name.get(entry.get("name", ""), []): - path = files_db.get(sha1, {}).get("path", "") - if not path: - continue - prefix = path.rsplit("/", 1)[0] + "/" - for candidate in files_db.values(): - held = candidate.get("path", "") - if ( - held.startswith(prefix) - and os.path.exists(held) - and shape_fits(entry, held, candidate.get("size", 0)) - ): - return held, prefix - break - return None - - -def frontend_digest_matches( - file_entry: dict, local_path: str | None, algorithm: str, rule: str = "" -) -> bool: - """Whether the frontend's own digest accepts the file. - - resolve_local_file calls a file `hash_mismatch` when any declared hash - disagrees, but a frontend compares one digest. verify_entry_md5 reads it - too: Recalbox hashes a ZIP by its members. Batocera compares the whole - md5 string (batocera-systems:1088), so a value cut short accepts nothing. Under SIZE_AND_ANY_HASH (RomM) the declared size must - match and then any one of md5, sha1 and crc32 does: a mistyped hash next - to a right one does not withhold the file, a wrong size does. - """ - if not local_path: - return False - - def composite() -> str | None: - if ".zip" not in os.path.basename(local_path): - return None - try: - return md5_composite(local_path) - except (zipfile.BadZipFile, OSError): - return None - - return digest_verdict( - file_entry, os.path.getsize(local_path), lambda: compute_hashes(local_path), - algorithm, rule, composite, - ) - - -def digest_verdict( - file_entry: dict, - size: int, - hashes: Callable[[], dict[str, str]], - algorithm: str, - rule: str = "", - composite: Callable[[], str | None] = lambda: None, -) -> bool: - """The frontend's acceptance rule over content given by its size, its - digests and, for an archive, its member digest. - - One rule for a file on disk and for a member of a built pack: the pack - check once compared only the md5 and refused, under RomM's rule, the - revision the builder had rightly shipped on its sha1 and size. - """ - if rule == SIZE_AND_ANY_HASH: - # RomM reads an absent size as 0: such an entry never verifies. - if size != int(file_entry.get("size") or 0): - return False - digests = hashes() - return any( - digests[field].lower() == str(file_entry[field]).strip().lower() - for field in ("md5", "sha1", "crc32") - if file_entry.get(field) - ) - if algorithm == "md5": - declared = parse_hash_list(file_entry.get("md5")) - else: - value = file_entry.get(algorithm) - values = value if isinstance(value, list) else [value] - declared = [str(v).strip().lower() for v in values if v] - if not declared: - return False - actual = hashes()[algorithm].lower() - if algorithm != "md5": - return actual in declared - # Recalbox hashes a .zip by its members only (Bios.cpp:64-68), so the - # container's own md5 answers nothing there. - composite_only = file_entry.get("zip_digest") == "composite" - if not composite_only and actual in declared: - return True - member_digest = composite() - if not member_digest: - return False - return member_digest.lower() in declared - - -def inner_rom_check(file_entry: dict, local_path: str) -> str: - """How an archive answers an entry that pins a ROM inside it. - - Batocera, RetroBat and ROCKNIX hash a member of the ZIP, never the ZIP: - the resolver hands back the archive as a mismatch and this decides it. - Returns check_inside_zip's answer for the first accepted MD5 that - matches, else for the last one tried. The pack and the install manifest - both read it, so a file one of them ships is a file the other lists. - """ - return _first_accepted_md5( - file_entry, - lambda md5: check_inside_zip(local_path, file_entry["zipped_file"], md5), - ) - - -def inner_rom_data_check(file_entry: dict, data: bytes) -> str: - """inner_rom_check on the bytes of an archive, as a pack holds it.""" - return _first_accepted_md5( - file_entry, - lambda md5: check_inside_zip_data(data, file_entry["zipped_file"], md5), - ) - - -def _first_accepted_md5(file_entry: dict, check: Callable[[str], str]) -> str: - # With no md5 declared, checkInsideZip still runs and needs the member. - result = "not_in_zip" - for candidate in parse_hash_list(file_entry.get("md5")) or [""]: - result = check(candidate) - if result == "ok": - break - return result - - -def baseline_verdict( - file_entry: dict, - local_path: str | None, - status: str, - verification_mode: str, - rule: str = "", -) -> tuple[str, str | None]: - """The status a platform entry ships under, or why a hash platform refuses it. - - Batocera hashes the member, never the ZIP: a zipped_file entry is checked - inside the archive whatever the outer resolution said, as verify does. A - frontend that hashes one digest accepts a file whose other declared - hashes disagree. The pack builder and the install manifest both read - this, so the one-line installer never places a file the pack refused. - Existence platforms never read the bytes: nothing is refused here. - """ - if not hash_mismatch_excludes_file(verification_mode): - return status, None - member = file_entry.get("zipped_file") - if member and local_path: - result = inner_rom_check(file_entry, local_path) - if result == "ok": - return "zip_exact", None - if result == "not_in_zip": - return status, f"{member} not found inside ZIP" - if result == "error": - return status, "cannot read ZIP" - return status, f"{member} MD5 mismatch inside ZIP" - if rule == SIZE_AND_ANY_HASH and local_path: - # A hash found by the resolver does not settle it: the size the - # frontend compares first can still be declared otherwise. - if frontend_digest_matches(file_entry, local_path, "", rule): - return status, None - return status, "size or hash mismatch" - if status != "hash_mismatch": - return status, None - if frontend_digest_matches(file_entry, local_path, digest_algorithm(verification_mode)): - return "frontend_digest_exact", None - return status, "hash mismatch" - - -def destination_owners(profiles: dict) -> dict[str, list[tuple[str, str]]]: - """For each file name, the path tail each emulator reads it under.""" - owners: dict[str, list[tuple[str, str]]] = {} - for emu_name, profile in profiles.items(): - for f in profile.get("files", []): - name = str(f.get("name") or "") - if not name: - continue - for declared in {f.get("path"), f.get("standalone_path")} - {None, ""} or {name}: - owners.setdefault(name.lower(), []).append( - (str(declared).replace("\\", "/").lower(), emu_name) - ) - return owners - - -def _owners_of(destination: str, name: str, owners: dict) -> set[str]: - """Emulators whose declared path is the longest tail of the destination.""" - destination = destination.replace("\\", "/").lower() - matching = [ - (tail, emu) for tail, emu in owners.get(name.lower(), []) - if destination == tail or destination.endswith("/" + tail) - ] - if not matching: - return set() - longest = max(len(tail) for tail, _emu in matching) - return {emu for tail, emu in matching if len(tail) == longest} - - -class Judges(TypedDict, total=False): - """The cores that judge a file in validated_choice, each by its own entries.""" - - emulators: set[str] | None - - -def validated_choice( - file_entry: dict, - local_path: str | None, - db: dict, - validation_index: dict, - bios_dir: str, - platform_digest: str | None, - destination: str = "", - owners: dict | None = None, - **judging: Unpack[Judges], -) -> tuple[str | None, str | None]: - """The file a platform destination ships, and the disagreement if any. - - A frontend's own check can pass while an emulator it runs rejects the - file. A held variant both accept replaces it. The pack and the install - manifest both read this, so they name the same file. A destination - another emulator declares more precisely is that emulator's: ZEsarUX's - 48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom. - """ - unknown = sorted(set(judging) - set(Judges.__annotations__)) - if unknown: - raise TypeError(f"validated_choice() got an unexpected keyword argument '{unknown[0]}'") - emulators = judging.get("emulators") - if not local_path or not validation_index: - return local_path, None - name = file_entry.get("name", "") - rules = validation_index.get(name) - judges: set[str] | None = emulators - if rules and judges is None and owners and destination: - owning = _owners_of(destination, name, owners) - if not owning & set(rules["emulators"]): - # No core that checks this name reads this destination: PC-98's - # bios.rom rules have no say over roms/ibmpcjr/bios.rom. - return local_path, None - # The cores that read this destination judge it, each by its own - # entries. - judges = owning & set(rules["emulators"]) - - def check(path: str, strict: bool) -> tuple[str, list[str]] | None: - return check_file_validation(path, name, validation_index, bios_dir, judges, strict) - - def variant(strict: bool) -> str | None: - return find_validated_variant( - file_entry, db, local_path, validation_index, bios_dir, - platform_digest=platform_digest, emulators=judges, strict=strict, - ) - - if not check(local_path, True): - return local_path, None - # A held file every check passes, warn-level ones included, comes first, - # then the file itself when only a warning fails (the core runs it), - # then a held file the core at least runs. - better = variant(True) - if better: - return better, None - failed = check(local_path, False) - if not failed: - return local_path, None - better = variant(False) - if better: - return better, None - reason, failing = failed - said = f"{', '.join(failing)} says {reason}" - return local_path, Refusal(said, reason.accepted) if isinstance(reason, Refusal) else said - - -def existence_discrepancy(file_entry: dict, local_path: str, platform_display: str) -> str: - """What an existence platform is told when its declared hash contradicts - the file it loads: the file is kept, the gap is said out loud. The pack - and verify both print this one line.""" - declared = file_entry.get("md5", "") or file_entry.get("sha1", "") - actual = compute_hashes(local_path) - return ( - f"packed per {platform_display} existence check: declared hash {declared}, " - f"file md5 {actual['md5']} sha1 {actual['sha1']}" - ) - - -def same_slot_entries(files: list, name: str, path: str) -> list[dict]: - """The entries of one profile that name the same file at the same path. - - A profile lists every version its code takes under one name (each GRP - of Raze's table, eduke32's demo and retail NWINTER.GRP): any of them - fills the slot. - """ - return [ - entry for entry in files or [] - if isinstance(entry, dict) and entry.get("name") == name - and (entry.get("path") or name) == path - ] - - -def slot_index(files: list) -> dict[tuple[str, str], list[dict]]: - """A profile's entries keyed by (name, path), as same_slot_entries - matches them: one pass, then one lookup per extra.""" - index: dict[tuple[str, str], list[dict]] = {} - for entry in files or []: - if isinstance(entry, dict) and isinstance(entry.get("name"), str): - name = entry["name"] - index.setdefault((name, entry.get("path") or name), []).append(entry) - return index - - -def extra_alternatives(fe: dict, profiles: Mapping | None) -> list[dict]: - """The versions the extra's own profile accepts at the extra's slot.""" - if not profiles: - return [] - profile = profiles.get(fe.get("source_profile") or "", {}) - name = fe.get("source_name") or fe.get("name", "") - return same_slot_entries( - profile.get("files") or [], name, fe.get("source_path") or name - ) - - -def core_size_refusal( - file_entry: dict, local_path: str | None, alternatives: Sequence[dict] = (), -) -> str | None: - """Why the core refuses this copy by the size its own code checks, or None. - - The one rule the builder, the install manifest and verify read for a - core's file. An existence platform never opens the bytes, so a copy whose - hash disagrees still ships to it, but a core that measures the file turns - one of the wrong size away: Basilisk II stops on the Apple IIGS' 128 KB - ROM (main_unix.cpp:692), so packing that file for it serves nothing. - ``alternatives`` are the other versions the profile accepts at the same - slot: a copy any of them takes is not refused. - """ - if not local_path or not os.path.isfile(local_path): - return None - size = os.path.getsize(local_path) - sized = [entry for entry in (file_entry, *alternatives) if name_match_size_ok(entry, size)] - if any(content_fits(entry, local_path) for entry in sized): - return None - if sized: - tests = sorted({check for entry in sized for check in declared_content_checks(entry)}) - return f"the core's {', '.join(tests)} test turns it away" - declared = file_entry.get("size") - bounds = [] if declared is None else [str(declared)] - multiple = file_entry.get("size_multiple") - if multiple or any(file_entry.get(k) is not None for k in ("min_size", "max_size")): - window = f"{file_entry.get('min_size', 0)} to {file_entry.get('max_size', 'any')}" - bounds.append(f"{window} in multiples of {multiple}" if multiple else window) - return f"{size} bytes, the core checks for {' or '.join(bounds)}" diff --git a/scripts/schemas/profilechecks.py b/scripts/schemas/profilechecks.py index 5d56436a2..afabe22ac 100644 --- a/scripts/schemas/profilechecks.py +++ b/scripts/schemas/profilechecks.py @@ -6,7 +6,7 @@ from pathlib import Path import core.paths from model.alternatives import groups_of -from resolve.validation import read_from_save_dir +from resolve.entryscope import read_from_save_dir CHECK_FIELDS = { diff --git a/scripts/sitegen/install.py b/scripts/sitegen/install.py index e615d45c9..bbfd16084 100644 --- a/scripts/sitegen/install.py +++ b/scripts/sitegen/install.py @@ -20,7 +20,7 @@ from model.profiles import reads_own_files from resolve.launches import PlatformLaunches from resolve.layout import data_root_place from resolve.standalone import platform_launches -from resolve.validation import installed_everywhere, installed_with_emulator +from resolve.entryscope import installed_everywhere, installed_with_emulator from sitegen import markup from installer_build.module import installer_module from sitegen.fields import search_excluded diff --git a/scripts/sitegen/wanted.py b/scripts/sitegen/wanted.py index bdc3be27e..b94ed8be5 100644 --- a/scripts/sitegen/wanted.py +++ b/scripts/sitegen/wanted.py @@ -28,7 +28,7 @@ from packs.crossref import first_hash from core.hashing import cut_md5_owner, declared_hash_lists, parse_hash_list from resolve.review import LARGE_FILE_ISSUE_URL, Placement, placement from resolve.sendable import can_send, sendable -from resolve.validation import deliverable, filter_files_by_mode +from resolve.entryscope import deliverable, filter_files_by_mode from sitegen.config import UPLOAD_ROOT ALGORITHMS = ("sha1", "sha256", "md5", "crc32") diff --git a/tests/test_agnostic_substitute.py b/tests/test_agnostic_substitute.py index 08cdd7164..993fbdf1d 100644 --- a/tests/test_agnostic_substitute.py +++ b/tests/test_agnostic_substitute.py @@ -15,7 +15,7 @@ import tempfile import unittest from pathlib import Path -from resolve.validation import agnostic_substitute +from resolve.acceptance import agnostic_substitute REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 9ffefeb48..99c66bda4 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -1452,7 +1452,7 @@ class OneBaselineVerdict(unittest.TestCase): return str(path) def test_a_missing_member_is_refused_whatever_the_outer_status(self): - from scripts.resolve.validation import baseline_verdict + from scripts.resolve.acceptance import baseline_verdict entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""} with tempfile.TemporaryDirectory() as directory: @@ -1494,7 +1494,7 @@ class OneBaselineVerdict(unittest.TestCase): import hashlib from scripts.core.hashing import md5_composite - from scripts.resolve.validation import baseline_verdict, digest_verdict + from scripts.resolve.acceptance import baseline_verdict, digest_verdict with tempfile.TemporaryDirectory() as directory: loose = Path(directory) / "abc.bin" @@ -1524,7 +1524,7 @@ class OneBaselineVerdict(unittest.TestCase): import hashlib from scripts.core.hashing import md5_composite - from scripts.resolve.validation import digest_verdict + from scripts.resolve.acceptance import digest_verdict with tempfile.TemporaryDirectory() as directory: archive = self._archive(Path(directory), "rom.bin") @@ -4050,7 +4050,7 @@ class KidVidTapesStayWithTheContent(unittest.TestCase): def test_no_pack_places_them_in_the_system_directory(self): from scripts.model.profiles import load_emulator_profiles - from scripts.resolve.validation import ( + from scripts.resolve.entryscope import ( outside_gap_scope, read_from_save_dir, read_from_system_dir, @@ -5700,7 +5700,7 @@ class BundledFilesAreNotToSource(unittest.TestCase): def test_a_build_scope_keeps_it_for_the_other_build(self): """PPSSPP's standalone release ships assets/, its libretro core does not: bundled for one build, the entry still reaches a core's pack.""" - from resolve.validation import deliverable + from resolve.entryscope import deliverable entries = [{"ref": "ppsspp-assets", "mode": "libretro"}, {"name": "a.bin", "bundled": True, "mode": "standalone"}, @@ -5712,7 +5712,7 @@ class BundledFilesAreNotToSource(unittest.TestCase): def test_a_platform_package_can_differ_both_ways(self): """Batocera's hcl package installs the binary alone, its blueMSX core package copies the machines beside the core.""" - from resolve.validation import installed_with_emulator + from resolve.entryscope import installed_with_emulator hcl = {"name": "data.pak", "bundled": True, "not_bundled_on": ["batocera"]} machines = {"name": "Machines/MSX/config.ini", "installed_on": ["batocera", "retropie"]} @@ -5727,7 +5727,7 @@ class BundledFilesAreNotToSource(unittest.TestCase): the global gap report and the wanted list all still ask for them.""" from acquire.provenance import profile_needs from packs.crossref import cross_reference - from resolve.validation import installed_everywhere + from resolve.entryscope import installed_everywhere from sitegen.install import comes_with_app font = {"name": "LiberationMono-Regular.ttf", "bundled": True, @@ -6246,7 +6246,7 @@ class ZippedFileMd5IsParsedOnce(unittest.TestCase): import hashlib import zipfile as zf_mod - from scripts.resolve.validation import inner_rom_check + from scripts.resolve.acceptance import inner_rom_check from scripts.packs.verdicts import verify_entry_md5 with tempfile.TemporaryDirectory() as directory: @@ -6708,7 +6708,7 @@ class FsUaeKickstartIsFoundByContent(unittest.TestCase): flag came from the RetroPie launcher, which the platform layer records.""" def test_the_kickstart_is_an_optional_label(self): - from scripts.resolve.validation import opens_by_name + from scripts.resolve.entryscope import opens_by_name profile = yaml.safe_load((ROOT / "emulators" / "fs-uae.yml").read_text(encoding="utf-8")) entry = next(f for f in profile["files"] if f.get("sha1") == "891e9a547772fe0c6c19b610baf8bc4ea7fcb785") @@ -7433,7 +7433,7 @@ class AFileTheLauncherNeverOpens(unittest.TestCase): as required and missing on RetroBat although nothing there opens them.""" def test_unread_on_drops_the_entry_for_that_platform_only(self): - from resolve.validation import deliverable, unread_on + from resolve.entryscope import deliverable, unread_on entry = {"name": "cdbios.bin", "unread_on": ["retrobat"]} self.assertTrue(unread_on(entry, "retrobat")) @@ -8110,7 +8110,7 @@ class Ps2BiosImagesAreFoundByContent(unittest.TestCase): name armsx2 opens on six platforms.""" import yaml - from resolve.validation import opens_by_name + from resolve.entryscope import opens_by_name named = [] for path in sorted((ROOT / "emulators").glob("*.yml")): @@ -8140,7 +8140,7 @@ class SynthRomsAreFoundByContent(unittest.TestCase): def test_every_synth_rom_is_marked(self): import yaml - from resolve.validation import opens_by_name + from resolve.entryscope import opens_by_name profile = yaml.safe_load( (ROOT / "emulators" / "dosbox-staging.yml").read_text(encoding="utf-8") @@ -8187,7 +8187,7 @@ class OpenMsxSystemRomsAreFoundBySha1(unittest.TestCase): def test_no_systemrom_label_reads_as_a_name(self): import yaml - from resolve.validation import opens_by_name + from resolve.entryscope import opens_by_name profile = yaml.safe_load((ROOT / "emulators" / "openmsx.yml").read_text()) named = [ @@ -8368,7 +8368,7 @@ class VerifySha1ReadsTheBuilderDigest(unittest.TestCase): self.sha1 = hashlib.sha1(b"bizhawk firmware").hexdigest() def _status(self, sha1: object) -> str: - from resolve.validation import frontend_digest_matches + from resolve.acceptance import frontend_digest_matches entry = {"name": "fw.bin", "sha1": sha1} builder = frontend_digest_matches(entry, self.path, "sha1") diff --git a/tests/test_content_checks.py b/tests/test_content_checks.py index 1b192a09e..eb9a2347e 100644 --- a/tests/test_content_checks.py +++ b/tests/test_content_checks.py @@ -225,7 +225,7 @@ class OtherContentTests(unittest.TestCase): self.assertFalse(size_fits(bsx, 32767)) def test_core_refusal_names_the_sizes_and_the_window(self): - from resolve.validation import core_size_refusal + from resolve.acceptance import core_size_refusal disk = {"size": [143360, 143403], "min_size": 143105, "max_size": 143364, "validation": ["size"]} diff --git a/tests/test_content_declarations.py b/tests/test_content_declarations.py index ea5234558..1ad7ddd98 100644 --- a/tests/test_content_declarations.py +++ b/tests/test_content_declarations.py @@ -13,7 +13,7 @@ import tests import unittest from model.declarations import platform_declared_contents -from resolve.validation import declaration_settles +from resolve.entryscope import declaration_settles SHA1 = "70cdf57469a208528f78a14275837352e90e20f1" DB = { diff --git a/tests/test_core_data_trees.py b/tests/test_core_data_trees.py index c1cf40a9e..391140b6a 100644 --- a/tests/test_core_data_trees.py +++ b/tests/test_core_data_trees.py @@ -26,7 +26,7 @@ from resolve.standalone import platform_layouts, platform_launches from packs import archive from packs import datatrees from packs import platformpack -from resolve.validation import deliverable, read_from_system_dir +from resolve.entryscope import deliverable, read_from_system_dir REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_core_size_refusal.py b/tests/test_core_size_refusal.py index 8c1d82b3c..6ba08d17e 100644 --- a/tests/test_core_size_refusal.py +++ b/tests/test_core_size_refusal.py @@ -26,7 +26,7 @@ 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 import platformpack -from resolve.validation import core_size_refusal +from resolve.acceptance import core_size_refusal from packs.gaps import find_undeclared_files from packs.coverage import verify_platform diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index 759b422e5..142179d77 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -458,12 +458,12 @@ class Md5CompositeDefinition(unittest.TestCase): """The page said the direct MD5 is tried before the composite, which Recalbox never does for a .zip, and the pack check did the same.""" from resolve.localfile import resolve_local_file - from resolve import validation + from resolve.acceptance import digest_verdict section = _section(_page("verification-modes.md"), "md5_composite (Recalbox ZIP verification)") self.assertIn("zip_digest: composite", section) self.assertNotIn("is tried before reporting a mismatch", section) - for function in (resolve_local_file, validation.digest_verdict): + for function in (resolve_local_file, digest_verdict): self.assertIn('get("zip_digest") == "composite"', inspect.getsource(function)) @@ -1873,7 +1873,7 @@ class CrossReferenceSettlesBySlotAndSize(unittest.TestCase): settles a file only at its slot or at a size the core accepts.""" def test_the_page_states_the_rule_verify_reads(self): - from resolve.validation import declaration_settles + from resolve.entryscope import declaration_settles rom1 = {"name": "ROM1.BIN", "size": 32768, "validation": ["size"]} self.assertFalse(declaration_settles(rom1, "ROM1.BIN", {"ROM1.BIN": [(4096, "rom1.bin")]}, diff --git a/tests/test_e2e.py b/tests/test_e2e.py index d006bde29..cbcdd8ad4 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -43,7 +43,8 @@ from model.platforms import load_platform_config from resolve.localfile import resolve_local_file from resolve.cores import resolve_platform_cores from resolve.truth import diff_platform_truth, generate_platform_truth -from resolve.validation import build_validation_index, check_file_validation, filter_files_by_mode +from resolve.validation import build_validation_index, check_file_validation +from resolve.entryscope import filter_files_by_mode from packs.verdicts import Severity, Status from packs.gaps import find_exclusion_notes, find_undeclared_files from packs.emulatorcheck import verify_emulator diff --git a/tests/test_gap_settlement.py b/tests/test_gap_settlement.py index f84f40350..4ac4bead3 100644 --- a/tests/test_gap_settlement.py +++ b/tests/test_gap_settlement.py @@ -15,7 +15,7 @@ from pathlib import Path from packs.crossref import cross_reference from resolve.launches import PlatformLaunches -from resolve.validation import case_folded_slots, declaration_settles +from resolve.entryscope import case_folded_slots, declaration_settles REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_held_record.py b/tests/test_held_record.py index 15ddf32a1..aa6d2881a 100644 --- a/tests/test_held_record.py +++ b/tests/test_held_record.py @@ -19,7 +19,7 @@ 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.validation import _variant_candidates +from resolve.acceptance import _variant_candidates SHA_A, SHA_B = "a" * 40, "b" * 40 MD5_A, MD5_B = "1" * 32, "2" * 32 diff --git a/tests/test_libretro_layout.py b/tests/test_libretro_layout.py index effc32ef9..e0d65e074 100644 --- a/tests/test_libretro_layout.py +++ b/tests/test_libretro_layout.py @@ -16,7 +16,7 @@ import unittest from pathlib import Path from packs.paths import resolve_destination -from resolve.validation import outside_gap_scope, read_from_save_dir, read_from_system_dir +from resolve.entryscope import outside_gap_scope, read_from_save_dir, read_from_system_dir REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_profile_checks.py b/tests/test_profile_checks.py index 15255e77a..b6f58e66f 100644 --- a/tests/test_profile_checks.py +++ b/tests/test_profile_checks.py @@ -368,7 +368,7 @@ class FbAlpha2012HiscoreFromSaveDir(unittest.TestCase): bios/hiscore.dat slot that MAME cores read on RetroDECK and RetroBat.""" def test_hiscore_is_not_a_system_file(self): - from resolve.validation import read_from_system_dir + from resolve.entryscope import read_from_system_dir for emulator in ("fbalpha2012", "fbalpha2012_cps3"): with self.subTest(emulator=emulator): @@ -427,7 +427,7 @@ class BizHawkFindsFirmwareByHash(unittest.TestCase): writes, and the export added 59 of them to RetroBat's native file.""" def test_entries_are_labels_named_by_the_firmware_database(self): - from resolve.validation import opens_by_name + from resolve.entryscope import opens_by_name profile = _profile("bizhawk") named = [f["name"] for f in profile["files"] if opens_by_name(f, profile, True)] @@ -444,7 +444,7 @@ class AmiberryNamesComeFromItsCode(unittest.TestCase): writes, and the code has its own AROS (':AROS', src/memory.cpp:2156).""" def test_scan_label_and_no_launcher_names(self): - from resolve.validation import opens_by_name + from resolve.entryscope import opens_by_name profile = _profile("amiberry") entry = next(f for f in profile["files"] if f["name"] == "amiga-os-310.rom") @@ -462,7 +462,7 @@ class WinUaeNamesComeFromItsCode(unittest.TestCase): Uae.Generator.cs searches, and kick.rom was missing.""" def test_kick_rom_is_read_by_name_and_kickstarts_are_labels(self): - from resolve.validation import opens_by_name, read_from_system_dir + from resolve.entryscope import opens_by_name, read_from_system_dir profile = _profile("winuae") kick = next(f for f in profile["files"] if f["name"] == "kick.rom") diff --git a/tests/test_romm_hash_rule.py b/tests/test_romm_hash_rule.py index 26149605a..3378adadd 100644 --- a/tests/test_romm_hash_rule.py +++ b/tests/test_romm_hash_rule.py @@ -18,7 +18,7 @@ import zlib from pathlib import Path from resolve.nativemode import HASH_RULES, SIZE_AND_ANY_HASH -from resolve.validation import baseline_verdict, frontend_digest_matches +from resolve.acceptance import baseline_verdict, frontend_digest_matches from packs.verdicts import Status, verify_entry_md5 REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_save_root.py b/tests/test_save_root.py index 4db53c42f..e7b4cb36c 100644 --- a/tests/test_save_root.py +++ b/tests/test_save_root.py @@ -36,7 +36,7 @@ from packs.paths import ( save_destination, save_layout, ) -from resolve.validation import ( +from resolve.entryscope import ( entry_root, outside_gap_scope, read_from_save_dir, diff --git a/tests/test_site_wanted.py b/tests/test_site_wanted.py index dc2b8fd36..d072a36f1 100644 --- a/tests/test_site_wanted.py +++ b/tests/test_site_wanted.py @@ -677,7 +677,7 @@ class ThePublishedList(unittest.TestCase): """Each emulator a row names declares that file as firmware it does not install itself: pak0.pk3, game data for every profile, is gone.""" from model.profiles import load_emulator_profiles - from resolve.validation import installed_everywhere + from resolve.entryscope import installed_everywhere profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) self.assertNotIn("pak0.pk3", [e["n"] for e in self.data["entries"]]) diff --git a/tests/test_validated_choice.py b/tests/test_validated_choice.py index f60d5c4d2..36df40808 100644 --- a/tests/test_validated_choice.py +++ b/tests/test_validated_choice.py @@ -17,7 +17,8 @@ import tempfile import unittest from pathlib import Path -from resolve.validation import build_validation_index, destination_owners, validated_choice +from resolve.validation import build_validation_index +from resolve.acceptance import destination_owners, validated_choice REPO_ROOT = Path(__file__).resolve().parent.parent @@ -309,7 +310,8 @@ class AlternativesAreLookedUpBySlot(unittest.TestCase): from unittest import mock from packs import extras as packextras - from resolve import validation + from resolve import acceptance as verdicts + from resolve.acceptance import extra_alternatives files = [{"name": "DUKE3D.GRP", "size": n} for n in (1, 2)] + [ {"name": "a.bin", "path": "dir/a.bin"}, {"name": "a.bin"}, "not an entry", @@ -322,10 +324,10 @@ class AlternativesAreLookedUpBySlot(unittest.TestCase): {"source_profile": "raze", "source_name": "a.bin", "name": "renamed"}, {"source_profile": "other", "name": "a.bin"}, ] - with mock.patch.object(validation, "slot_index", side_effect=validation.slot_index) as built: + with mock.patch.object(verdicts, "slot_index", side_effect=verdicts.slot_index) as built: for fe in extras: self.assertEqual(resolver.alternatives(fe), - validation.extra_alternatives(fe, profiles)) + extra_alternatives(fe, profiles)) self.assertEqual(built.call_count, 2) diff --git a/tests/test_variant_choice.py b/tests/test_variant_choice.py index 518f52c35..3ddaa0bee 100644 --- a/tests/test_variant_choice.py +++ b/tests/test_variant_choice.py @@ -21,7 +21,7 @@ import tempfile import unittest from pathlib import Path -from resolve.validation import find_validated_variant +from resolve.acceptance import find_validated_variant REPO_ROOT = Path(__file__).resolve().parents[1] @@ -95,7 +95,8 @@ _SEEDED = """ import hashlib, sys, tempfile from pathlib import Path sys.path.insert(0, sys.argv[1]) -from resolve.validation import build_validation_index, find_validated_variant +from resolve.validation import build_validation_index +from resolve.acceptance import find_validated_variant root = Path(sys.argv[2]) paths = [root / f"ctrl_{i}.rom" for i in range(8)] files = {}