mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-28 20:38:52 -06:00
refactor: move leaf modules into packages
core: hashing, artifacts, ziptools, deterministic_zip, romdir, sect233r1, crypto_verify, paths (REPO_ROOT). model: safeparse (needs yaml), dumpcatalog, largefiles, alternatives. resolve: nativemode, validation, launchers, slot, truth, gamedata, and exporter/baseline.py and exporter/candidates.py as resolve/reconcile.py and resolve/categories.py, which truth and gamedata read. Every importer follows. Modules one level deeper read the repository root from core.paths instead of __file__.
This commit is contained in:
1 parent
23d8a770f1
commit
c784aef883
167 files changed
+412
-434
No files matched your search
@@ -9,7 +9,7 @@ every build, and an addition is written the same way.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .baseline import NativeFile
|
||||
from resolve.reconcile import NativeFile
|
||||
from .batocera_exporter import Exporter as BatoceraExporter
|
||||
|
||||
SOURCE_URL = (
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Generic, TypeVar, Union
|
||||
|
||||
from .baseline import NativeFile, NativeSystem, Report
|
||||
from resolve.reconcile 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).
|
||||
|
||||
@@ -1,826 +0,0 @@
|
||||
"""Reconciliation of a platform's own declarations with the ground truth.
|
||||
|
||||
An export is not the truth rendered in a native syntax. It is the platform's
|
||||
file, corrected: what the truth can prove is applied, what it says nothing
|
||||
about is left alone, and what it knows and the platform lacks is added. A
|
||||
platform that loses two thirds of its systems to an export cannot use it.
|
||||
|
||||
Systems are keyed by the identifier the platform itself uses. Several of our
|
||||
slugs collapse onto one native id (Recalbox files pcengine, pcenginecd and
|
||||
supergrafx under one slug) and one slug can carry several native ids, so the
|
||||
grouping is rebuilt from the per-file native_system the scrapers record.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from common import _norm_system_id
|
||||
|
||||
HASH_FIELDS = ("sha1", "md5", "sha256", "crc32")
|
||||
|
||||
|
||||
def _hash_values(entry: dict, field_name: str) -> list[str]:
|
||||
"""Return a hash field as a list, whatever shape it was written in."""
|
||||
raw = entry.get(field_name)
|
||||
if not raw:
|
||||
return []
|
||||
if isinstance(raw, list):
|
||||
return [str(v).strip().lower() for v in raw if str(v).strip()]
|
||||
return [v.strip().lower() for v in str(raw).split(",") if v.strip()]
|
||||
|
||||
|
||||
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 _hash_values(entry, f)]
|
||||
if checked and all(len(set(_hash_values(entry, 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.
|
||||
"""
|
||||
checked = checked_hashes(truth_entry) or {}
|
||||
theirs = comparable(platform_entry)
|
||||
return [
|
||||
field_name for field_name in HASH_FIELDS
|
||||
if (ours := set(_hash_values(checked, field_name)))
|
||||
and (held := set(_hash_values(theirs, field_name)))
|
||||
and not ours & held
|
||||
]
|
||||
|
||||
|
||||
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(_hash_values(entry or {}, 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 _hash_values(self.platform or {}, field_name)
|
||||
truth_values = _hash_values(self._checked_truth, field_name)
|
||||
platform_values = _hash_values(self.platform or {}, 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 = _hash_values(self.platform or {}, field_name)
|
||||
return values[0] if values else ""
|
||||
source = self._identity_source()
|
||||
truth_values = _hash_values(self._checked_truth, field_name)
|
||||
platform_values = _hash_values(self.platform or {}, 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 (
|
||||
file_entry.get("native_system")
|
||||
or sys_data.get("native_id")
|
||||
or sys_key
|
||||
)
|
||||
|
||||
|
||||
def _match_key(entry: dict) -> tuple[str, str]:
|
||||
dest = str(entry.get("destination") or entry.get("path") or entry.get("name", ""))
|
||||
return dest.casefold(), str(entry.get("name", "")).casefold()
|
||||
|
||||
|
||||
def _names(entry: dict) -> set[str]:
|
||||
"""The names an entry answers to: its own and the aliases it declares."""
|
||||
return {
|
||||
str(n).casefold()
|
||||
for n in (entry.get("name", ""), *(entry.get("aliases") or []))
|
||||
if n
|
||||
}
|
||||
|
||||
|
||||
def by_destination(truth_entry: dict, platform_entry: dict) -> bool:
|
||||
"""The platform's destination ends in the path the truth declares.
|
||||
|
||||
Dolphin writes dolphin-emu/Sys/GC/USA/IPL.bin for the truth's
|
||||
GC/USA/IPL.bin. A bare name is no path: dc/boot.bin ends in /boot.bin,
|
||||
and fbneo's 480-byte boot.bin is not that 2 MB Dreamcast BIOS.
|
||||
"""
|
||||
t_dest = _match_key(truth_entry)[0]
|
||||
theirs = _match_key(platform_entry)[0]
|
||||
if not t_dest:
|
||||
return False
|
||||
return theirs == t_dest or ("/" in t_dest and theirs.endswith("/" + t_dest))
|
||||
|
||||
|
||||
def by_name(truth_entry: dict, platform_entry: dict) -> bool:
|
||||
"""One of the truth's names, in the same directory, at the same size."""
|
||||
t_dest = _match_key(truth_entry)[0]
|
||||
theirs_dest, theirs = _match_key(platform_entry)
|
||||
if not theirs or theirs not in _names(truth_entry):
|
||||
return False
|
||||
# Two declared directories that differ name two files: the truth's
|
||||
# BeebFile/BIOS.rom is not Recalbox's np2kai/bios.rom.
|
||||
if "/" in t_dest and "/" in theirs_dest and not theirs_dest.endswith(
|
||||
"/" + t_dest.rsplit("/", 1)[0].rsplit("/", 1)[-1] + "/" + theirs
|
||||
):
|
||||
return False
|
||||
# A shared name with two declared sizes is two files: fbneo's 480-byte
|
||||
# boot.bin is not RomM's 2 MB Dreamcast boot.bin.
|
||||
t_size = truth_entry.get("size")
|
||||
p_size = platform_entry.get("size")
|
||||
return not (isinstance(t_size, int) and isinstance(p_size, int) and t_size != p_size)
|
||||
|
||||
|
||||
def by_hash(truth_entry: dict, platform_entry: dict) -> bool:
|
||||
"""A value on any of the four hash fields in common: a renamed file."""
|
||||
ours = {v for f in HASH_FIELDS for v in _hash_values(truth_entry, f)}
|
||||
if not ours:
|
||||
return False
|
||||
theirs = comparable(platform_entry)
|
||||
return bool(ours & {v for f in HASH_FIELDS for v in _hash_values(theirs, f)})
|
||||
|
||||
|
||||
def _contradicts(truth_entry: dict, platform_entry: dict) -> bool:
|
||||
"""A hash both entries declare, without a value in common."""
|
||||
platform_entry = comparable(platform_entry)
|
||||
return any(
|
||||
(ours := set(_hash_values(truth_entry, f)))
|
||||
and (theirs := set(_hash_values(platform_entry, f)))
|
||||
and not ours & theirs
|
||||
for f in HASH_FIELDS
|
||||
)
|
||||
|
||||
|
||||
def _agreeing(test: Callable[[dict, dict], bool]) -> Callable[[dict, dict], bool]:
|
||||
def agrees(truth_entry: dict, platform_entry: dict) -> bool:
|
||||
return test(truth_entry, platform_entry) and not _contradicts(
|
||||
truth_entry, platform_entry
|
||||
)
|
||||
return agrees
|
||||
|
||||
|
||||
_PAIRING_TESTS = (
|
||||
_agreeing(by_destination),
|
||||
_agreeing(by_name),
|
||||
by_hash,
|
||||
by_destination,
|
||||
by_name,
|
||||
)
|
||||
|
||||
|
||||
def pair_entries(truth_entries: list[dict], candidates: list[dict]) -> dict[int, int]:
|
||||
"""Which platform entry each truth entry describes, as index -> index.
|
||||
|
||||
The one rule export_native and diff_truth read. Each test runs over
|
||||
every truth entry and every candidate before the next one does:
|
||||
claimed entry by entry, dosbox-x's system.rom took np2kai/BIOS.ROM by
|
||||
its alias before np2kai's own np2kai/bios.rom was tried, and wrote an
|
||||
IBM PCjr md5 on it. A path or a name that contradicts a hash comes
|
||||
after the hash: the truth's MSX.rom carries bluemsx's path and fmsx's
|
||||
md5, and fmsx's own line holds that md5. An entry never answers for two.
|
||||
"""
|
||||
pairs: dict[int, int] = {}
|
||||
claimed: set[int] = set()
|
||||
for test in _PAIRING_TESTS:
|
||||
for t_index, truth_entry in enumerate(truth_entries):
|
||||
# A label answers for no name or path, only for its content.
|
||||
if t_index in pairs or (test is not by_hash and is_label(truth_entry)):
|
||||
continue
|
||||
for index, candidate in enumerate(candidates):
|
||||
if index not in claimed and test(truth_entry, candidate):
|
||||
pairs[t_index] = index
|
||||
claimed.add(index)
|
||||
break
|
||||
return pairs
|
||||
|
||||
|
||||
def platform_declares(truth_entry: dict, candidates: list[dict]) -> bool:
|
||||
"""A file another truth entry already claimed is still the platform's
|
||||
file, not one it lacks: scph101.bin, declared by two PSX cores. The
|
||||
same content under another name is not: fuse opens fuse/128-1.rom by
|
||||
name, and Recalbox's fuse/128p-1.rom holding that dump does not serve
|
||||
it."""
|
||||
return any(
|
||||
by_destination(truth_entry, c) or by_name(truth_entry, c) for c in candidates
|
||||
)
|
||||
|
||||
|
||||
def _platform_systems(scraped_systems: dict, report: Report) -> dict[str, NativeSystem]:
|
||||
"""Pass 1: the platform's own file, grouped as the platform groups it."""
|
||||
systems: dict[str, NativeSystem] = {}
|
||||
for sys_key, sys_data in scraped_systems.items():
|
||||
for file_entry in sys_data.get("files", []):
|
||||
native_id = _native_id_of(sys_key, sys_data, file_entry)
|
||||
system = systems.get(native_id)
|
||||
if system is None:
|
||||
system = NativeSystem(
|
||||
native_id=native_id,
|
||||
name=str(file_entry.get("native_name") or sys_data.get("name", "")),
|
||||
from_platform=True,
|
||||
)
|
||||
systems[native_id] = system
|
||||
report.systems_kept += 1
|
||||
name = str(file_entry.get("name", ""))
|
||||
destination = str(file_entry.get("destination") or name)
|
||||
system.files.append(
|
||||
NativeFile(
|
||||
name=name,
|
||||
destination=destination,
|
||||
native_system=native_id,
|
||||
platform=file_entry,
|
||||
composite_md5=file_entry.get("zip_digest") == "composite"
|
||||
or bool(file_entry.get("zipped_file")),
|
||||
)
|
||||
)
|
||||
report.files_kept += 1
|
||||
return systems
|
||||
|
||||
|
||||
def _correct_matched(matched: NativeFile, truth_entry: dict, report: Report) -> None:
|
||||
"""Record what the truth corrects or fills on the platform's own entry."""
|
||||
matched.truth = truth_entry
|
||||
checked = checked_hashes(truth_entry) or {}
|
||||
contradicted = contradicted_hashes(truth_entry, matched.platform)
|
||||
for field_name in HASH_FIELDS:
|
||||
if field_name == "md5" and matched.composite_md5:
|
||||
continue
|
||||
if field_name in contradicted:
|
||||
matched.corrections.append(field_name)
|
||||
report.hashes_corrected.append(
|
||||
f"{matched.native_system}/{matched.name} {field_name}"
|
||||
)
|
||||
elif _hash_values(checked, field_name) and not _hash_values(
|
||||
comparable(matched.platform), field_name
|
||||
):
|
||||
matched.filled.append(field_name)
|
||||
t_req = truth_entry.get("required")
|
||||
p_req = (matched.platform or {}).get("required")
|
||||
# A file a core takes as one of a set has no requirement of
|
||||
# its own: a platform line cannot say "one of these", so
|
||||
# truth leaves its value as written rather than claim
|
||||
# every member optional or every member needed.
|
||||
if (
|
||||
t_req is not None
|
||||
and p_req is not None
|
||||
and bool(t_req) != bool(p_req)
|
||||
and not (truth_entry.get("one_of_required") and not t_req)
|
||||
):
|
||||
matched.corrections.append("required")
|
||||
report.required_corrected.append(
|
||||
f"{matched.native_system}/{matched.name}"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _TruthPass:
|
||||
"""Pass 2: the truth applied onto the platform's grouping."""
|
||||
|
||||
systems: dict[str, NativeSystem]
|
||||
report: Report
|
||||
scraped_systems: dict
|
||||
composite_zips: bool
|
||||
# Which native ids a truth system may contribute to.
|
||||
norm_to_scraped: dict[str, str] = field(init=False)
|
||||
# Every system the platform names, files or none: an addition elsewhere
|
||||
# is filed under our own slug.
|
||||
platform_ids: set[str] = field(init=False)
|
||||
native_by_norm: dict[str, str] = field(init=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
scraped_systems = self.scraped_systems
|
||||
self.norm_to_scraped = {
|
||||
_norm_system_id(key): key for key in scraped_systems
|
||||
}
|
||||
self.platform_ids = {
|
||||
native_id
|
||||
for key, sys_data in scraped_systems.items()
|
||||
for native_id in (
|
||||
sys_data.get("native_id") or key,
|
||||
*(_native_id_of(key, sys_data, fe) for fe in sys_data.get("files", [])),
|
||||
)
|
||||
}
|
||||
self.native_by_norm = {}
|
||||
for system in self.systems.values():
|
||||
self.native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id)
|
||||
|
||||
def target_native_ids(self, truth_sid: str) -> tuple[list[str], bool]:
|
||||
"""The native ids a truth system spans, and whether the first one
|
||||
is where an addition belongs without asking which core reads it."""
|
||||
scraped_systems = self.scraped_systems
|
||||
scraped_key = truth_sid if truth_sid in scraped_systems else None
|
||||
if scraped_key is None:
|
||||
scraped_key = self.norm_to_scraped.get(_norm_system_id(truth_sid))
|
||||
if scraped_key is not None:
|
||||
sys_data = scraped_systems[scraped_key]
|
||||
ids = {
|
||||
_native_id_of(scraped_key, sys_data, fe)
|
||||
for fe in sys_data.get("files", [])
|
||||
}
|
||||
if not ids:
|
||||
return [sys_data.get("native_id") or scraped_key], True
|
||||
# A file the platform does not declare joins the system's primary
|
||||
# id, not whichever of its native ids sorts first: Recalbox files
|
||||
# pcengine, pcenginecd and supergrafx under one slug, and an
|
||||
# addition belongs to the one the system is named for.
|
||||
primary = sys_data.get("native_id")
|
||||
ordered = sorted(ids)
|
||||
if primary in ids:
|
||||
ordered.remove(primary)
|
||||
ordered.insert(0, primary)
|
||||
return ordered, primary in ids or len(ordered) == 1
|
||||
direct = self.native_by_norm.get(_norm_system_id(truth_sid))
|
||||
return ([direct] if direct else [truth_sid]), True
|
||||
|
||||
def _files_of(self, target_ids: list[str]) -> list[NativeFile]:
|
||||
return [
|
||||
candidate
|
||||
for native_id in target_ids
|
||||
for candidate in self.systems.get(native_id, NativeSystem(native_id)).files
|
||||
]
|
||||
|
||||
def apply(self, truth_sid: str, truth_sys: dict) -> None:
|
||||
truth_files = truth_sys.get("files", [])
|
||||
if not truth_files:
|
||||
return
|
||||
|
||||
target_ids, settled_id = self.target_native_ids(truth_sid)
|
||||
truth_files = [
|
||||
entry for entry in truth_files
|
||||
if (name := str(entry.get("name", "")))
|
||||
and not name.startswith("_") and not _is_placeholder(name)
|
||||
]
|
||||
candidates = [c for c in self._files_of(target_ids) if c.truth is None]
|
||||
pairs = pair_entries(truth_files, [c.platform or {} for c in candidates])
|
||||
# The cores that read what the platform files under each native id,
|
||||
# from the truth entries its declarations pair with.
|
||||
readers: dict[str, set[str]] = {}
|
||||
for t_index, index in pairs.items():
|
||||
readers.setdefault(candidates[index].native_system, set()).update(
|
||||
truth_files[t_index].get("_cores") or ()
|
||||
)
|
||||
for candidate in (c for c in self._files_of(target_ids) if c.platform is not None):
|
||||
own = str(candidate.name).casefold()
|
||||
candidate.namesakes.extend(
|
||||
entry for entry in truth_files if own in _names(entry)
|
||||
)
|
||||
|
||||
for t_index, truth_entry in enumerate(truth_files):
|
||||
paired = pairs.get(t_index)
|
||||
if paired is not None:
|
||||
_correct_matched(candidates[paired], truth_entry, self.report)
|
||||
continue
|
||||
self._add(truth_sid, truth_entry, target_ids, settled_id, readers)
|
||||
|
||||
def _add(
|
||||
self,
|
||||
truth_sid: str,
|
||||
truth_entry: dict,
|
||||
target_ids: list[str],
|
||||
settled_id: bool,
|
||||
readers: dict[str, set[str]],
|
||||
) -> None:
|
||||
"""File a truth entry the platform does not declare, when it can be."""
|
||||
name = str(truth_entry["name"])
|
||||
if is_label(truth_entry):
|
||||
self.report.labels += 1
|
||||
return
|
||||
# The emulator installs it: no user is asked to bring it.
|
||||
if truth_entry.get("bundled"):
|
||||
return
|
||||
|
||||
# A file another core's entry already claimed is still the
|
||||
# platform's file, not a new one: scph101.bin, declared by two
|
||||
# PSX cores, was written into RetroDECK's manifest a second time.
|
||||
declared = [
|
||||
candidate.platform
|
||||
for candidate in self._files_of(target_ids)
|
||||
if candidate.platform is not None
|
||||
]
|
||||
if platform_declares(truth_entry, declared):
|
||||
return
|
||||
|
||||
# The truth knows a file the platform does not declare. Across
|
||||
# several native ids and no primary, it joins the one whose files
|
||||
# its cores read: RetroDECK's arcade spans mame and fbneo, and
|
||||
# MAME device archives were filed as FBNeo BIOS because fbneo
|
||||
# sorts first. With no single answer it is not written.
|
||||
native_id = target_ids[0]
|
||||
if not settled_id:
|
||||
wanted = set(truth_entry.get("_cores") or ())
|
||||
shared = {nid: len(readers.get(nid, set()) & wanted) for nid in target_ids}
|
||||
best = max(shared.values())
|
||||
winners = [nid for nid, count in shared.items() if count == best]
|
||||
if not best or len(winners) > 1:
|
||||
self.report.unattributed.append(f"{truth_sid}/{name}")
|
||||
return
|
||||
native_id = winners[0]
|
||||
system = self.systems.get(native_id)
|
||||
if system is None:
|
||||
system = NativeSystem(native_id=native_id, from_platform=False)
|
||||
self.systems[native_id] = system
|
||||
self.report.systems_added += 1
|
||||
destination = str(
|
||||
truth_entry.get("path") or truth_entry.get("destination") or name
|
||||
)
|
||||
system.files.append(
|
||||
NativeFile(
|
||||
name=name,
|
||||
destination=destination,
|
||||
native_system=native_id,
|
||||
truth=truth_entry,
|
||||
foreign_system=native_id not in self.platform_ids,
|
||||
composite_md5=self.composite_zips and name.lower().endswith(".zip"),
|
||||
)
|
||||
)
|
||||
self.report.files_added += 1
|
||||
|
||||
|
||||
def build_native_model(
|
||||
truth: dict,
|
||||
scraped: dict | None,
|
||||
) -> tuple[dict[str, NativeSystem], Report]:
|
||||
"""Rebuild the platform's systems, corrected by the truth.
|
||||
|
||||
Returns the systems keyed by native id, in the platform's own order
|
||||
first and truth-only additions after, plus what changed.
|
||||
"""
|
||||
report = Report()
|
||||
scraped_systems = (scraped or {}).get("systems", {})
|
||||
systems = _platform_systems(scraped_systems, report)
|
||||
|
||||
truth_pass = _TruthPass(
|
||||
systems, report, scraped_systems,
|
||||
(scraped or {}).get("zip_digest") == "composite",
|
||||
)
|
||||
for truth_sid in sorted(truth.get("systems", {})):
|
||||
truth_pass.apply(truth_sid, truth["systems"][truth_sid])
|
||||
|
||||
# A reader takes the files in the order the list gives, so the one the
|
||||
# code looks for first is named first. Only what we add is ordered: what
|
||||
# the platform already wrote keeps the place the platform gave it.
|
||||
for system in systems.values():
|
||||
head = [fe for fe in system.files if fe.platform is not None]
|
||||
tail = [fe for fe in system.files if fe.platform is None]
|
||||
system.files = head + search_order(tail)
|
||||
|
||||
_attach_runners(systems, scraped)
|
||||
return systems, report
|
||||
|
||||
|
||||
def _attach_runners(systems: dict[str, NativeSystem], scraped: dict | None) -> None:
|
||||
"""Name the cores behind each addition the way the platform names them.
|
||||
|
||||
The platform lists its cores by its own names (Batocera's
|
||||
`mednafen_psx`, Recalbox's `mednafen_psx`), our truth by profile key
|
||||
(`beetle_psx`), and a profile's `cores:` holds the names it answers to.
|
||||
The build a platform runs an emulator as decides the runner, and the
|
||||
truth says which build needs the file (`_brought_by`): ROCKNIX's
|
||||
armsx2-sa installs pcsx2/resources itself, the libretro build does not.
|
||||
"""
|
||||
if not scraped:
|
||||
return
|
||||
from common import load_emulator_profiles, runs_standalone
|
||||
|
||||
declared = scraped.get("cores")
|
||||
libretro = {str(c) for c in declared} if isinstance(declared, list) else set()
|
||||
standalone = {str(c) for c in scraped.get("standalone_cores") or []}
|
||||
profiles = load_emulator_profiles(str(Path(__file__).resolve().parents[2] / "emulators"))
|
||||
for system in systems.values():
|
||||
for fe in system.files:
|
||||
if fe.platform is not None or not fe.truth:
|
||||
continue
|
||||
runners: list[tuple[bool, str]] = []
|
||||
brought = fe.truth.get("_brought_by")
|
||||
layers = (
|
||||
sorted((key, build == "standalone") for key, _, build in
|
||||
(b.partition(":") for b in brought))
|
||||
if brought is not None
|
||||
else [(key, runs_standalone(key, profiles.get(key, {}), standalone))
|
||||
for key in sorted(fe.truth.get("_cores") or ())]
|
||||
)
|
||||
for key, as_standalone in layers:
|
||||
profile = profiles.get(key, {})
|
||||
names = [key, *(str(c) for c in profile.get("cores") or [])]
|
||||
if as_standalone:
|
||||
name = next((n for n in names if n in standalone), None)
|
||||
runner = (True, name) if name else None
|
||||
else:
|
||||
name = next((n for n in names if n in libretro - standalone), None) \
|
||||
or next((n for n in names if n in libretro), None)
|
||||
runner = (False, name) if name else None
|
||||
if runner and runner not in runners:
|
||||
runners.append(runner)
|
||||
fe.runners = runners
|
||||
|
||||
|
||||
def search_order(files: list[NativeFile]) -> list[NativeFile]:
|
||||
"""Order files the way the code looks for them, best first.
|
||||
|
||||
`priority:` is that order where the source states it, lowest first.
|
||||
Where it does not, the order the entries were declared in is the order
|
||||
the code walks, so it is left alone.
|
||||
"""
|
||||
ranked = [(fe.priority, position, fe) for position, fe in enumerate(files)]
|
||||
return [
|
||||
fe
|
||||
for _, _, fe in sorted(
|
||||
ranked,
|
||||
key=lambda item: (
|
||||
(0, item[0]) if item[0] is not None else (1, item[1])
|
||||
),
|
||||
)
|
||||
]
|
||||
@@ -12,7 +12,7 @@ import ast
|
||||
import re
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://raw.githubusercontent.com/batocera-linux/batocera.linux/master"
|
||||
|
||||
@@ -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 .baseline import NativeFile, NativeSystem, Report
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://raw.githubusercontent.com/TASEmulators/BizHawk/master"
|
||||
|
||||
@@ -1,494 +0,0 @@
|
||||
"""Entries a platform declares that no core it runs is known to open.
|
||||
|
||||
The export never removes a platform's entry. An entry the truth did not
|
||||
pair may still be read: by a name or an alias, by its content, under a
|
||||
directory a core walks, inside a data directory. Each of those is looked
|
||||
for in the profiles of the cores the platform runs, and an entry none of
|
||||
them answers is listed with what was examined. Absence of a match is not
|
||||
proof that the code ignores the file, so the list is a report, and a core
|
||||
the platform names that no profile describes leaves the verdict open.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from common import _norm_system_id, resolve_platform_cores, unresolved_platform_cores
|
||||
from exporter.baseline import HASH_FIELDS, NativeSystem, _hash_values
|
||||
from launchers import _names as launcher_names
|
||||
|
||||
|
||||
def _tails(path: str) -> list[str]:
|
||||
"""Every trailing run of segments of a path, longest first."""
|
||||
parts = [p for p in path.casefold().strip("/").split("/") if p]
|
||||
return ["/".join(parts[i:]) for i in range(len(parts))]
|
||||
|
||||
|
||||
def _entry_hashes(entry: dict) -> set[str]:
|
||||
values = {v for f in HASH_FIELDS for v in _hash_values(entry, f)}
|
||||
for member in entry.get("contents") or []:
|
||||
if isinstance(member, dict):
|
||||
values |= {v for f in HASH_FIELDS for v in _hash_values(member, f)}
|
||||
return values
|
||||
|
||||
|
||||
def _declared_hashes(entry: dict) -> dict[str, set[str]]:
|
||||
"""Hash field -> the values a platform entry declares, alt_md5 as md5."""
|
||||
found = {f: set(_hash_values(entry, f)) for f in HASH_FIELDS}
|
||||
found["md5"] |= set(_hash_values(entry, "alt_md5"))
|
||||
return {f: values for f, values in found.items() if values}
|
||||
|
||||
|
||||
def _accepts(accepted: set[str], declared: dict[str, set[str]]) -> bool:
|
||||
"""True when the hashes a profile entry accepts, the members of its
|
||||
archive included, hold one the platform entry declares."""
|
||||
return any(values & accepted for values in declared.values())
|
||||
|
||||
|
||||
def _contradicts(profile_entry: dict, declared: dict[str, set[str]]) -> bool:
|
||||
"""True when both sides state the same kind of hash and no value agrees:
|
||||
the profile entry describes another dump under the same name."""
|
||||
for field_name, values in declared.items():
|
||||
own = set(_hash_values(profile_entry, field_name))
|
||||
if own and not set(values) & set(own):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReadEvidence:
|
||||
"""What the examined profiles open, indexed for one lookup per entry."""
|
||||
|
||||
names: set[str] = field(default_factory=set)
|
||||
tails: set[str] = field(default_factory=set)
|
||||
hashes: set[str] = field(default_factory=set)
|
||||
directories: set[str] = field(default_factory=set)
|
||||
trees: set[str] = field(default_factory=set)
|
||||
tree_members: set[str] = field(default_factory=set)
|
||||
launched: set[str] = field(default_factory=set)
|
||||
|
||||
def add_launchers(self, records: list[dict]) -> None:
|
||||
"""Every name the platform's own launch code opens, links or copies.
|
||||
|
||||
Batocera's DuckStation generator walks 22 names (bios_lists,
|
||||
duckstationGenerator.py:501-515): each is read on Batocera whatever
|
||||
the profiles call it.
|
||||
"""
|
||||
for record in records:
|
||||
if isinstance(record, dict):
|
||||
for name in launcher_names(record):
|
||||
self.launched.update(_tails(name))
|
||||
|
||||
def add_profile(self, profile: dict, data_registry: dict) -> None:
|
||||
for entry in profile.get("files") or []:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
locations = [
|
||||
str(entry[key]) for key in ("path", "standalone_path", "destination")
|
||||
if entry.get(key)
|
||||
]
|
||||
if entry.get("type") == "directory":
|
||||
self.directories |= {
|
||||
"/".join(p for p in loc.casefold().split("/") if p) + "/"
|
||||
for loc in [*locations, str(entry.get("name", ""))] if loc
|
||||
}
|
||||
continue
|
||||
self.names |= {
|
||||
str(n).casefold()
|
||||
for n in (entry.get("name"), *(entry.get("aliases") or []))
|
||||
if n
|
||||
}
|
||||
for location in locations:
|
||||
tails = _tails(location)
|
||||
self.tails.update(tails)
|
||||
if tails:
|
||||
self.names.add(tails[-1])
|
||||
self.hashes |= _entry_hashes(entry)
|
||||
for tree in profile.get("data_directories") or []:
|
||||
if not isinstance(tree, dict):
|
||||
continue
|
||||
destination = str(tree.get("destination") or "").casefold().strip("/")
|
||||
if destination:
|
||||
self.trees.add(destination + "/")
|
||||
continue
|
||||
# A tree laid at the root: only its own files say what it holds.
|
||||
cache = (data_registry.get(str(tree.get("ref", ""))) or {}).get("local_cache")
|
||||
if cache and Path(cache).is_dir():
|
||||
self.tree_members |= {
|
||||
p.relative_to(cache).as_posix().casefold()
|
||||
for p in Path(cache).rglob("*") if p.is_file()
|
||||
}
|
||||
|
||||
def proof(self, entry: dict, destination: str) -> str | None:
|
||||
"""How a profile reads the entry, or None when nothing answers."""
|
||||
names = {
|
||||
str(n).casefold()
|
||||
for n in (entry.get("name"), *(entry.get("aliases") or []))
|
||||
if n
|
||||
}
|
||||
tails = _tails(destination)
|
||||
if any(t in self.tails for t in tails[:-1]):
|
||||
return "path"
|
||||
if names & self.launched or (tails and tails[-1] in self.launched):
|
||||
return "launcher"
|
||||
if names & self.names or (tails and tails[-1] in self.names):
|
||||
return "name"
|
||||
hashes = {
|
||||
v for f in (*HASH_FIELDS, "alt_md5") for v in _hash_values(entry, f)
|
||||
}
|
||||
if hashes & self.hashes:
|
||||
return "hash"
|
||||
full = "/" + (tails[0] if tails else "")
|
||||
if any("/" + d in full for d in self.directories):
|
||||
return "directory"
|
||||
if any("/" + t in full for t in self.trees):
|
||||
return "data_directory"
|
||||
if full[1:] in self.tree_members:
|
||||
return "data_directory"
|
||||
return None
|
||||
|
||||
|
||||
# The order ReadEvidence.proof tries: a reader's proof is the first that holds.
|
||||
_PROOF_ORDER = ("path", "launcher", "name", "hash", "directory", "data_directory")
|
||||
|
||||
|
||||
class ProofIndex:
|
||||
"""ReadEvidence.proof for many readers at once, by lookup.
|
||||
|
||||
Asking every core in turn cost one proof per core and entry: 3.8 million
|
||||
calls to categorize 7,430 entries. Each key a reader can match is indexed
|
||||
once, and an entry's own keys find the readers it concerns. The proof of
|
||||
each reader is the one ReadEvidence.proof returns.
|
||||
"""
|
||||
|
||||
def __init__(self, readers: list[ReadEvidence]) -> None:
|
||||
self._index: dict[str, dict[str, set[int]]] = {
|
||||
kind: {} for kind in ("tail", "launched", "name", "hash", "dir", "tree", "member")
|
||||
}
|
||||
for position, evidence in enumerate(readers):
|
||||
for kind, keys in (
|
||||
("tail", evidence.tails), ("launched", evidence.launched),
|
||||
("name", evidence.names), ("hash", evidence.hashes),
|
||||
("dir", evidence.directories), ("tree", evidence.trees),
|
||||
("member", evidence.tree_members),
|
||||
):
|
||||
for key in keys:
|
||||
self._index[kind].setdefault(key, set()).add(position)
|
||||
|
||||
def _hits(self, kind: str, keys: Iterable[str]) -> set[int]:
|
||||
table = self._index[kind]
|
||||
found: set[int] = set()
|
||||
for key in keys:
|
||||
found |= table.get(key, set())
|
||||
return found
|
||||
|
||||
def proofs(self, entry: dict, destination: str) -> dict[int, str]:
|
||||
"""Reader position -> its proof, for the readers that have one."""
|
||||
names = {
|
||||
str(n).casefold()
|
||||
for n in (entry.get("name"), *(entry.get("aliases") or []))
|
||||
if n
|
||||
}
|
||||
tails = _tails(destination)
|
||||
last = {tails[-1]} if tails else set()
|
||||
hashes = {
|
||||
v for f in (*HASH_FIELDS, "alt_md5") for v in _hash_values(entry, f)
|
||||
}
|
||||
# "/" + d in "/" + path: d is a run of whole segments ending in "/",
|
||||
# so it is a run of the path's segments before the last one.
|
||||
parts = tails[0].split("/") if tails else []
|
||||
runs = {
|
||||
"/".join(parts[i:j]) + "/"
|
||||
for i in range(len(parts)) for j in range(i + 1, len(parts))
|
||||
}
|
||||
found = {
|
||||
"path": self._hits("tail", tails[:-1]),
|
||||
"launcher": self._hits("launched", names | last),
|
||||
"name": self._hits("name", names | last),
|
||||
"hash": self._hits("hash", hashes),
|
||||
"directory": self._hits("dir", runs),
|
||||
"data_directory": self._hits("tree", runs)
|
||||
| self._index["member"].get(tails[0] if tails else "", set()),
|
||||
}
|
||||
result: dict[int, str] = {}
|
||||
for kind in _PROOF_ORDER:
|
||||
for position in found[kind]:
|
||||
result.setdefault(position, kind)
|
||||
return result
|
||||
|
||||
|
||||
def _loads_romsets(profile: dict) -> bool:
|
||||
"""A core that opens ROM sets by name: MAME pulls a device's set from
|
||||
device_t::searchpath(), and no profile lists every device set."""
|
||||
return any(
|
||||
isinstance(f, dict) and f.get("category") == "bios_zip"
|
||||
for f in profile.get("files") or []
|
||||
)
|
||||
|
||||
|
||||
_ARCHIVES = (".zip", ".7z")
|
||||
|
||||
REASONS = {
|
||||
"candidate": "no profile of a core the platform runs names it",
|
||||
"unresolved": "a core the platform names has no profile yet",
|
||||
"romset": "a ROM set, and these cores open sets their profiles do not list",
|
||||
}
|
||||
|
||||
|
||||
def removal_candidates(
|
||||
systems: dict[str, NativeSystem],
|
||||
scraped: dict | None,
|
||||
profiles: dict[str, dict],
|
||||
data_registry: dict | None = None,
|
||||
) -> list[dict]:
|
||||
"""The platform's unpaired entries that no examined core is known to open.
|
||||
|
||||
Every core the platform runs is searched. `cores_examined` names those
|
||||
among them that emulate the entry's system, the ones a reader expects to
|
||||
find it in. `verdict` is `candidate` when nothing examined could open the
|
||||
entry, `undetermined` when something still could: a core the platform
|
||||
names that no profile describes, or a core of the system that opens ROM
|
||||
sets by name. A platform that resolves no core (BizHawk wires each
|
||||
firmware in its own code, MiSTer's BiosDB is its authority) gives nothing
|
||||
to examine and lists nothing. Nothing is removed from the platform's file.
|
||||
"""
|
||||
if not scraped:
|
||||
return []
|
||||
examined = resolve_platform_cores(scraped, profiles)
|
||||
if not examined:
|
||||
return []
|
||||
unresolved = sorted(unresolved_platform_cores(scraped, profiles))
|
||||
evidence = ReadEvidence()
|
||||
for key in sorted(examined):
|
||||
evidence.add_profile(profiles[key], data_registry or {})
|
||||
evidence.add_launchers(scraped.get("launchers") or [])
|
||||
|
||||
system_of = {
|
||||
id(file_entry): sys_key
|
||||
for sys_key, sys_data in (scraped.get("systems") or {}).items()
|
||||
for file_entry in sys_data.get("files", [])
|
||||
}
|
||||
by_system: dict[str, list[str]] = {}
|
||||
for key in sorted(examined):
|
||||
for sid in profiles[key].get("systems") or []:
|
||||
by_system.setdefault(_norm_system_id(str(sid)), []).append(key)
|
||||
|
||||
romset_cores = {key for key in examined if _loads_romsets(profiles[key])}
|
||||
|
||||
listed: list[dict] = []
|
||||
for system in systems.values():
|
||||
for entry in system.files:
|
||||
if entry.platform is None or entry.truth is not None or not entry.name:
|
||||
continue
|
||||
if evidence.proof(entry.platform, entry.destination) is not None:
|
||||
continue
|
||||
slug = system_of.get(id(entry.platform), entry.native_system)
|
||||
cores = by_system.get(_norm_system_id(slug), [])
|
||||
readers = (
|
||||
[c for c in cores if c in romset_cores]
|
||||
if entry.name.casefold().endswith(_ARCHIVES) else []
|
||||
)
|
||||
if unresolved:
|
||||
verdict, reason = "undetermined", REASONS["unresolved"]
|
||||
elif readers:
|
||||
verdict = "undetermined"
|
||||
reason = f"{REASONS['romset']}: {', '.join(readers)}"
|
||||
else:
|
||||
verdict, reason = "candidate", REASONS["candidate"]
|
||||
listed.append({
|
||||
"system": entry.native_system,
|
||||
"name": entry.name,
|
||||
"destination": entry.destination,
|
||||
"verdict": verdict,
|
||||
"reason": reason,
|
||||
"cores_examined": cores,
|
||||
"unresolved_cores": unresolved,
|
||||
})
|
||||
return listed
|
||||
|
||||
|
||||
# What a platform entry is, for the gates and the filters: firmware a core
|
||||
# needs, a game's own data, or a name no examined core opens.
|
||||
BIOS, GAME_DATA, UNREAD = "bios", "game_data", "unread"
|
||||
|
||||
|
||||
class EntryCategories:
|
||||
"""Categorize a platform's entries by what the cores it runs read.
|
||||
|
||||
An entry only game_data profile entries answer is the game's data, and
|
||||
one nothing examined answers is unread. Unread needs the same certainty
|
||||
as a removal candidate: every core the platform names is profiled, and
|
||||
no core of the platform opens ROM sets by name when the entry is an
|
||||
archive, and the platform declares the cores it runs. Anything else,
|
||||
and every entry of a platform with no core to examine (BizHawk, MiSTer),
|
||||
stays firmware.
|
||||
|
||||
A system that carries its own `cores:` list is settled by those cores:
|
||||
the cores examined are the ones it runs, and only its own unprofiled
|
||||
cores leave it open. Otherwise the platform's whole list applies.
|
||||
|
||||
`explain` returns the category with its evidence: the profile entries
|
||||
that read the file, or the cores of its system that were examined.
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict, profiles: dict[str, dict],
|
||||
data_registry: dict | None = None) -> None:
|
||||
examined = resolve_platform_cores(config, profiles)
|
||||
self._unresolved = sorted(unresolved_platform_cores(config, profiles))
|
||||
# Without a declared core list, the examined cores are those sharing
|
||||
# a system id: a guess about what runs, which cannot prove a negative.
|
||||
self._guessed = not config.get("cores")
|
||||
self._romsets = sorted(key for key in examined if _loads_romsets(profiles[key]))
|
||||
self._profiles = profiles
|
||||
# The hashes each profile entry accepts, read once: every platform
|
||||
# entry with a proof walks its reader's whole profile, and a MAME
|
||||
# profile's archive members were hashed again for each.
|
||||
self._accepted: dict[int, set[str]] = {}
|
||||
self._entry_index: dict[tuple[str, str], tuple[dict, dict]] = {}
|
||||
# One index per core and per kind, so a proof names its reader.
|
||||
self._readers: list[tuple[str, str, ReadEvidence]] = []
|
||||
for key in sorted(examined):
|
||||
profile = profiles[key]
|
||||
files = [f for f in profile.get("files") or [] if isinstance(f, dict)]
|
||||
for kind, keep in ((BIOS, lambda f: f.get("category") != GAME_DATA),
|
||||
(GAME_DATA, lambda f: f.get("category") == GAME_DATA)):
|
||||
evidence = ReadEvidence()
|
||||
evidence.add_profile(
|
||||
{"files": [f for f in files if keep(f)],
|
||||
"data_directories": profile.get("data_directories") if kind == BIOS else []},
|
||||
data_registry or {},
|
||||
)
|
||||
self._readers.append((kind, key, evidence))
|
||||
self._launchers = ReadEvidence()
|
||||
self._launchers.add_launchers(config.get("launchers") or [])
|
||||
self._proofs = ProofIndex([evidence for _kind, _key, evidence in self._readers]
|
||||
+ [self._launchers])
|
||||
self._by_system: dict[str, list[str]] = {}
|
||||
for key in sorted(examined):
|
||||
for sid in profiles[key].get("systems") or []:
|
||||
self._by_system.setdefault(_norm_system_id(str(sid)), []).append(key)
|
||||
# Where the platform says which cores run a system, those settle its
|
||||
# entries: an unprofiled core of another system has no say.
|
||||
self._system_runs: dict[str, tuple[list[str], list[str]]] = {}
|
||||
for sys_id, system in (config.get("systems") or {}).items():
|
||||
names = system.get("cores") if isinstance(system, dict) else None
|
||||
if names:
|
||||
own = {**config, "cores": list(names)}
|
||||
for key in ("standalone_cores", "dual_mode_cores"):
|
||||
if key in config:
|
||||
own[key] = [n for n in config.get(key) or [] if n in names]
|
||||
self._system_runs[sys_id] = (
|
||||
sorted(resolve_platform_cores(own, profiles)),
|
||||
sorted(unresolved_platform_cores(own, profiles)),
|
||||
)
|
||||
|
||||
def _accepted_by(self, profile_entry: dict) -> set[str]:
|
||||
accepted = self._accepted.get(id(profile_entry))
|
||||
if accepted is None:
|
||||
accepted = self._accepted[id(profile_entry)] = _entry_hashes(profile_entry)
|
||||
return accepted
|
||||
|
||||
def _index_of(self, key: str, kind: str) -> tuple[dict, dict]:
|
||||
"""A profile's entries of one kind by casefolded name and by accepted
|
||||
hash, each list in file order. Built once per profile and kind: a
|
||||
scan per platform entry cost 2 s of verify --all on MAME alone."""
|
||||
index = self._entry_index.get((key, kind))
|
||||
if index is None:
|
||||
by_name: dict[str, list[tuple[int, dict]]] = {}
|
||||
by_hash: dict[str, list[tuple[int, dict]]] = {}
|
||||
for position, f in enumerate(self._profiles[key].get("files") or []):
|
||||
if not isinstance(f, dict) or (f.get("category") == GAME_DATA) != (kind == GAME_DATA):
|
||||
continue
|
||||
for n in {str(n).casefold() for n in (f.get("name"), *(f.get("aliases") or [])) if n}:
|
||||
by_name.setdefault(n, []).append((position, f))
|
||||
for value in self._accepted_by(f):
|
||||
by_hash.setdefault(value, []).append((position, f))
|
||||
index = self._entry_index[(key, kind)] = (by_name, by_hash)
|
||||
return index
|
||||
|
||||
def _matching(self, key: str, kind: str, entry: dict) -> list[dict]:
|
||||
"""The profile entries of `key` that read the platform entry.
|
||||
|
||||
A platform entry that declares a hash is answered by the profile
|
||||
entries accepting that hash: one name covers several revisions
|
||||
(DuckStation lists scph1001.bin v2.2 at bios.cpp:36 and v2.0 at
|
||||
bios.cpp:42), and a match by name cited the line of another dump.
|
||||
A same-named entry is kept, marked `"by": "name"`, only when no
|
||||
entry accepts the hash and its own hashes do not contradict it.
|
||||
"""
|
||||
names = {
|
||||
str(n).casefold()
|
||||
for n in (entry.get("name"), *(entry.get("aliases") or []))
|
||||
if n
|
||||
}
|
||||
declared = _declared_hashes(entry)
|
||||
by_name_index, by_hash_index = self._index_of(key, kind)
|
||||
|
||||
def cited(f: dict) -> dict:
|
||||
return {k: f[k] for k in ("name", "source_ref") if f.get(k)}
|
||||
|
||||
found: dict[int, dict] = {
|
||||
position: f
|
||||
for values in declared.values()
|
||||
for value in values
|
||||
for position, f in by_hash_index.get(value, ())
|
||||
}
|
||||
if found:
|
||||
return [cited(found[p]) for p in sorted(found)]
|
||||
named = {position: f for n in names for position, f in by_name_index.get(n, ())}
|
||||
return [
|
||||
{**cited(named[p]), "by": "name"}
|
||||
for p in sorted(named)
|
||||
if not (declared and _contradicts(named[p], declared))
|
||||
]
|
||||
|
||||
def explain(self, entry: dict, destination: str, system: str) -> dict:
|
||||
"""The category of an entry and what establishes it."""
|
||||
readers: dict[str, list[dict]] = {BIOS: [], GAME_DATA: []}
|
||||
proofs = self._proofs.proofs(entry, destination)
|
||||
for position in sorted(p for p in proofs if p < len(self._readers)):
|
||||
kind, key, _evidence = self._readers[position]
|
||||
readers[kind].append({
|
||||
"emulator": key, "proof": proofs[position],
|
||||
"entries": self._matching(key, kind, entry),
|
||||
})
|
||||
if len(self._readers) in proofs:
|
||||
readers[BIOS].append({"emulator": "launcher", "proof": "launcher", "entries": []})
|
||||
if system in self._system_runs:
|
||||
system_cores, unresolved = self._system_runs[system]
|
||||
else:
|
||||
system_cores = self._by_system.get(_norm_system_id(system), [])
|
||||
unresolved = self._unresolved
|
||||
# A reader that runs the entry's system comes first and says so: a
|
||||
# core of another system may only share the file's name.
|
||||
for found in readers.values():
|
||||
for reader in found:
|
||||
reader["runs_system"] = reader["emulator"] in system_cores
|
||||
found.sort(key=lambda r: not r["runs_system"])
|
||||
if readers[BIOS]:
|
||||
return {"category": BIOS, "read_by": readers[BIOS]}
|
||||
if readers[GAME_DATA]:
|
||||
return {"category": GAME_DATA, "read_by": readers[GAME_DATA]}
|
||||
examined = {"cores_examined": system_cores}
|
||||
if self._guessed:
|
||||
return {"category": BIOS, "unsettled": "the platform declares no core list", **examined}
|
||||
if unresolved:
|
||||
return {"category": BIOS,
|
||||
"unsettled": "cores the platform names have no profile: "
|
||||
+ ", ".join(unresolved), **examined}
|
||||
if not system_cores:
|
||||
return {"category": BIOS,
|
||||
"unsettled": "no examined core emulates this system", **examined}
|
||||
if self._romsets and str(entry.get("name", "")).casefold().endswith(_ARCHIVES):
|
||||
return {"category": BIOS,
|
||||
"unsettled": "a ROM set, opened by name by " + ", ".join(self._romsets),
|
||||
**examined}
|
||||
return {"category": UNREAD, **examined}
|
||||
|
||||
def category(self, entry: dict, destination: str, system: str) -> str:
|
||||
return self.explain(entry, destination, system)["category"]
|
||||
@@ -22,9 +22,9 @@ from common import (
|
||||
resolve_platform_cores,
|
||||
standalone_set,
|
||||
)
|
||||
from exporter.baseline import HASH_FIELDS, _hash_values
|
||||
from resolve.reconcile import HASH_FIELDS, _hash_values
|
||||
from slots import _accepted_by_all, _lists_hashes, find_collisions
|
||||
from validation import opens_by_name, outside_gap_scope
|
||||
from resolve.validation import opens_by_name, outside_gap_scope
|
||||
|
||||
|
||||
def _names(entry: dict) -> set[str]:
|
||||
|
||||
@@ -18,7 +18,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from scraper.emudeck_scraper import FUNCTION_HASH_MAP, _RE_FUNC, _RE_LOCAL_HASHES
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report, _hash_values
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report, _hash_values
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://raw.githubusercontent.com/dragoonDorise/EmuDeck/main"
|
||||
|
||||
@@ -14,7 +14,7 @@ from collections import OrderedDict
|
||||
from typing import Union
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://raw.githubusercontent.com/ajgowans/BiosDB_MiSTer/db/bios_db.json.zip"
|
||||
|
||||
@@ -23,7 +23,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from common import load_emulator_profiles, parse_untrusted_xml
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report, by_destination, by_name
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report, by_destination, by_name
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://gitlab.com/recalbox/recalbox/-/raw/master/board/recalbox/fsoverlay"
|
||||
|
||||
@@ -11,7 +11,7 @@ import re
|
||||
from collections import OrderedDict
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://raw.githubusercontent.com/RetroBat-Official/emulatorlauncher/master"
|
||||
|
||||
@@ -13,7 +13,7 @@ import json
|
||||
from collections import OrderedDict
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report
|
||||
|
||||
COMPONENTS_REPO = "RetroDECK/components"
|
||||
COMPONENTS_BRANCH = "main"
|
||||
|
||||
@@ -24,7 +24,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from common import load_emulator_profiles
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report, search_order
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report, search_order
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://codeload.github.com/RetroPie/RetroPie-Setup/tar.gz/refs/heads/master"
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .baseline import NativeSystem, Report
|
||||
from resolve.reconcile import NativeSystem, Report
|
||||
from .batocera_exporter import Exporter as BatoceraExporter
|
||||
|
||||
SOURCE_URL = (
|
||||
|
||||
@@ -18,7 +18,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from scraper.romm_scraper import SLUG_MAP
|
||||
|
||||
from .base_exporter import BaseExporter
|
||||
from .baseline import NativeFile, NativeSystem, Report, _hash_values
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report, _hash_values
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://raw.githubusercontent.com/rommapp/romm/master/backend/models"
|
||||
|
||||
@@ -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 .baseline import NativeFile, NativeSystem, Report
|
||||
from resolve.reconcile import NativeFile, NativeSystem, Report
|
||||
|
||||
SOURCE_URL = (
|
||||
"https://raw.githubusercontent.com/libretro/libretro-database/master/dat/System.dat"
|
||||
|
||||
Reference in new issue
Block a user