diff --git a/scripts/acquire/fetch.py b/scripts/acquire/fetch.py index e713e1595..9ea69b57c 100644 --- a/scripts/acquire/fetch.py +++ b/scripts/acquire/fetch.py @@ -16,7 +16,7 @@ from core import upstream from core.hashing import parse_hash_list from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT from resolve.lookup import held_record_for -from resolve.review import load_platform_hashes, load_profile_hashes +from resolve.reviewhashes import load_platform_hashes, load_profile_hashes MAX_DOWNLOAD = 100 * 1024 * 1024 # 100MB per file diff --git a/scripts/exporter/amberelec_exporter.py b/scripts/exporter/amberelec_exporter.py index 7e2de673e..d08f6a102 100644 --- a/scripts/exporter/amberelec_exporter.py +++ b/scripts/exporter/amberelec_exporter.py @@ -9,7 +9,7 @@ every build, and an addition is written the same way. from __future__ import annotations -from resolve.reconcile import NativeFile +from resolve.nativemodel import NativeFile from .batocera_exporter import Exporter as BatoceraExporter SOURCE_URL = ( diff --git a/scripts/exporter/base_exporter.py b/scripts/exporter/base_exporter.py index 3f364c5e8..9134f5625 100644 --- a/scripts/exporter/base_exporter.py +++ b/scripts/exporter/base_exporter.py @@ -12,7 +12,7 @@ from abc import ABC, abstractmethod from typing import Generic, TypeVar, Union from model.profiles import core_key_index, platform_core_profiles -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report # What a produced file holds: text for every format, bytes besides for one # that also hands back an archive (MiSTer's bios_db.json.zip). diff --git a/scripts/exporter/batocera_exporter.py b/scripts/exporter/batocera_exporter.py index ac9e0e5c8..c086de52d 100644 --- a/scripts/exporter/batocera_exporter.py +++ b/scripts/exporter/batocera_exporter.py @@ -14,7 +14,7 @@ import re from scraper.batocera_scraper import comment_start, systems_span from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report SOURCE_URL = ( "https://raw.githubusercontent.com/batocera-linux/batocera.linux/master" diff --git a/scripts/exporter/bizhawk_exporter.py b/scripts/exporter/bizhawk_exporter.py index 2b43c40cb..e54bc23ff 100644 --- a/scripts/exporter/bizhawk_exporter.py +++ b/scripts/exporter/bizhawk_exporter.py @@ -10,7 +10,7 @@ file is served as BizHawk wrote it, checked for its structure. from __future__ import annotations from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report SOURCE_URL = ( "https://raw.githubusercontent.com/TASEmulators/BizHawk/master" diff --git a/scripts/exporter/emudeck_exporter.py b/scripts/exporter/emudeck_exporter.py index 2e3f17284..cc4c59119 100644 --- a/scripts/exporter/emudeck_exporter.py +++ b/scripts/exporter/emudeck_exporter.py @@ -19,7 +19,7 @@ from scraper.emudeck_scraper import FUNCTION_HASH_MAP, RE_FUNC, RE_LOCAL_HASHES from .base_exporter import BaseExporter from core.hashing import parse_hash_list -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report SOURCE_URL = ( "https://raw.githubusercontent.com/dragoonDorise/EmuDeck/main" diff --git a/scripts/exporter/landed.py b/scripts/exporter/landed.py index 8d9c843eb..86cf1d012 100644 --- a/scripts/exporter/landed.py +++ b/scripts/exporter/landed.py @@ -7,7 +7,8 @@ from dataclasses import dataclass, field from .base_exporter import BaseExporter from core.hashing import parse_hash_list -from resolve.reconcile import HASH_FIELDS, NativeFile, single_size +from resolve.reconcile import HASH_FIELDS +from resolve.nativemodel import NativeFile, single_size @dataclass diff --git a/scripts/exporter/misterfpga_exporter.py b/scripts/exporter/misterfpga_exporter.py index 69898ec8e..e71170afa 100644 --- a/scripts/exporter/misterfpga_exporter.py +++ b/scripts/exporter/misterfpga_exporter.py @@ -14,7 +14,7 @@ from collections import OrderedDict from typing import Union from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report SOURCE_URL = ( "https://raw.githubusercontent.com/ajgowans/BiosDB_MiSTer/db/bios_db.json.zip" diff --git a/scripts/exporter/native.py b/scripts/exporter/native.py index 897cdd431..a70d470ce 100644 --- a/scripts/exporter/native.py +++ b/scripts/exporter/native.py @@ -30,7 +30,8 @@ from model.registry import load_data_dir_registry, load_platform_registry from model.safeparse import yaml_load from packs.datadirs import hold_data_dirs from resolve.categories import removal_candidates -from resolve.reconcile import Report, build_native_model +from resolve.nativemodel import Report +from resolve.reconcile import build_native_model from resolve.truth import generate_platform_truth diff --git a/scripts/exporter/recalbox_exporter.py b/scripts/exporter/recalbox_exporter.py index 874e036c8..5e320e534 100644 --- a/scripts/exporter/recalbox_exporter.py +++ b/scripts/exporter/recalbox_exporter.py @@ -24,9 +24,8 @@ from core.hashing import parse_hash_list from model.safeparse import parse_untrusted_xml from .base_exporter import BaseExporter -from resolve.reconcile import ( - NativeFile, NativeSystem, Report, by_destination, by_name, -) +from resolve.nativemodel import NativeFile, NativeSystem, Report +from resolve.reconcile import by_destination, by_name SOURCE_URL = ( "https://gitlab.com/recalbox/recalbox/-/raw/master/board/recalbox/fsoverlay" diff --git a/scripts/exporter/retrobat_exporter.py b/scripts/exporter/retrobat_exporter.py index 201ed4395..73770324d 100644 --- a/scripts/exporter/retrobat_exporter.py +++ b/scripts/exporter/retrobat_exporter.py @@ -11,7 +11,7 @@ import re from collections import OrderedDict from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report SOURCE_URL = ( "https://raw.githubusercontent.com/RetroBat-Official/emulatorlauncher/master" diff --git a/scripts/exporter/retrodeck_exporter.py b/scripts/exporter/retrodeck_exporter.py index 7f768a16c..d4d32da6e 100644 --- a/scripts/exporter/retrodeck_exporter.py +++ b/scripts/exporter/retrodeck_exporter.py @@ -15,7 +15,7 @@ from collections import OrderedDict from .base_exporter import BaseExporter from core.hashing import parse_hash_list from model.declarations import declared_components -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report COMPONENTS_REPO = "RetroDECK/components" COMPONENTS_BRANCH = "main" diff --git a/scripts/exporter/retropie_exporter.py b/scripts/exporter/retropie_exporter.py index 1f35adf2b..dafc951ef 100644 --- a/scripts/exporter/retropie_exporter.py +++ b/scripts/exporter/retropie_exporter.py @@ -23,7 +23,8 @@ from scraper.retropie_modules import module_fields from scraper.retropie_scraper import script_members from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report, search_order +from resolve.nativemodel import NativeFile, NativeSystem, Report +from resolve.reconcile import search_order SOURCE_URL = ( "https://codeload.github.com/RetroPie/RetroPie-Setup/tar.gz/refs/heads/master" diff --git a/scripts/exporter/rocknix_exporter.py b/scripts/exporter/rocknix_exporter.py index 1b886667b..c508d40ef 100644 --- a/scripts/exporter/rocknix_exporter.py +++ b/scripts/exporter/rocknix_exporter.py @@ -8,7 +8,7 @@ from __future__ import annotations import re -from resolve.reconcile import NativeSystem, Report +from resolve.nativemodel import NativeSystem, Report from .batocera_exporter import Exporter as BatoceraExporter SOURCE_URL = ( diff --git a/scripts/exporter/romm_exporter.py b/scripts/exporter/romm_exporter.py index 33f92e036..794d3302d 100644 --- a/scripts/exporter/romm_exporter.py +++ b/scripts/exporter/romm_exporter.py @@ -19,7 +19,7 @@ from scraper.romm_scraper import SLUG_MAP from .base_exporter import BaseExporter from core.hashing import parse_hash_list -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report SOURCE_URL = ( "https://raw.githubusercontent.com/rommapp/romm/master/backend/models" diff --git a/scripts/exporter/systemdat_exporter.py b/scripts/exporter/systemdat_exporter.py index abc89a013..75e235955 100644 --- a/scripts/exporter/systemdat_exporter.py +++ b/scripts/exporter/systemdat_exporter.py @@ -16,7 +16,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from scraper.dat_parser import parse_dat from .base_exporter import BaseExporter -from resolve.reconcile import NativeFile, NativeSystem, Report +from resolve.nativemodel import NativeFile, NativeSystem, Report SOURCE_URL = ( "https://raw.githubusercontent.com/libretro/libretro-database/master/dat/System.dat" diff --git a/scripts/resolve/categories.py b/scripts/resolve/categories.py index f819308a6..0fe464531 100644 --- a/scripts/resolve/categories.py +++ b/scripts/resolve/categories.py @@ -19,9 +19,8 @@ from pathlib import Path from model.systems import norm_system_id from resolve.cores import resolve_platform_cores, unresolved_platform_cores from core.hashing import declared_hashes, parse_hash_list -from resolve.reconcile import ( - HASH_FIELDS, NativeSystem, comparable, contradicts, entry_names, -) +from resolve.reconcile import HASH_FIELDS, entry_names +from resolve.nativemodel import NativeSystem, comparable, contradicts from resolve.launcherconfig import bound_launchers from resolve.launcherplaces import record_names as launcher_names diff --git a/scripts/resolve/nativemodel.py b/scripts/resolve/nativemodel.py new file mode 100644 index 000000000..fffaea552 --- /dev/null +++ b/scripts/resolve/nativemodel.py @@ -0,0 +1,346 @@ +"""The native model of a platform's list: its files, systems and report, and how their hashes compare.""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from core.hashing import HASH_FIELDS, declared_hashes, parse_hash_list + + +def checked_hashes(entry: dict | None) -> dict | None: + """The truth entry with only the hashes its code checks. + + `validation:` names what the code verifies. Where a checked hash names + one value, the content is pinned and every hash describes it. Where + the code checks no hash, or accepts several values, a hash it does not + name describes one revision among those it accepts: dosbox checks + MT32_CONTROL.ROM against nine sha1, and the one md5 beside them + replaced System.dat's, another accepted revision. Such a value still + pairs a renamed file, it never corrects or fills one. + + `hash_conflict` marks an entry whose cores declare different values: the + truth kept the first core's, so its hashes describe one revision among + those the cores accept. armsx2 and yaps2 disagree on GameIndex.yaml, and + armsx2's revision replaced System.dat's line for LRPS2. + """ + if not entry: + return entry + if entry.get("hash_conflict"): + return {k: v for k, v in entry.items() if k not in HASH_FIELDS} + if entry.get("validation") is None: + return entry + raw = entry["validation"] + if isinstance(raw, dict): + kinds = {str(k) for values in raw.values() for k in values or ()} + elif isinstance(raw, list): + kinds = {str(k) for k in raw} + else: + kinds = {str(raw)} + checked = [f for f in HASH_FIELDS if f in kinds and parse_hash_list(entry.get(f))] + if checked and all(len(set(parse_hash_list(entry.get(f)))) == 1 for f in checked): + return entry + return {k: v for k, v in entry.items() if k not in HASH_FIELDS or k in kinds} + + +def comparable(entry: dict | None) -> dict: + """The entry with only the hashes the truth can be compared with. + + Recalbox hashes a .zip by its members (Bios.cpp:64-68 calls + Zip::Md5Composite, which feeds each member's bytes in name order into + one md5), never by the container's bytes. Its md5 on an archive is that + composite, a digest no profile declares: read as a container md5 it was + replaced by geolith's, which Recalbox never computes. + """ + if not entry or entry.get("zip_digest") != "composite": + return entry or {} + return {k: v for k, v in entry.items() if k != "md5"} + + +def contradicted_hashes(truth_entry: dict, platform_entry: dict | None) -> list[str]: + """The hash fields a platform entry declares against the truth. + + A field contradicts when both sides declare it without a value in + common, among the hashes the code checks and the platform values a + profile can be compared with. export_native corrects exactly these and + diff_truth reports them: the diff read three fields and let one shared + value settle all of them, so it stayed silent on an md5 or a sha256 + the export rewrote. + """ + ours = declared_hashes(checked_hashes(truth_entry) or {}) + theirs = declared_hashes(comparable(platform_entry)) + return [f for f, values in ours.items() if f in theirs and not values & theirs[f]] + + +def contradicts(ours: dict[str, set[str]], theirs: dict[str, set[str]]) -> bool: + """A hash field both declared maps hold without a value in common.""" + return any(f in theirs and not values & theirs[f] for f, values in ours.items()) + + +def shares_hash(ours: dict[str, set[str]], theirs: dict[str, set[str]]) -> bool: + """A value in common on any hash field both declared maps hold.""" + return any(values & theirs.get(f, set()) for f, values in ours.items()) + + +def is_label(entry: dict) -> bool: + """A name only content-scanning cores give: no core opens that file. + + DuckStation identifies its BIOS by MD5 in a folder it scans, so + scph1001_v20.bin names nothing a platform could check by path. + """ + return bool(entry.get("_cores")) and "_named_by" in entry and not entry["_named_by"] + + +def is_placeholder(name: str) -> bool: + return "<" in name or ">" in name or "*" in name + + +def _field_sets(entry: dict | None) -> dict[str, set[str]]: + return {f: set(parse_hash_list((entry or {}).get(f))) for f in HASH_FIELDS} + + +def single_size(value: int | str | list[int | str]) -> int | None: + """One size, or None: a list names several accepted revisions, which a + single size field cannot state (int() on it stopped the whole export).""" + if isinstance(value, list): + distinct = {int(v) for v in value} + return distinct.pop() if len(distinct) == 1 else None + return int(value) + + +@dataclass +class NativeFile: + """One file as the platform will read it, after correction.""" + + name: str + destination: str + native_system: str + platform: dict | None = None + truth: dict | None = None + corrections: list[str] = field(default_factory=list) + # Hash fields the platform left empty and the truth fills. + filled: list[str] = field(default_factory=list) + # An addition filed under our own slug: the platform names no such system. + foreign_system: bool = False + # For an addition, each core that wants it as (runs standalone, name the + # platform gives it), empty when no core the platform runs is named. + runners: list[tuple[bool, str]] = field(default_factory=list) + # The platform reads this file's md5 as a composite of its members + # (Recalbox on a .zip) or as one member's (Batocera's zippedFile, which + # checkInsideZip compares inside the archive): the truth's md5 describes + # the container and can be neither compared with it nor written in its + # place. + composite_md5: bool = False + # Every truth entry of the system that answers to this platform entry's + # name, whichever one the pairing took: the element names its cores, and + # each core's own entry for the file says whether that core needs it. + namesakes: list[dict] = field(default_factory=list) + + @property + def origin(self) -> str: + if self.platform is not None and self.truth is not None: + return "both" + return "platform" if self.platform is not None else "truth" + + @property + def _checked_truth(self) -> dict: + """The truth's hashes that can overrule the platform's. An addition + has no platform value to overrule and keeps them all.""" + if self.platform is None: + return self.truth or {} + return checked_hashes(self.truth) or {} + + def _identity_source(self) -> str: + """Which side's content fields describe the file: one side, or both. + + Mixing them field by field wrote the truth's size and crc beside the + platform's sha1, a record no file satisfies. The truth decides alone + only on a contradiction: a hash both sides declare without a value in + common, or two declared sizes. Different fields prove nothing: the + truth's crc32 beside Batocera's md5 for bios7.bin is one dump, and + reading it as a contradiction emptied the md5 the frontend checks. + """ + truth, plat = _field_sets(self._checked_truth), _field_sets(comparable(self.platform)) + if self.composite_md5: + truth["md5"] = set() + if not any(truth.values()): + return "platform" + if not any(plat.values()): + return "truth" + shared = [f for f in HASH_FIELDS if truth[f] and plat[f]] + if any(truth[f] & plat[f] for f in shared): + return "both" + return "truth" if shared or self._sizes_differ() else "both" + + def _sizes_differ(self) -> bool: + t_size = (self.truth or {}).get("size") + p_size = (self.platform or {}).get("size") + return isinstance(t_size, int) and isinstance(p_size, int) and t_size != p_size + + def hashes(self, field_name: str) -> list[str]: + """Accepted values for a hash, truth first when it has an opinion. + + The truth is read from the emulator's source. The platform list is a + secondary source. When both speak and disagree, the truth decides and + the divergence is recorded, never silently merged: an emulator that + rejects a file will reject it whatever the platform declares. + """ + if field_name == "md5" and self.composite_md5: + return parse_hash_list((self.platform or {}).get(field_name)) + truth_values = parse_hash_list(self._checked_truth.get(field_name)) + platform_values = parse_hash_list((self.platform or {}).get(field_name)) + source = self._identity_source() + if source == "platform": + return platform_values + if source == "truth": + return truth_values + if not truth_values: + return platform_values + if not set(truth_values) & set(platform_values): + return truth_values + # Nothing to add: the platform's own order stands. Truth first + # rewrote Recalbox's msx/CARTS.SHA md5 list with the same two values + # swapped, a diff line that changes nothing the frontend checks. + if set(truth_values) <= set(platform_values): + return platform_values + # Keep the platform's extra accepted revisions alongside ours. + return truth_values + [v for v in platform_values if v not in truth_values] + + def hash(self, field_name: str) -> str: + values = self.hashes(field_name) + return values[0] if values else "" + + def record_hash(self, field_name: str) -> str: + """One value of a record whose fields all describe one dump. + + A clrmamepro rom line or a RomM entry carries a single crc, md5 and + sha1: taking each field's first accepted value wrote syscard2.pce + with the v2.0 crc (the truth's first) beside the v2.1 md5 and sha1 + (System.dat's), a record no file satisfies. When the two sides + agree on the dump, the platform's record is kept whole, its value + chosen among those the truth accepts. A field only the truth names + is written when it names one value, which is then that dump's. + """ + if field_name == "md5" and self.composite_md5: + values = parse_hash_list((self.platform or {}).get(field_name)) + return values[0] if values else "" + source = self._identity_source() + truth_values = parse_hash_list(self._checked_truth.get(field_name)) + platform_values = parse_hash_list((self.platform or {}).get(field_name)) + if source == "truth": + return truth_values[0] if truth_values else "" + if source == "platform" or not truth_values: + return platform_values[0] if platform_values else "" + if platform_values: + accepted = [v for v in platform_values if v in truth_values] + return (accepted or truth_values)[0] + return truth_values[0] if len(truth_values) == 1 else "" + + @property + def required(self) -> bool: + if self.truth is not None and self.truth.get("required") is not None: + return bool(self.truth["required"]) + if self.platform is not None and self.platform.get("required") is not None: + return bool(self.platform["required"]) + if self.truth is not None and self.truth.get("one_of_required") is not None: + return bool(self.truth["one_of_required"]) + return True + + @property + def priority(self) -> int | None: + """Where the code looks for this file, lowest first. + + DuckStation's FindBIOSImageInDirectory keeps the image whose + priority is lower, and a search list a core walks in order maps + onto it as 1, 2, 3. Where cores disagree this is the best rank any + of them gives: nothing is dropped on it, so a file that is some + core's first choice is read early. None when nothing states one. + """ + for entry in (self.truth, self.platform): + if entry and entry.get("priority") is not None: + return int(entry["priority"]) + return None + + def size(self) -> int | None: + """Size of the content the written hashes describe. + + hashes() keeps the platform's values when the truth has none, so the + truth's size is only taken when the truth also speaks for the hash: + a name-matched 480-byte fbneo boot.bin turned RomM's Dreamcast + boot.bin into size 480 beside its 2 MB md5, which never verifies. + When the truth contradicts the platform's hash, the platform's size + describes the dump the truth rejects: geolith's neocdz.zip md5 went + out beside System.dat's 953078 bytes, a record no file satisfies. + """ + source = self._identity_source() + order = { + "platform": (self.platform, self.truth), + "truth": (self.truth,), + }.get(source, (self.truth, self.platform)) + # A list names every size the code accepts (geargrafx's syscard3.pce, + # headerless or headered). It states no single size, but it still + # admits the one the platform writes: System.dat's 262144 for the + # same md5 lost its size field when the list came first. + accepted: set[int] | None = None + for entry in order: + if not entry or not entry.get("size"): + continue + single = single_size(entry["size"]) + if single is None: + if accepted is None: + accepted = {int(v) for v in entry["size"]} + continue + if accepted is None or single in accepted: + return single + return None + + def native(self, key: str, default: object = "") -> object: + """Read a field the platform declares and we only carry through.""" + for entry in (self.platform, self.truth): + if entry and entry.get(key) not in (None, ""): + return entry[key] + return default + + def cores(self) -> list[str]: + """Cores that want this file, as Recalbox writes them: the declared + value, else each runner, a standalone bare and a core under + libretro/. A profile key is not a name the platform knows: + `libretro/duckstation` named no core Recalbox runs.""" + declared = self.native("core", "") + if declared: + return [c.strip() for c in str(declared).split(",") if c.strip()] + return [name if standalone else f"libretro/{name}" for standalone, name in self.runners] + + +@dataclass +class NativeSystem: + """One system as the platform names it.""" + + native_id: str + name: str = "" + files: list[NativeFile] = field(default_factory=list) + from_platform: bool = False + + @property + def origin(self) -> str: + return "platform" if self.from_platform else "truth" + + +@dataclass +class Report: + """What the reconciliation changed, so the caller can say it out loud.""" + + systems_kept: int = 0 + systems_added: int = 0 + files_kept: int = 0 + files_added: int = 0 + hashes_corrected: list[str] = field(default_factory=list) + required_corrected: list[str] = field(default_factory=list) + # Entries only content-scanning cores name: never written as files. + labels: int = 0 + # Additions to a system spanning several native ids that their cores do + # not tell apart, as truth system/name: not written. + unattributed: list[str] = field(default_factory=list) + + @property + def corrections(self) -> int: + return len(self.hashes_corrected) + len(self.required_corrected) diff --git a/scripts/resolve/platformdiff.py b/scripts/resolve/platformdiff.py index 20b083926..d8fe6e548 100644 --- a/scripts/resolve/platformdiff.py +++ b/scripts/resolve/platformdiff.py @@ -19,7 +19,7 @@ def _hash_mismatch(t_entry: dict, s_entry: dict) -> dict | None: contradicts nothing (checked_hashes), and a platform md5 that is a composite of a zip's members is no container md5 (comparable). """ - from resolve.reconcile import contradicted_hashes + from resolve.nativemodel import contradicted_hashes fields = contradicted_hashes(t_entry, s_entry) if not fields: @@ -42,7 +42,8 @@ def _diff_system(truth_sys: dict, scraped_sys: dict) -> dict: correct while the export corrected hashes the diff never named. An entry never answers for two. """ - from resolve.reconcile import is_placeholder, is_label, pair_entries, platform_declares + from resolve.nativemodel import is_placeholder, is_label + from resolve.reconcile import pair_entries, platform_declares truth_files = [ fe for fe in truth_sys.get("files", []) diff --git a/scripts/resolve/reconcile.py b/scripts/resolve/reconcile.py index 0a2bb5278..538567d6a 100644 --- a/scripts/resolve/reconcile.py +++ b/scripts/resolve/reconcile.py @@ -20,349 +20,22 @@ from types import MappingProxyType from core.hashing import HASH_FIELDS, declared_hashes, parse_hash_list from model.profiles import profile_names from model.systems import norm_system_id +from resolve.nativemodel import ( + NativeFile, + NativeSystem, + Report, + checked_hashes, + comparable, + contradicted_hashes, + contradicts, + is_label, + is_placeholder, + shares_hash, +) _NO_PROFILES: Mapping[str, dict] = MappingProxyType({}) -def checked_hashes(entry: dict | None) -> dict | None: - """The truth entry with only the hashes its code checks. - - `validation:` names what the code verifies. Where a checked hash names - one value, the content is pinned and every hash describes it. Where - the code checks no hash, or accepts several values, a hash it does not - name describes one revision among those it accepts: dosbox checks - MT32_CONTROL.ROM against nine sha1, and the one md5 beside them - replaced System.dat's, another accepted revision. Such a value still - pairs a renamed file, it never corrects or fills one. - - `hash_conflict` marks an entry whose cores declare different values: the - truth kept the first core's, so its hashes describe one revision among - those the cores accept. armsx2 and yaps2 disagree on GameIndex.yaml, and - armsx2's revision replaced System.dat's line for LRPS2. - """ - if not entry: - return entry - if entry.get("hash_conflict"): - return {k: v for k, v in entry.items() if k not in HASH_FIELDS} - if entry.get("validation") is None: - return entry - raw = entry["validation"] - if isinstance(raw, dict): - kinds = {str(k) for values in raw.values() for k in values or ()} - elif isinstance(raw, list): - kinds = {str(k) for k in raw} - else: - kinds = {str(raw)} - checked = [f for f in HASH_FIELDS if f in kinds and parse_hash_list(entry.get(f))] - if checked and all(len(set(parse_hash_list(entry.get(f)))) == 1 for f in checked): - return entry - return {k: v for k, v in entry.items() if k not in HASH_FIELDS or k in kinds} - - -def comparable(entry: dict | None) -> dict: - """The entry with only the hashes the truth can be compared with. - - Recalbox hashes a .zip by its members (Bios.cpp:64-68 calls - Zip::Md5Composite, which feeds each member's bytes in name order into - one md5), never by the container's bytes. Its md5 on an archive is that - composite, a digest no profile declares: read as a container md5 it was - replaced by geolith's, which Recalbox never computes. - """ - if not entry or entry.get("zip_digest") != "composite": - return entry or {} - return {k: v for k, v in entry.items() if k != "md5"} - - -def contradicted_hashes(truth_entry: dict, platform_entry: dict | None) -> list[str]: - """The hash fields a platform entry declares against the truth. - - A field contradicts when both sides declare it without a value in - common, among the hashes the code checks and the platform values a - profile can be compared with. export_native corrects exactly these and - diff_truth reports them: the diff read three fields and let one shared - value settle all of them, so it stayed silent on an md5 or a sha256 - the export rewrote. - """ - ours = declared_hashes(checked_hashes(truth_entry) or {}) - theirs = declared_hashes(comparable(platform_entry)) - return [f for f, values in ours.items() if f in theirs and not values & theirs[f]] - - -def contradicts(ours: dict[str, set[str]], theirs: dict[str, set[str]]) -> bool: - """A hash field both declared maps hold without a value in common.""" - return any(f in theirs and not values & theirs[f] for f, values in ours.items()) - - -def shares_hash(ours: dict[str, set[str]], theirs: dict[str, set[str]]) -> bool: - """A value in common on any hash field both declared maps hold.""" - return any(values & theirs.get(f, set()) for f, values in ours.items()) - - -def is_label(entry: dict) -> bool: - """A name only content-scanning cores give: no core opens that file. - - DuckStation identifies its BIOS by MD5 in a folder it scans, so - scph1001_v20.bin names nothing a platform could check by path. - """ - return bool(entry.get("_cores")) and "_named_by" in entry and not entry["_named_by"] - - -def is_placeholder(name: str) -> bool: - return "<" in name or ">" in name or "*" in name - - -def _field_sets(entry: dict | None) -> dict[str, set[str]]: - return {f: set(parse_hash_list((entry or {}).get(f))) for f in HASH_FIELDS} - - -def single_size(value: int | str | list[int | str]) -> int | None: - """One size, or None: a list names several accepted revisions, which a - single size field cannot state (int() on it stopped the whole export).""" - if isinstance(value, list): - distinct = {int(v) for v in value} - return distinct.pop() if len(distinct) == 1 else None - return int(value) - - -@dataclass -class NativeFile: - """One file as the platform will read it, after correction.""" - - name: str - destination: str - native_system: str - platform: dict | None = None - truth: dict | None = None - corrections: list[str] = field(default_factory=list) - # Hash fields the platform left empty and the truth fills. - filled: list[str] = field(default_factory=list) - # An addition filed under our own slug: the platform names no such system. - foreign_system: bool = False - # For an addition, each core that wants it as (runs standalone, name the - # platform gives it), empty when no core the platform runs is named. - runners: list[tuple[bool, str]] = field(default_factory=list) - # The platform reads this file's md5 as a composite of its members - # (Recalbox on a .zip) or as one member's (Batocera's zippedFile, which - # checkInsideZip compares inside the archive): the truth's md5 describes - # the container and can be neither compared with it nor written in its - # place. - composite_md5: bool = False - # Every truth entry of the system that answers to this platform entry's - # name, whichever one the pairing took: the element names its cores, and - # each core's own entry for the file says whether that core needs it. - namesakes: list[dict] = field(default_factory=list) - - @property - def origin(self) -> str: - if self.platform is not None and self.truth is not None: - return "both" - return "platform" if self.platform is not None else "truth" - - @property - def _checked_truth(self) -> dict: - """The truth's hashes that can overrule the platform's. An addition - has no platform value to overrule and keeps them all.""" - if self.platform is None: - return self.truth or {} - return checked_hashes(self.truth) or {} - - def _identity_source(self) -> str: - """Which side's content fields describe the file: one side, or both. - - Mixing them field by field wrote the truth's size and crc beside the - platform's sha1, a record no file satisfies. The truth decides alone - only on a contradiction: a hash both sides declare without a value in - common, or two declared sizes. Different fields prove nothing: the - truth's crc32 beside Batocera's md5 for bios7.bin is one dump, and - reading it as a contradiction emptied the md5 the frontend checks. - """ - truth, plat = _field_sets(self._checked_truth), _field_sets(comparable(self.platform)) - if self.composite_md5: - truth["md5"] = set() - if not any(truth.values()): - return "platform" - if not any(plat.values()): - return "truth" - shared = [f for f in HASH_FIELDS if truth[f] and plat[f]] - if any(truth[f] & plat[f] for f in shared): - return "both" - return "truth" if shared or self._sizes_differ() else "both" - - def _sizes_differ(self) -> bool: - t_size = (self.truth or {}).get("size") - p_size = (self.platform or {}).get("size") - return isinstance(t_size, int) and isinstance(p_size, int) and t_size != p_size - - def hashes(self, field_name: str) -> list[str]: - """Accepted values for a hash, truth first when it has an opinion. - - The truth is read from the emulator's source. The platform list is a - secondary source. When both speak and disagree, the truth decides and - the divergence is recorded, never silently merged: an emulator that - rejects a file will reject it whatever the platform declares. - """ - if field_name == "md5" and self.composite_md5: - return parse_hash_list((self.platform or {}).get(field_name)) - truth_values = parse_hash_list(self._checked_truth.get(field_name)) - platform_values = parse_hash_list((self.platform or {}).get(field_name)) - source = self._identity_source() - if source == "platform": - return platform_values - if source == "truth": - return truth_values - if not truth_values: - return platform_values - if not set(truth_values) & set(platform_values): - return truth_values - # Nothing to add: the platform's own order stands. Truth first - # rewrote Recalbox's msx/CARTS.SHA md5 list with the same two values - # swapped, a diff line that changes nothing the frontend checks. - if set(truth_values) <= set(platform_values): - return platform_values - # Keep the platform's extra accepted revisions alongside ours. - return truth_values + [v for v in platform_values if v not in truth_values] - - def hash(self, field_name: str) -> str: - values = self.hashes(field_name) - return values[0] if values else "" - - def record_hash(self, field_name: str) -> str: - """One value of a record whose fields all describe one dump. - - A clrmamepro rom line or a RomM entry carries a single crc, md5 and - sha1: taking each field's first accepted value wrote syscard2.pce - with the v2.0 crc (the truth's first) beside the v2.1 md5 and sha1 - (System.dat's), a record no file satisfies. When the two sides - agree on the dump, the platform's record is kept whole, its value - chosen among those the truth accepts. A field only the truth names - is written when it names one value, which is then that dump's. - """ - if field_name == "md5" and self.composite_md5: - values = parse_hash_list((self.platform or {}).get(field_name)) - return values[0] if values else "" - source = self._identity_source() - truth_values = parse_hash_list(self._checked_truth.get(field_name)) - platform_values = parse_hash_list((self.platform or {}).get(field_name)) - if source == "truth": - return truth_values[0] if truth_values else "" - if source == "platform" or not truth_values: - return platform_values[0] if platform_values else "" - if platform_values: - accepted = [v for v in platform_values if v in truth_values] - return (accepted or truth_values)[0] - return truth_values[0] if len(truth_values) == 1 else "" - - @property - def required(self) -> bool: - if self.truth is not None and self.truth.get("required") is not None: - return bool(self.truth["required"]) - if self.platform is not None and self.platform.get("required") is not None: - return bool(self.platform["required"]) - if self.truth is not None and self.truth.get("one_of_required") is not None: - return bool(self.truth["one_of_required"]) - return True - - @property - def priority(self) -> int | None: - """Where the code looks for this file, lowest first. - - DuckStation's FindBIOSImageInDirectory keeps the image whose - priority is lower, and a search list a core walks in order maps - onto it as 1, 2, 3. Where cores disagree this is the best rank any - of them gives: nothing is dropped on it, so a file that is some - core's first choice is read early. None when nothing states one. - """ - for entry in (self.truth, self.platform): - if entry and entry.get("priority") is not None: - return int(entry["priority"]) - return None - - def size(self) -> int | None: - """Size of the content the written hashes describe. - - hashes() keeps the platform's values when the truth has none, so the - truth's size is only taken when the truth also speaks for the hash: - a name-matched 480-byte fbneo boot.bin turned RomM's Dreamcast - boot.bin into size 480 beside its 2 MB md5, which never verifies. - When the truth contradicts the platform's hash, the platform's size - describes the dump the truth rejects: geolith's neocdz.zip md5 went - out beside System.dat's 953078 bytes, a record no file satisfies. - """ - source = self._identity_source() - order = { - "platform": (self.platform, self.truth), - "truth": (self.truth,), - }.get(source, (self.truth, self.platform)) - # A list names every size the code accepts (geargrafx's syscard3.pce, - # headerless or headered). It states no single size, but it still - # admits the one the platform writes: System.dat's 262144 for the - # same md5 lost its size field when the list came first. - accepted: set[int] | None = None - for entry in order: - if not entry or not entry.get("size"): - continue - single = single_size(entry["size"]) - if single is None: - if accepted is None: - accepted = {int(v) for v in entry["size"]} - continue - if accepted is None or single in accepted: - return single - return None - - def native(self, key: str, default: object = "") -> object: - """Read a field the platform declares and we only carry through.""" - for entry in (self.platform, self.truth): - if entry and entry.get(key) not in (None, ""): - return entry[key] - return default - - def cores(self) -> list[str]: - """Cores that want this file, as Recalbox writes them: the declared - value, else each runner, a standalone bare and a core under - libretro/. A profile key is not a name the platform knows: - `libretro/duckstation` named no core Recalbox runs.""" - declared = self.native("core", "") - if declared: - return [c.strip() for c in str(declared).split(",") if c.strip()] - return [name if standalone else f"libretro/{name}" for standalone, name in self.runners] - - -@dataclass -class NativeSystem: - """One system as the platform names it.""" - - native_id: str - name: str = "" - files: list[NativeFile] = field(default_factory=list) - from_platform: bool = False - - @property - def origin(self) -> str: - return "platform" if self.from_platform else "truth" - - -@dataclass -class Report: - """What the reconciliation changed, so the caller can say it out loud.""" - - systems_kept: int = 0 - systems_added: int = 0 - files_kept: int = 0 - files_added: int = 0 - hashes_corrected: list[str] = field(default_factory=list) - required_corrected: list[str] = field(default_factory=list) - # Entries only content-scanning cores name: never written as files. - labels: int = 0 - # Additions to a system spanning several native ids that their cores do - # not tell apart, as truth system/name: not written. - unattributed: list[str] = field(default_factory=list) - - @property - def corrections(self) -> int: - return len(self.hashes_corrected) + len(self.required_corrected) - - def _native_id_of(sys_key: str, sys_data: dict, file_entry: dict) -> str: """The platform's own id for the system a file belongs to.""" return ( diff --git a/scripts/resolve/review.py b/scripts/resolve/review.py index c63a1be10..88d403a0d 100644 --- a/scripts/resolve/review.py +++ b/scripts/resolve/review.py @@ -3,29 +3,26 @@ from __future__ import annotations import os -import sys import urllib.parse import zipfile from collections.abc import Callable, Iterable from dataclasses import dataclass -from typing import Any, TYPE_CHECKING, TypedDict +from typing import TYPE_CHECKING, TypedDict try: import yaml except ImportError: yaml = None -from core.hashing import compute_hashes, parse_hash_list, stream_hashes +from core.hashing import compute_hashes, stream_hashes from core.memo import DerivedView from model.nodedup import in_nodedup_dir -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.nativemode import digest_algorithm from resolve.acceptance import frontend_digest_matches, inner_rom_check if TYPE_CHECKING: from typing_extensions import Unpack +from resolve.reviewhashes import name_systems BLOCKED_EXTENSIONS = { @@ -102,213 +99,6 @@ class ValidationResult: return "FAIL" if not self.passed else "REVIEW" if self.outcome else "PASS" -def _note_sizes(sizes: dict[str, list], names: list[str], entry: dict) -> None: - """Record the sizes an entry accepts under each of its names. - - An entry that declares no size says nothing about it, so a name is - judged only by the declarations that do. - """ - size = entry.get("size") - accepted = [] - if isinstance(size, list): - accepted = [(int(v), int(v)) for v in size] - elif isinstance(size, int) and size > 0: - accepted = [(size, size)] - if entry.get("min_size") or entry.get("max_size"): - accepted.append((int(entry.get("min_size") or 0), - int(entry.get("max_size") or 2 ** 63))) - for name in names if accepted else []: - sizes.setdefault(name, []).extend(accepted) - - -def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict: - """Load all known hashes from platform configs. - - With the database, `folders` maps each declared hash to the - bios/// folders the collection files its system - under, read from the other files of that system it holds. - """ - known: dict[str, Any] = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(), - "names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}, - "name_systems": {}, "system_dirs": {}, "system_folders": {}} - systems_of: dict[str, set[str]] = {} - folders_of: dict[str, dict[str, int]] = {} - files = (db or {}).get("files", {}) - by_md5 = (db or {}).get("indexes", {}).get("by_md5", {}) - - if not os.path.isdir(platforms_dir) or yaml is None: - return known - - # Read the way verify reads them: inheritance and shared groups resolved, - # and a Recalbox md5 field split into the revisions it lists. The raw - # file kept "a,b,c" as one value, so a PR adding the seventh accepted - # falcon.img was told its hash differs. - for name in list_registered_platforms(platforms_dir): - try: - config = load_platform_config(name, platforms_dir) - except (OSError, yaml.YAMLError) as exc: - print(f"WARNING: {name}: {exc}", file=sys.stderr) - continue - - mode, rule = platform_mode(config), config.get("hash_rule", "") - for system_id, system in config.get("systems", {}).items(): - for file_entry in system.get("files", []): - sha1s = parse_hash_list(file_entry.get("sha1")) - md5s = parse_hash_list(file_entry.get("md5")) - sha256s = parse_hash_list(file_entry.get("sha256")) - known["sha1"].update(sha1s) - known["md5"].update(md5s) - known["sha256"].update(sha256s) - if not (sha1s or md5s or sha256s) and isinstance(file_entry.get("size"), int): - # The resolver's reading: a crc32 counts where no stronger - # hash is declared, bounded by the declared size. - known["crc32"].update( - (crc.zfill(8), file_entry["size"]) - for crc in parse_hash_list(file_entry.get("crc32")) - ) - if "name" in file_entry: - known["names"].add(file_entry["name"]) - _note_sizes(known["sizes"], [file_entry["name"]], file_entry) - # A frontend that hashes a ZIP's member or its members - # together, or that takes any hash at the declared size, - # answers by its own rule, read per entry. - known["entries"].setdefault(file_entry["name"].lower(), []).append( - (file_entry, mode, rule, name) - ) - known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id) - for value in (*sha1s, *md5s): - systems_of.setdefault(value, set()).add(system_id) - for value in (*sha1s, *md5s, *sha256s): - if "name" in file_entry: - known["named"].setdefault(value, set()).add(file_entry["name"]) - _note_folder(folders_of, system_id, files, by_md5, sha1s, md5s, - known["system_dirs"]) - - known["folders"] = _system_homes(systems_of, folders_of) - known["system_folders"] = _single_maker_folders(folders_of) - return known - - -def _note_folder( - folders_of: dict[str, dict[str, int]], system_id: str, files: dict, - by_md5: dict, sha1s: list[str], md5s: list[str], - dirs_of: dict[str, set[str]] | None = None, -) -> None: - """Count the bios/// folder a held file sits in, - and note the directory it sits in under *dirs_of*.""" - held = next((s for s in sha1s if s in files), None) or next( - (by_md5[m] for m in md5s if m in by_md5), None - ) - path = str(files.get(held, {}).get("path", "")) - if dirs_of is not None and "/" in path and "/.variants/" not in path: - dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/") - parts = path.split("/") - if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."): - folder = "/".join(parts[:3]) + "/" - counts = folders_of.setdefault(system_id, {}) - counts[folder] = counts.get(folder, 0) + 1 - - -def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]: - """System id to the folders the collection files it under, for a system - filed under one manufacturer only, the rule _system_homes applies.""" - return { - system_id: set(held_in) for system_id, held_in in folders_of.items() - if len({folder.split("/")[1] for folder in held_in}) == 1 - } - - -def _system_homes( - systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]] -) -> dict[str, set[str]]: - """Hash value to the folders the collection files its systems under. - - A system whose files sit under several manufacturers (arcade sets, - computers sharing ROM chips) names no single home: only a system filed - under one manufacturer says where a newcomer belongs. - """ - homes: dict[str, set[str]] = {} - for value, systems in systems_of.items(): - folders: set[str] = set() - for system_id in systems: - held_in = folders_of.get(system_id, {}) - if len({folder.split("/")[1] for folder in held_in}) == 1: - folders.update(held_in) - if folders: - homes[value] = folders - return homes - - -def load_profile_hashes( - emulators_dir: str, db: dict | None = None -) -> dict[str, dict[str, set[str]]]: - """Hash value to the emulators whose profile declares it, per algorithm. - - A file only a core reads (a standalone emulator's firmware, a game - engine's data) is in no platform list: the review called every such - contribution "not referenced, needs manual review". With the database, - `folders` maps each declared hash to the folders the collection files - the entry's system under, as load_platform_hashes does: a contributor - holding a file only a profile declares was told to pick a - bios/Manufacturer/Console/ folder alone. - """ - known: dict[str, dict] = { - "sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {}, - "named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {}, - } - systems_of: dict[str, set[str]] = {} - folders_of: dict[str, dict[str, int]] = {} - files = (db or {}).get("files", {}) - indexes = (db or {}).get("indexes", {}) - by_md5, by_sha256 = indexes.get("by_md5", {}), indexes.get("by_sha256", {}) - for emulator, profile in load_emulator_profiles(emulators_dir).items(): - declared_systems = profile.get("systems") or [] - for entry in profile.get("files") or []: - if not isinstance(entry, dict): - continue - names = [entry.get("name"), *(entry.get("aliases") or [])] - _note_sizes(known["sizes"], [n for n in names if isinstance(n, str)], entry) - # The resolver's reading: comma lists split (mesence's four - # sha256), and a crc32 counts only where no stronger hash is - # declared, bounded by the declared size (626 entries name a - # file by crc32 alone, clk's Electron os.rom among them). - hashes = { - algo: parse_hash_list(entry.get(algo)) for algo in ("sha1", "sha256", "md5") - } - for algo, values in hashes.items(): - for value in values: - known[algo].setdefault(value, set()).add(emulator) - if isinstance(entry.get("name"), str): - known["named"].setdefault(value, set()).add(entry["name"]) - # The entry's own system, or the profile's when it emulates one. - system = entry.get("system") or ( - declared_systems[0] if len(declared_systems) == 1 else None - ) - if isinstance(system, str): - for value in (v for values in hashes.values() for v in values): - systems_of.setdefault(value, set()).add(system) - for n in names: - if isinstance(n, str): - known["name_systems"].setdefault(n.lower(), set()).add(system) - sha1s = [*hashes["sha1"], *( - by_sha256[v] for v in hashes["sha256"] if v in by_sha256 - )] - _note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"], - known["system_dirs"]) - if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")): - size = entry.get("size") - sizes = [int(v) for v in size] if isinstance(size, list) else ( - [int(size)] if size else [None] - ) - for value in parse_hash_list(entry.get("crc32")): - for accepted in sizes: - key = (value.zfill(8), accepted) - known["crc32"].setdefault(key, set()).add(emulator) - known["folders"] = _system_homes(systems_of, folders_of) - known["system_folders"] = _single_maker_folders(folders_of) - return known - - @dataclass(frozen=True) class _Digests: """The digests of one file or ZIP member, as the hash tables key them.""" @@ -886,14 +676,6 @@ def _directory_tail(db: dict | None, directory: str) -> str: return "" -def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]: - """The systems whose platform or profile entries declare this name.""" - return { - system for table in (platform_hashes, profile_hashes or {}) - for system in table.get("name_systems", {}).get(filename.lower(), ()) - } - - def _variant_home(db: dict | None, name: str, held: str = "", within: set[str] | None = None) -> str: """The folder the collection keeps a name in, for its variants beside it. diff --git a/scripts/resolve/reviewhashes.py b/scripts/resolve/reviewhashes.py new file mode 100644 index 000000000..218dde51d --- /dev/null +++ b/scripts/resolve/reviewhashes.py @@ -0,0 +1,233 @@ +"""The hashes a review knows: every file the platforms and the profiles declare, with its folder and systems.""" + +from __future__ import annotations + +import os +import sys +from typing import Any + +try: + import yaml +except ImportError: + yaml = None + +from core.hashing import parse_hash_list +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 platform_mode + + +def _note_sizes(sizes: dict[str, list], names: list[str], entry: dict) -> None: + """Record the sizes an entry accepts under each of its names. + + An entry that declares no size says nothing about it, so a name is + judged only by the declarations that do. + """ + size = entry.get("size") + accepted = [] + if isinstance(size, list): + accepted = [(int(v), int(v)) for v in size] + elif isinstance(size, int) and size > 0: + accepted = [(size, size)] + if entry.get("min_size") or entry.get("max_size"): + accepted.append((int(entry.get("min_size") or 0), + int(entry.get("max_size") or 2 ** 63))) + for name in names if accepted else []: + sizes.setdefault(name, []).extend(accepted) + + +def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict: + """Load all known hashes from platform configs. + + With the database, `folders` maps each declared hash to the + bios/// folders the collection files its system + under, read from the other files of that system it holds. + """ + known: dict[str, Any] = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(), + "names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}, + "name_systems": {}, "system_dirs": {}, "system_folders": {}} + systems_of: dict[str, set[str]] = {} + folders_of: dict[str, dict[str, int]] = {} + files = (db or {}).get("files", {}) + by_md5 = (db or {}).get("indexes", {}).get("by_md5", {}) + + if not os.path.isdir(platforms_dir) or yaml is None: + return known + + # Read the way verify reads them: inheritance and shared groups resolved, + # and a Recalbox md5 field split into the revisions it lists. The raw + # file kept "a,b,c" as one value, so a PR adding the seventh accepted + # falcon.img was told its hash differs. + for name in list_registered_platforms(platforms_dir): + try: + config = load_platform_config(name, platforms_dir) + except (OSError, yaml.YAMLError) as exc: + print(f"WARNING: {name}: {exc}", file=sys.stderr) + continue + + mode, rule = platform_mode(config), config.get("hash_rule", "") + for system_id, system in config.get("systems", {}).items(): + for file_entry in system.get("files", []): + sha1s = parse_hash_list(file_entry.get("sha1")) + md5s = parse_hash_list(file_entry.get("md5")) + sha256s = parse_hash_list(file_entry.get("sha256")) + known["sha1"].update(sha1s) + known["md5"].update(md5s) + known["sha256"].update(sha256s) + if not (sha1s or md5s or sha256s) and isinstance(file_entry.get("size"), int): + # The resolver's reading: a crc32 counts where no stronger + # hash is declared, bounded by the declared size. + known["crc32"].update( + (crc.zfill(8), file_entry["size"]) + for crc in parse_hash_list(file_entry.get("crc32")) + ) + if "name" in file_entry: + known["names"].add(file_entry["name"]) + _note_sizes(known["sizes"], [file_entry["name"]], file_entry) + # A frontend that hashes a ZIP's member or its members + # together, or that takes any hash at the declared size, + # answers by its own rule, read per entry. + known["entries"].setdefault(file_entry["name"].lower(), []).append( + (file_entry, mode, rule, name) + ) + known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id) + for value in (*sha1s, *md5s): + systems_of.setdefault(value, set()).add(system_id) + for value in (*sha1s, *md5s, *sha256s): + if "name" in file_entry: + known["named"].setdefault(value, set()).add(file_entry["name"]) + _note_folder(folders_of, system_id, files, by_md5, sha1s, md5s, + known["system_dirs"]) + + known["folders"] = _system_homes(systems_of, folders_of) + known["system_folders"] = _single_maker_folders(folders_of) + return known + + +def _note_folder( + folders_of: dict[str, dict[str, int]], system_id: str, files: dict, + by_md5: dict, sha1s: list[str], md5s: list[str], + dirs_of: dict[str, set[str]] | None = None, +) -> None: + """Count the bios/// folder a held file sits in, + and note the directory it sits in under *dirs_of*.""" + held = next((s for s in sha1s if s in files), None) or next( + (by_md5[m] for m in md5s if m in by_md5), None + ) + path = str(files.get(held, {}).get("path", "")) + if dirs_of is not None and "/" in path and "/.variants/" not in path: + dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/") + parts = path.split("/") + if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."): + folder = "/".join(parts[:3]) + "/" + counts = folders_of.setdefault(system_id, {}) + counts[folder] = counts.get(folder, 0) + 1 + + +def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]: + """System id to the folders the collection files it under, for a system + filed under one manufacturer only, the rule _system_homes applies.""" + return { + system_id: set(held_in) for system_id, held_in in folders_of.items() + if len({folder.split("/")[1] for folder in held_in}) == 1 + } + + +def _system_homes( + systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]] +) -> dict[str, set[str]]: + """Hash value to the folders the collection files its systems under. + + A system whose files sit under several manufacturers (arcade sets, + computers sharing ROM chips) names no single home: only a system filed + under one manufacturer says where a newcomer belongs. + """ + homes: dict[str, set[str]] = {} + for value, systems in systems_of.items(): + folders: set[str] = set() + for system_id in systems: + held_in = folders_of.get(system_id, {}) + if len({folder.split("/")[1] for folder in held_in}) == 1: + folders.update(held_in) + if folders: + homes[value] = folders + return homes + + +def load_profile_hashes( + emulators_dir: str, db: dict | None = None +) -> dict[str, dict[str, set[str]]]: + """Hash value to the emulators whose profile declares it, per algorithm. + + A file only a core reads (a standalone emulator's firmware, a game + engine's data) is in no platform list: the review called every such + contribution "not referenced, needs manual review". With the database, + `folders` maps each declared hash to the folders the collection files + the entry's system under, as load_platform_hashes does: a contributor + holding a file only a profile declares was told to pick a + bios/Manufacturer/Console/ folder alone. + """ + known: dict[str, dict] = { + "sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {}, + "named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {}, + } + systems_of: dict[str, set[str]] = {} + folders_of: dict[str, dict[str, int]] = {} + files = (db or {}).get("files", {}) + indexes = (db or {}).get("indexes", {}) + by_md5, by_sha256 = indexes.get("by_md5", {}), indexes.get("by_sha256", {}) + for emulator, profile in load_emulator_profiles(emulators_dir).items(): + declared_systems = profile.get("systems") or [] + for entry in profile.get("files") or []: + if not isinstance(entry, dict): + continue + names = [entry.get("name"), *(entry.get("aliases") or [])] + _note_sizes(known["sizes"], [n for n in names if isinstance(n, str)], entry) + # The resolver's reading: comma lists split (mesence's four + # sha256), and a crc32 counts only where no stronger hash is + # declared, bounded by the declared size (626 entries name a + # file by crc32 alone, clk's Electron os.rom among them). + hashes = { + algo: parse_hash_list(entry.get(algo)) for algo in ("sha1", "sha256", "md5") + } + for algo, values in hashes.items(): + for value in values: + known[algo].setdefault(value, set()).add(emulator) + if isinstance(entry.get("name"), str): + known["named"].setdefault(value, set()).add(entry["name"]) + # The entry's own system, or the profile's when it emulates one. + system = entry.get("system") or ( + declared_systems[0] if len(declared_systems) == 1 else None + ) + if isinstance(system, str): + for value in (v for values in hashes.values() for v in values): + systems_of.setdefault(value, set()).add(system) + for n in names: + if isinstance(n, str): + known["name_systems"].setdefault(n.lower(), set()).add(system) + sha1s = [*hashes["sha1"], *( + by_sha256[v] for v in hashes["sha256"] if v in by_sha256 + )] + _note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"], + known["system_dirs"]) + if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")): + size = entry.get("size") + sizes = [int(v) for v in size] if isinstance(size, list) else ( + [int(size)] if size else [None] + ) + for value in parse_hash_list(entry.get("crc32")): + for accepted in sizes: + key = (value.zfill(8), accepted) + known["crc32"].setdefault(key, set()).add(emulator) + known["folders"] = _system_homes(systems_of, folders_of) + known["system_folders"] = _single_maker_folders(folders_of) + return known + + +def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]: + """The systems whose platform or profile entries declare this name.""" + return { + system for table in (platform_hashes, profile_hashes or {}) + for system in table.get("name_systems", {}).get(filename.lower(), ()) + } diff --git a/scripts/resolve/truth.py b/scripts/resolve/truth.py index 4a2ed91f9..9d56a8c1f 100644 --- a/scripts/resolve/truth.py +++ b/scripts/resolve/truth.py @@ -13,7 +13,7 @@ import os from resolve.launches import PlatformLaunches from resolve.standalone import platform_layouts, platform_launches from resolve.cores import resolve_platform_cores -from resolve.reconcile import contradicts, shares_hash +from resolve.nativemodel import contradicts, shares_hash from model.alternatives import groups_of from core.hashing import HASH_FIELDS, compute_hashes, declared_hashes, parse_hash_list from resolve.entryscope import ( diff --git a/scripts/sitegen/build.py b/scripts/sitegen/build.py index 5f66ae110..c386d0043 100644 --- a/scripts/sitegen/build.py +++ b/scripts/sitegen/build.py @@ -30,7 +30,7 @@ from packs.crossref import whole_tree_gaps from packs.supplemental import SupplementalIndex from acquire.provenance import build_report, profile_needs from resolve.cores import resolve_platform_cores -from resolve.review import load_platform_hashes, load_profile_hashes +from resolve.reviewhashes import load_platform_hashes, load_profile_hashes from installer_build.handhelds import GROUP_PAGE from sitegen import ( agents as siteagents, diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index c87f30c7e..c3d010dfe 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -26,7 +26,8 @@ import sys sys.path.insert(0, os.path.dirname(__file__)) from model.database import load_optional_database from core.cli import add_repo_inputs, require_directory -from resolve.review import load_platform_hashes, load_profile_hashes, validate_file +from resolve.reviewhashes import load_platform_hashes, load_profile_hashes +from resolve.review import validate_file from devtools.reviewfiles import ChangedFilesUnreadable, SelectionError, files_to_validate, place from devtools.reviewreport import json_rows, markdown_report, text_lines diff --git a/tests/test_batocera_md5_list.py b/tests/test_batocera_md5_list.py index 6e6d24863..d735e3215 100644 --- a/tests/test_batocera_md5_list.py +++ b/tests/test_batocera_md5_list.py @@ -20,7 +20,8 @@ from pathlib import Path from resolve.localfile import resolve_local_file from exporter import discover_exporters from exporter.landed import landed_changes -from resolve.reconcile import NativeFile, build_native_model +from resolve.nativemodel import NativeFile +from resolve.reconcile import build_native_model from exporter.batocera_exporter import md5_list_support from scraper import rocknix_scraper from scraper.base_scraper import md5_field, requirement_entry diff --git a/tests/test_elec_scrapers.py b/tests/test_elec_scrapers.py index 74272f96a..6eae0d96e 100644 --- a/tests/test_elec_scrapers.py +++ b/tests/test_elec_scrapers.py @@ -271,7 +271,7 @@ class TheExportKeepsTheirShape(unittest.TestCase): def test_paths_start_where_the_list_starts(self): from exporter.amberelec_exporter import Exporter as Amber - from resolve.reconcile import NativeFile + from resolve.nativemodel import NativeFile from exporter.knulli_exporter import Exporter as Knulli fe = NativeFile("neogeo.zip", "neogeo/neogeo.zip", "neogeo") diff --git a/tests/test_export_counts.py b/tests/test_export_counts.py index 8cb55d330..124525309 100644 --- a/tests/test_export_counts.py +++ b/tests/test_export_counts.py @@ -16,7 +16,8 @@ import unittest from collections import OrderedDict from pathlib import Path -from resolve.reconcile import NativeFile, NativeSystem, Report, build_native_model +from resolve.nativemodel import NativeFile, NativeSystem, Report +from resolve.reconcile import build_native_model from exporter.bizhawk_exporter import Exporter as BizHawk from exporter.misterfpga_exporter import Exporter as Mister from exporter.romm_exporter import Exporter as Romm @@ -191,7 +192,7 @@ class RetroBatKeepsWhatWeDoNotModel(unittest.TestCase): ]}, "newsys": {"name": "New", "biosFiles": [{"md5": B, "file": "bios/new.bin"}]}, } - from resolve.reconcile import Report + from resolve.nativemodel import Report produced = json.loads(RetroBat().render( systems, Report(), {"batocera-systems.json": json.dumps(original)}, @@ -251,7 +252,7 @@ class PureDataExportsKeepWhatWeDoNotModel(unittest.TestCase): filled=[]) def test_recalbox(self): - from resolve.reconcile import Report + from resolve.nativemodel import Report from exporter.recalbox_exporter import Exporter as Recalbox fe = self._file("a.bin", "nes", destination="nes/a.bin", core="libretro:fceumm") @@ -277,7 +278,7 @@ class PureDataExportsKeepWhatWeDoNotModel(unittest.TestCase): self.assertIn('mandatory="false"', produced) def test_system_dat(self): - from resolve.reconcile import Report + from resolve.nativemodel import Report fe = self._file("a.bin", "Nintendo - NES") systems = {"Nintendo - NES": NativeSystem("Nintendo - NES", files=[fe])} @@ -301,7 +302,7 @@ class PureDataExportsKeepWhatWeDoNotModel(unittest.TestCase): def test_two_additions_differing_by_directory_are_two_lines(self): """PCSX2's vulkan and opengl convert.glsl were both written under the bare name, so the second was dropped and still counted as added.""" - from resolve.reconcile import Report + from resolve.nativemodel import Report shaders = [ NativeFile("convert.glsl", f"pcsx2/resources/shaders/{api}/convert.glsl", @@ -989,7 +990,7 @@ class TheSummaryCountsWhatTheFileCarries(unittest.TestCase): def test_romm_drops_the_hashes_it_counts_cleared(self): from exporter.landed import landed_changes - from resolve.reconcile import Report + from resolve.nativemodel import Report fe = self._contradicted() systems = {"psx": NativeSystem("psx", files=[fe])} diff --git a/tests/test_exporters.py b/tests/test_exporters.py index 96796c814..1458be147 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -38,7 +38,8 @@ from exporter import discover_exporters from exporter.base_exporter import BaseExporter from exporter.originals import SOURCES_INDEX, collect_originals, fetch, pinned_base, source_key from exporter.landed import landed_changes -from resolve.reconcile import NativeFile, NativeSystem, Report, build_native_model +from resolve.nativemodel import NativeFile, NativeSystem, Report +from resolve.reconcile import build_native_model REPO_ROOT = Path(__file__).resolve().parent.parent @@ -760,7 +761,7 @@ class SearchOrder(unittest.TestCase): """PicoDrive loads the first file of each region's list. RetroPie names one per region, but the export appended three more, which the sentence reads as three more required files.""" - from resolve.reconcile import NativeSystem + from resolve.nativemodel import NativeSystem def cd(name, region, rank): return NativeFile(name=name, destination=name, native_system="segacd", truth={ @@ -795,7 +796,7 @@ class SearchOrder(unittest.TestCase): """flycast's help names the Dreamcast BIOS, then the Naomi/Atomiswave ones. naomi2.zip, an arcade archive, went into the Dreamcast list: only the first BIOS clause was read.""" - from resolve.reconcile import NativeSystem + from resolve.nativemodel import NativeSystem def entry(name, system): return NativeFile(name=name, destination=f"dc/{name}", native_system=system, @@ -2871,7 +2872,7 @@ class ARecordDescribesOneDump(unittest.TestCase): export wrote v2.0's crc beside v2.1's md5 and sha1.""" def test_the_platform_record_stays_whole_when_the_truth_accepts_it(self): - from resolve.reconcile import NativeFile + from resolve.nativemodel import NativeFile fe = NativeFile( name="syscard2.pce", destination="syscard2.pce", native_system="pce", @@ -2884,7 +2885,7 @@ class ARecordDescribesOneDump(unittest.TestCase): self.assertEqual(fe.record_hash("md5"), "3cdd6614" + "0" * 24) def test_a_field_only_the_truth_names_is_written_when_unambiguous(self): - from resolve.reconcile import NativeFile + from resolve.nativemodel import NativeFile one = NativeFile(name="a", destination="a", native_system="s", platform={"crc32": "11111111"}, diff --git a/tests/test_site_wanted.py b/tests/test_site_wanted.py index d072a36f1..21af41289 100644 --- a/tests/test_site_wanted.py +++ b/tests/test_site_wanted.py @@ -28,7 +28,7 @@ from pathlib import Path from sitegen import gaps from sitegen import lookup from sitegen import wanted as sitewanted -from resolve import review, sendable +from resolve import review, reviewhashes, sendable import yaml from model.database import load_database from tests.test_site_pronouns import pronouns @@ -159,7 +159,7 @@ class _World(unittest.TestCase): ]}] self.platform_hashes = {"sha1": set(), "md5": set(), "names": set(), "folders": {}, "named": {}} - self.profile_hashes = review.load_profile_hashes(str(emulators), self.db) + self.profile_hashes = reviewhashes.load_profile_hashes(str(emulators), self.db) self.placer = sitewanted.Placer(self.db, self.platform_hashes, self.profile_hashes) self.data = sitewanted.build_wanted( self.profiles, self.coverages, self.gap_report, self.db, self.placer, @@ -606,8 +606,8 @@ class AFolderComesFromTheSystem(unittest.TestCase): if not (REPO_ROOT / "database.json").is_file(): raise unittest.SkipTest("no database") cls.db = load_database(str(REPO_ROOT / "database.json")) - cls.platform_hashes = review.load_platform_hashes(str(REPO_ROOT / "platforms"), cls.db) - cls.profile_hashes = review.load_profile_hashes(str(REPO_ROOT / "emulators"), cls.db) + cls.platform_hashes = reviewhashes.load_platform_hashes(str(REPO_ROOT / "platforms"), cls.db) + cls.profile_hashes = reviewhashes.load_profile_hashes(str(REPO_ROOT / "emulators"), cls.db) def place(self, systems: list[str], directory: str) -> review.Placement: return review.placement([], "config.ini", self.db, self.platform_hashes, @@ -655,8 +655,8 @@ class ThePublishedList(unittest.TestCase): def test_every_folder_is_the_reviews(self): placer = sitewanted.Placer( - self.db, review.load_platform_hashes(str(REPO_ROOT / "platforms"), self.db), - review.load_profile_hashes(str(REPO_ROOT / "emulators"), self.db)) + self.db, reviewhashes.load_platform_hashes(str(REPO_ROOT / "platforms"), self.db), + reviewhashes.load_profile_hashes(str(REPO_ROOT / "emulators"), self.db)) # An entry placed by its hashes. The others take their folder from # their system and directory, which the list does not carry: the # synthetic world above holds them to the rule. diff --git a/tests/test_truth_data_dir_readers.py b/tests/test_truth_data_dir_readers.py index 7b36a00da..9ded01547 100644 --- a/tests/test_truth_data_dir_readers.py +++ b/tests/test_truth_data_dir_readers.py @@ -18,7 +18,7 @@ import unittest import unittest.mock from pathlib import Path -from resolve.reconcile import checked_hashes +from resolve.nativemodel import checked_hashes from resolve.truth import generate_platform_truth REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_validate_pr.py b/tests/test_validate_pr.py index 82e436057..0c397abd5 100644 --- a/tests/test_validate_pr.py +++ b/tests/test_validate_pr.py @@ -18,6 +18,7 @@ from pathlib import Path from devtools import reviewfiles, reviewreport from resolve import review +from resolve.reviewhashes import load_profile_hashes, load_platform_hashes REPO_ROOT = Path(__file__).resolve().parent.parent @@ -132,7 +133,7 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): "emulator: Engine\ntype: standalone\nsystems: [x]\nfiles:\n" f" - name: \"data.bin\"\n sha1: \"{hashlib.sha1(data).hexdigest()}\"\n" ) - known = review.load_profile_hashes(str(emulators)) + known = load_profile_hashes(str(emulators)) result = review.validate_file( self._bios_file("bios/Maker/Engine/data.bin", data), None, EMPTY_HASHES, known, ) @@ -155,7 +156,7 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): ) db = {"files": {hashlib.sha1(held).hexdigest(): {"path": "bios/Maker/Console/a.bin"}}, "indexes": {"by_md5": {}, "by_sha256": {}}} - known = review.load_profile_hashes(str(emulators), db) + known = load_profile_hashes(str(emulators), db) result = review.validate_file( self._bios_file("Downloads/b.bin", missing), db, EMPTY_HASHES, known, ) @@ -203,7 +204,7 @@ class ADeclaredFileBesideItsHeldNameIsAVariant(_Fixture): ) db = {"files": {"a" * 40: {"path": "bios/Maker/Console/v.bin"}}, "indexes": {"by_md5": {}, "by_sha256": {}, "by_name": {"v.bin": ["a" * 40]}}} - known = review.load_profile_hashes(str(emulators), db) + known = load_profile_hashes(str(emulators), db) result = review.validate_file( self._bios_file("card/v.bin", data), db, EMPTY_HASHES, known) slot = f"bios/Maker/Console/.variants/v.bin.{result.sha1[:8]}" @@ -434,7 +435,7 @@ class PlacementBySystem(_Fixture): db = {"files": {"aaaa": {"path": "bios/Arcade/MAME/a.zip"}, "bbbb": {"path": "bios/Apple/Apple II/b.zip"}}, "indexes": {"by_md5": {}}} - known = review.load_platform_hashes(str(platforms), db) + known = load_platform_hashes(str(platforms), db) self.assertEqual(known["folders"], {}) @@ -498,7 +499,7 @@ class Reporting(_Fixture): class PlatformHashLoading(_Fixture): def test_missing_directory_yields_empty_sets(self): - known = review.load_platform_hashes(str(self.tmp / "absent")) + known = load_platform_hashes(str(self.tmp / "absent")) self.assertEqual(known, {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(), "names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}, "name_systems": {}, "system_dirs": {}, @@ -519,7 +520,7 @@ class PlatformHashLoading(_Fixture): f" sha1: {'a' * 40}\n" f" md5: {'b' * 32}\n" ) - known = review.load_platform_hashes(str(platforms)) + known = load_platform_hashes(str(platforms)) self.assertIn("a" * 40, known["sha1"]) self.assertIn("b" * 32, known["md5"]) self.assertIn("boot.bin", known["names"]) @@ -539,7 +540,7 @@ class ThePlatformsOwnCheckDecides(_Fixture): encoding="utf-8") (platforms / "p.yml").write_text(f"platform: P\nsystems:\n s:\n files:\n{systems}", encoding="utf-8") - return review.load_platform_hashes(str(platforms)) + return load_platform_hashes(str(platforms)) def _zip(self) -> str: import zipfile @@ -682,7 +683,7 @@ class ProfileHashesReadAsTheResolverDoes(unittest.TestCase): " - name: bsx.bin\n sha256: \"aa,bb\"\n", encoding="utf-8", ) - known = review.load_profile_hashes(tmp) + known = load_profile_hashes(tmp) self.assertEqual(known["crc32"][("bf63fb1f", 16384)], {"core"}) self.assertIn("bb", known["sha256"]) diff --git a/tests/test_validate_pr_hashes.py b/tests/test_validate_pr_hashes.py index 3c268f784..77207e507 100644 --- a/tests/test_validate_pr_hashes.py +++ b/tests/test_validate_pr_hashes.py @@ -20,9 +20,9 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class EveryAcceptedRevisionIsKnown(unittest.TestCase): def test_multi_hash_members_are_known(self): - from resolve import review + from resolve.reviewhashes import load_platform_hashes - known = review.load_platform_hashes(str(REPO_ROOT / "platforms")) + known = load_platform_hashes(str(REPO_ROOT / "platforms")) raw = yaml.safe_load((REPO_ROOT / "platforms" / "recalbox.yml").read_text()) listed = [ value.strip().lower()