mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-26 03:18: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
@@ -0,0 +1 @@
|
||||
"""From declarations to files: content checks, resolution, layouts, cores, truth."""
|
||||
@@ -0,0 +1,492 @@
|
||||
"""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
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
from common import _norm_system_id, resolve_platform_cores, unresolved_platform_cores
|
||||
from resolve.reconcile import HASH_FIELDS, NativeSystem, _hash_values
|
||||
from resolve.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"]
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Leaving a game's own data out of a pack, a manifest or a report.
|
||||
|
||||
A platform list can name the files a game reads beside the firmware its
|
||||
emulator needs, and a core profile marks the data files of the games it runs
|
||||
`category: game_data`. `--no-game-data` keeps the firmware: the platform's
|
||||
entries categorized as game data and the profiles' game data entries are left
|
||||
out, and each one is named with the reason.
|
||||
|
||||
Every caller cuts from the full platform config and the full profiles. The
|
||||
category of a platform entry is read from the profiles' game data entries, so
|
||||
cutting twice would find no evidence the second time.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from common import resolve_platform_cores
|
||||
from resolve.categories import GAME_DATA, EntryCategories
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LeftOut:
|
||||
"""One game data file left out, and who reads it as game data."""
|
||||
|
||||
layer: str # "platform" (the platform's list) or "core" (a core profile)
|
||||
system: str
|
||||
name: str
|
||||
readers: tuple[str, ...]
|
||||
|
||||
def describe(self) -> str:
|
||||
where = f"{self.system}/{self.name}" if self.system else self.name
|
||||
if not self.readers:
|
||||
return where
|
||||
return f"{where} (game data of {', '.join(self.readers)})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class GameDataCut:
|
||||
"""The config and profiles without game data, and what was left out."""
|
||||
|
||||
config: dict
|
||||
profiles: dict[str, dict]
|
||||
left_out: list[LeftOut]
|
||||
|
||||
def report_lines(self) -> list[str]:
|
||||
"""What the cut left out, named, one line per layer.
|
||||
|
||||
The platform layer names each entry and the cores that read it as
|
||||
game data. The core layer names each core with the files its profile
|
||||
declares `category: game_data`, held by the collection or not.
|
||||
"""
|
||||
lines = []
|
||||
platform = [item.describe() for item in self.left_out if item.layer == "platform"]
|
||||
if platform:
|
||||
lines.append(
|
||||
f"Left out as game data, {len(platform)} entries of the platform's "
|
||||
f"list: {', '.join(platform)}"
|
||||
)
|
||||
by_core: dict[str, list[str]] = {}
|
||||
for item in self.left_out:
|
||||
if item.layer == "core":
|
||||
names = by_core.setdefault(item.readers[0], [])
|
||||
if item.name not in names:
|
||||
names.append(item.name)
|
||||
if by_core:
|
||||
count = sum(len(names) for names in by_core.values())
|
||||
named = "; ".join(
|
||||
f"{core}: {', '.join(names)}" for core, names in sorted(by_core.items())
|
||||
)
|
||||
lines.append(
|
||||
f"Left out as game data, {count} files the cores declare "
|
||||
f"category: game_data ({named})"
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
def is_game_data(entry: dict) -> bool:
|
||||
return entry.get("category") == GAME_DATA
|
||||
|
||||
|
||||
def _entry_names(entry: dict) -> set[str]:
|
||||
names = {str(entry.get("name") or "")}
|
||||
names.update(str(a) for a in entry.get("aliases") or [])
|
||||
path = str(entry.get("path") or "")
|
||||
if path:
|
||||
names.add(path.rstrip("/").rsplit("/", 1)[-1])
|
||||
return {n.casefold() for n in names if n}
|
||||
|
||||
|
||||
def platform_game_data(
|
||||
config: dict, profiles: dict[str, dict], data_registry: dict | None
|
||||
) -> set[int]:
|
||||
"""The `id()` of every platform entry categorized as game data."""
|
||||
categories = EntryCategories(config, profiles, data_registry)
|
||||
return {
|
||||
id(fe)
|
||||
for sys_id, system in (config.get("systems") or {}).items()
|
||||
for fe in system.get("files") or []
|
||||
if isinstance(fe, dict)
|
||||
and categories.category(
|
||||
fe, str(fe.get("destination", fe.get("name", ""))), sys_id
|
||||
) == GAME_DATA
|
||||
}
|
||||
|
||||
|
||||
def without_game_data(
|
||||
config: dict,
|
||||
profiles: dict[str, dict],
|
||||
data_registry: dict | None = None,
|
||||
target_cores: set[str] | None = None,
|
||||
) -> GameDataCut:
|
||||
"""The platform config and the profiles with every game data entry removed.
|
||||
|
||||
The profiles lose their `category: game_data` files, so no core extra
|
||||
of that category reaches the pack, the manifest or the report. The
|
||||
platform keeps every entry that is not categorized game data.
|
||||
"""
|
||||
dropped = platform_game_data(config, profiles, data_registry)
|
||||
examined = sorted(resolve_platform_cores(config, profiles, target_cores=target_cores))
|
||||
readers_by_name: dict[str, set[str]] = {}
|
||||
for key in examined:
|
||||
for fe in profiles[key].get("files") or []:
|
||||
if isinstance(fe, dict) and is_game_data(fe):
|
||||
for name in _entry_names(fe):
|
||||
readers_by_name.setdefault(name, set()).add(key)
|
||||
|
||||
left_out: list[LeftOut] = []
|
||||
systems: dict[str, dict] = {}
|
||||
for sys_id, system in (config.get("systems") or {}).items():
|
||||
files = system.get("files") or []
|
||||
kept = [fe for fe in files if id(fe) not in dropped]
|
||||
for fe in files:
|
||||
if id(fe) in dropped:
|
||||
name = str(fe.get("name") or "")
|
||||
left_out.append(LeftOut(
|
||||
"platform", sys_id, name,
|
||||
tuple(sorted(readers_by_name.get(name.casefold(), ()))),
|
||||
))
|
||||
systems[sys_id] = {**system, "files": kept} if len(kept) != len(files) else system
|
||||
|
||||
left_out.extend(
|
||||
LeftOut("core", "", str(fe.get("name") or ""), (key,))
|
||||
for key in examined
|
||||
for fe in profiles[key].get("files") or []
|
||||
if isinstance(fe, dict) and is_game_data(fe)
|
||||
)
|
||||
|
||||
stripped = {
|
||||
key: (
|
||||
{**profile, "files": [
|
||||
fe for fe in profile.get("files") or []
|
||||
if not (isinstance(fe, dict) and is_game_data(fe))
|
||||
]}
|
||||
if any(isinstance(fe, dict) and is_game_data(fe)
|
||||
for fe in profile.get("files") or [])
|
||||
else profile
|
||||
)
|
||||
for key, profile in profiles.items()
|
||||
}
|
||||
return GameDataCut({**config, "systems": systems}, stripped, left_out)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The one place that decides what a platform's native check actually does.
|
||||
|
||||
verify.py reports coverage and generate_pack.py decides what goes in the ZIP.
|
||||
They have to reach the same verdict on the same file or the pack and the
|
||||
report describe different collections. The rule they share is small:
|
||||
|
||||
does the frontend read the file's bytes, or only look for the name?
|
||||
|
||||
Everything downstream follows from that answer. RetroArch, Lakka and RetroPie
|
||||
call path_is_valid() and never open the file, so a declared hash contradicted
|
||||
by the local dump is a documentation error, the file still loads, and the
|
||||
builder ships it while the report flags the divergence. Batocera, Recalbox,
|
||||
RetroBat, RetroDECK, RomM, ROCKNIX, MiSTer and BizHawk compare a digest, so
|
||||
the same file would be rejected at runtime and shipping it would be shipping
|
||||
a known failure.
|
||||
|
||||
Keeping the predicate here rather than in each caller is what makes
|
||||
"verify.py and generate_pack.py must agree" a property of the code instead of
|
||||
something a reviewer has to notice.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DEFAULT_MODE = "existence"
|
||||
|
||||
#: Every verification mode a platform YAML may declare. Mirrors the enum in
|
||||
#: schemas/platform.schema.json, and tests/test_audit_regressions.py pins them
|
||||
#: together so a new mode cannot be added to one without the other.
|
||||
MODES = ("existence", "md5", "sha1")
|
||||
|
||||
#: The digest each content-checking mode compares. Modes absent from this map
|
||||
#: do not read the file at all.
|
||||
MODE_DIGEST = {"md5": "md5", "sha1": "sha1"}
|
||||
|
||||
|
||||
#: A frontend that accepts a file on its size and any one declared hash.
|
||||
#: RomM's Firmware.verify_file_hashes: size first, then md5, sha1 or crc.
|
||||
SIZE_AND_ANY_HASH = "size_and_any_hash"
|
||||
HASH_RULES = (SIZE_AND_ANY_HASH,)
|
||||
|
||||
|
||||
#: How a platform checks a file, in a reader's words. Every table and badge
|
||||
#: that says it reads this, so a page cannot call RomM's rule an MD5 check.
|
||||
_CHECK_LABELS = {"existence": "name only", "md5": "MD5", "sha1": "SHA-1"}
|
||||
|
||||
|
||||
def check_label(mode: str | None, hash_rule: str | None = None) -> str:
|
||||
"""The words for what a platform's own check compares."""
|
||||
if hash_rule == SIZE_AND_ANY_HASH:
|
||||
return "size, then any hash"
|
||||
return _CHECK_LABELS[normalize(mode)]
|
||||
|
||||
|
||||
def normalize(mode: str | None) -> str:
|
||||
"""Return a declared mode, falling back to the schema default."""
|
||||
return mode if mode in MODES else DEFAULT_MODE
|
||||
|
||||
|
||||
def reads_file_contents(mode: str | None) -> bool:
|
||||
"""Whether the frontend opens the file rather than just finding it."""
|
||||
return normalize(mode) in MODE_DIGEST
|
||||
|
||||
|
||||
def digest_algorithm(mode: str | None) -> str | None:
|
||||
"""The hash this mode compares, or None when it compares nothing."""
|
||||
return MODE_DIGEST.get(normalize(mode))
|
||||
|
||||
|
||||
def hash_mismatch_excludes_file(mode: str | None) -> bool:
|
||||
"""Whether a local dump contradicting a declared hash must be omitted.
|
||||
|
||||
True for the digest modes: the frontend would reject the file, so packing
|
||||
it ships a known failure. False for existence: the frontend never looks,
|
||||
and dropping the file over an upstream metadata error would remove
|
||||
something that works.
|
||||
"""
|
||||
return reads_file_contents(mode)
|
||||
@@ -0,0 +1,824 @@
|
||||
"""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
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
from common import _norm_system_id
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
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(REPO_ROOT / "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])
|
||||
),
|
||||
)
|
||||
]
|
||||
@@ -0,0 +1,231 @@
|
||||
"""One file per slot: keep the BIOS a core would actually load.
|
||||
|
||||
A slot is a (system, region) pair holding several interchangeable BIOS. Region
|
||||
filtering narrows a pack to one territory, but a system can still ship three US
|
||||
PlayStation BIOS that differ only by revision, which is what leaves the choice
|
||||
open in the frontend.
|
||||
|
||||
The winner is only ever taken from the preference order the core's own code
|
||||
applies, recorded as `priority:` on the file entry, lowest first. DuckStation
|
||||
keeps the image whose priority is lower (bios.cpp, FindBIOSImageInDirectory)
|
||||
and its table de-prioritizes by raising the number: the buggy launch console
|
||||
sits at 50 and PS2 images at 100, while scph5501 sits at 5. A core that walks
|
||||
an ordered search list, as PicoDrive does with biosfiles_us/eu/jp, maps onto
|
||||
the same field as 1, 2, 3.
|
||||
|
||||
Every candidate of a group must carry one. A set where some members are
|
||||
unranked cannot be ordered, and dropping the unranked ones would discard
|
||||
exactly the file the core may load. Where the order is not declared the group
|
||||
is reported undecidable and every candidate is kept: picking one would be the
|
||||
arbitrary selection this exists to remove.
|
||||
|
||||
The scale is only meaningful inside one emulator's candidate set. When two
|
||||
profiles rank the same file differently (pcsx1 walks scph1001 first while
|
||||
DuckStation prefers scph5501), the pack serves both cores, so neither order
|
||||
may win: the file is marked conflicting and its group stays undecidable.
|
||||
The same holds when one profile ranks a file and another declares it with no
|
||||
rank: the second core reads it by its own rule, which no rank expresses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from model.alternatives import set_keys
|
||||
|
||||
BIOS_CATEGORY = "bios"
|
||||
|
||||
|
||||
def platform_slot_index(
|
||||
config: dict, profiles: dict, target_cores: set[str] | None = None
|
||||
) -> dict[str, dict]:
|
||||
"""The slot index of the emulators a platform runs, nothing else.
|
||||
|
||||
Built over every profile, DuckStation, ePSXe and Rustation ranked the
|
||||
PlayStation BIOS of RomM, whose cores rank none of them, and
|
||||
`--one-per-slot` dropped four images RomM declares.
|
||||
"""
|
||||
return {
|
||||
key: merge_claims(by_emu)
|
||||
for key, by_emu in platform_slot_claims(config, profiles, target_cores).items()
|
||||
}
|
||||
|
||||
|
||||
def platform_slot_claims(
|
||||
config: dict, profiles: dict, target_cores: set[str] | None = None
|
||||
) -> dict[str, dict[str, dict]]:
|
||||
"""What each emulator a platform runs declares at each key, unmerged."""
|
||||
from common import resolve_platform_cores
|
||||
|
||||
cores = resolve_platform_cores(config, profiles, target_cores=target_cores)
|
||||
return slot_claims({n: profiles[n] for n in cores if n in profiles})
|
||||
|
||||
|
||||
def slot_claims(profiles: dict) -> dict[str, dict[str, dict]]:
|
||||
"""Per key (path, standalone path, name), what each emulator declares there.
|
||||
|
||||
Each claim holds the ranks the emulator gives the key in declaration
|
||||
order, None for an entry without one, the regions, and the set keys.
|
||||
The install manifest carries these unmerged, so the installer merges
|
||||
them over the cores a board runs as build_slot_index merges them here.
|
||||
"""
|
||||
claims: dict[str, dict[str, dict]] = {}
|
||||
for emu_name, profile in sorted(profiles.items()):
|
||||
if profile.get("type") in ("launcher", "alias"):
|
||||
continue
|
||||
for f in profile.get("files") or []:
|
||||
if not isinstance(f, dict):
|
||||
continue
|
||||
if f.get("category", BIOS_CATEGORY) != BIOS_CATEGORY:
|
||||
continue
|
||||
name = f.get("name", "")
|
||||
path = f.get("path") or ""
|
||||
# Keyed by the standalone layout too, as build_region_index is.
|
||||
for key in {path, f.get("standalone_path") or "", name} - {""}:
|
||||
claim = claims.setdefault(key, {}).setdefault(
|
||||
emu_name, {"ranks": [], "regions": set(), "sets": set()}
|
||||
)
|
||||
claim["regions"] |= {str(r) for r in (f.get("region") or [])}
|
||||
claim["sets"] |= set(set_keys(emu_name, f))
|
||||
claim["ranks"].append(f.get("priority"))
|
||||
return claims
|
||||
|
||||
|
||||
def merge_claims(by_emulator: dict[str, dict]) -> dict:
|
||||
"""One key's slot metadata, merged over the emulators claiming it.
|
||||
|
||||
Two ranks that differ make the key conflicting. So does an emulator
|
||||
that declares the key without a rank beside one that ranks it: a core
|
||||
that declares the file without a rank loads it by a rule of its own.
|
||||
Genesis Plus GX opens bios_CD_U.bin by name for a US disc, and
|
||||
PicoDrive's rank 4 for it would let its rank-3 file replace it.
|
||||
"""
|
||||
ranks = {r for claim in by_emulator.values() for r in claim["ranks"] if r is not None}
|
||||
ranked_by = {e for e, claim in by_emulator.items()
|
||||
if any(r is not None for r in claim["ranks"])}
|
||||
unranked_by = {e for e, claim in by_emulator.items() if None in claim["ranks"]}
|
||||
return {
|
||||
"rank": min(ranks) if ranks else None,
|
||||
"conflict": len(ranks) > 1 or bool(ranked_by and unranked_by - ranked_by),
|
||||
"regions": {r for claim in by_emulator.values() for r in claim["regions"]},
|
||||
"emulators": sorted(by_emulator),
|
||||
"sets": {k for claim in by_emulator.values() for k in claim["sets"]},
|
||||
}
|
||||
|
||||
|
||||
def build_slot_index(profiles: dict) -> dict[str, dict]:
|
||||
"""Map a file key to its slot metadata, keyed by path then name."""
|
||||
return {key: merge_claims(by_emu) for key, by_emu in slot_claims(profiles).items()}
|
||||
|
||||
|
||||
def slot_lookup_keys(destination: str, name: str) -> list[str]:
|
||||
"""The keys lookup_slot tries, in its order."""
|
||||
keys: list[str] = []
|
||||
if destination:
|
||||
parts = destination.split("/")
|
||||
keys += ["/".join(parts[i:]) for i in range(len(parts))]
|
||||
return [*keys, name]
|
||||
|
||||
|
||||
def lookup_slot(index: dict[str, dict], destination: str, name: str) -> dict | None:
|
||||
"""Look a candidate up, trying the destination then its suffixes then name."""
|
||||
if destination:
|
||||
entry = index.get(destination)
|
||||
if entry:
|
||||
return entry
|
||||
parts = destination.split("/")
|
||||
for i in range(1, len(parts)):
|
||||
entry = index.get("/".join(parts[i:]))
|
||||
if entry:
|
||||
return entry
|
||||
return index.get(name)
|
||||
|
||||
|
||||
def resolve_slot_drops(
|
||||
groups: dict[str, list[tuple[str, str]]],
|
||||
index: dict[str, dict],
|
||||
held: set[str] | None = None,
|
||||
) -> tuple[set[str], list[str]]:
|
||||
"""Destinations to skip, and the groups no declared order can decide.
|
||||
|
||||
Returns (drops, undecidable). A group is decided only when every candidate
|
||||
declares a priority and exactly one holds the lowest. Anything else keeps
|
||||
every candidate. ``held`` names the destinations the collection holds: a
|
||||
candidate it lacks ships nothing, so it neither wins nor displaces one.
|
||||
"""
|
||||
keep: set[str] = set()
|
||||
drop: set[str] = set()
|
||||
undecidable: list[str] = []
|
||||
|
||||
# A slot is a system AND a declared region: the Japanese and American
|
||||
# PlayStation BIOS are not alternatives to each other, and comparing their
|
||||
# ranks across regions would pick one territory's file for another's.
|
||||
bucketed: dict[tuple[str, tuple[str, ...]], list[tuple[str, int | None, frozenset]]] = {}
|
||||
for group_id, members in groups.items():
|
||||
for destination, name in members:
|
||||
if held is not None and destination not in held:
|
||||
continue
|
||||
entry = lookup_slot(index, destination, name)
|
||||
if entry is None:
|
||||
keep.add(destination)
|
||||
continue
|
||||
tier = tuple(sorted(entry["regions"]))
|
||||
rank = None if entry.get("conflict") else entry["rank"]
|
||||
bucketed.setdefault((group_id, tier), []).append(
|
||||
(destination, rank, frozenset(entry.get("sets") or ()))
|
||||
)
|
||||
# A rank orders the members of one set: px68k-sdl ranks its IPL and its
|
||||
# font ROM lists each from 1, and the two never compete. Candidates are
|
||||
# compared when they share a set, and those in no set among themselves.
|
||||
tiers: dict[tuple[str, tuple[str, ...], int], list[tuple[str, int | None]]] = {}
|
||||
for (group_id, tier), found in bucketed.items():
|
||||
for part, component in enumerate(_by_shared_set(found)):
|
||||
tiers[(group_id, tier, part)] = component
|
||||
|
||||
for (group_id, tier, _part), candidates in tiers.items():
|
||||
if len(candidates) < 2:
|
||||
keep.update(dest for dest, _p in candidates)
|
||||
continue
|
||||
|
||||
# Every candidate must carry a rank: a set where some members are
|
||||
# unranked cannot be ordered, and dropping the unranked ones would
|
||||
# discard exactly the file the core may load.
|
||||
if any(p is None for _d, p in candidates):
|
||||
undecidable.append(f"{group_id}|{','.join(tier)}" if tier else group_id)
|
||||
keep.update(dest for dest, _p in candidates)
|
||||
continue
|
||||
|
||||
best = min(p for _d, p in candidates if p is not None)
|
||||
winners = [dest for dest, p in candidates if p == best]
|
||||
if len(winners) != 1:
|
||||
undecidable.append(f"{group_id}|{','.join(tier)}" if tier else group_id)
|
||||
keep.update(dest for dest, _p in candidates)
|
||||
continue
|
||||
|
||||
keep.add(winners[0])
|
||||
drop.update(dest for dest, _p in candidates if dest != winners[0])
|
||||
|
||||
return drop - keep, sorted(undecidable)
|
||||
|
||||
|
||||
def _by_shared_set(
|
||||
found: list[tuple[str, int | None, frozenset]],
|
||||
) -> list[list[tuple[str, int | None]]]:
|
||||
"""The candidates of one tier split where no set links them."""
|
||||
parent = list(range(len(found)))
|
||||
|
||||
def root(i: int) -> int:
|
||||
while parent[i] != i:
|
||||
parent[i] = parent[parent[i]]
|
||||
i = parent[i]
|
||||
return i
|
||||
|
||||
first_of: dict[object, int] = {}
|
||||
for i, (_dest, _rank, sets) in enumerate(found):
|
||||
for key in sets or {None}:
|
||||
if key in first_of:
|
||||
parent[root(i)] = root(first_of[key])
|
||||
else:
|
||||
first_of[key] = i
|
||||
parts: dict[int, list[tuple[str, int | None]]] = {}
|
||||
for i, (dest, rank, _sets) in enumerate(found):
|
||||
parts.setdefault(root(i), []).append((dest, rank))
|
||||
return list(parts.values())
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user