mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-03 06:48:52 -06:00
refactor: split truth generation from its diff
This commit is contained in:
1 parent
2d79a2e1b5
commit
753e873472
11 files changed
+652
-620
No files matched your search
@@ -6,7 +6,7 @@ import os
|
||||
|
||||
from model.platforms import load_platform_config, native_layer
|
||||
from model.safeparse import require_yaml, yaml_load
|
||||
from resolve.truth import diff_platform_truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
|
||||
require_yaml()
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
"""The divergences between a platform's own declarations and its generated truth."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from model.systems import norm_system_id
|
||||
|
||||
|
||||
# Platform truth diffing
|
||||
|
||||
|
||||
def _path_tail(value: object) -> str:
|
||||
return str(value or "").replace("\\", "/").casefold()
|
||||
|
||||
|
||||
def _hash_mismatch(t_entry: dict, s_entry: dict) -> dict | None:
|
||||
"""The first hash field the export would correct, by the export's rule.
|
||||
|
||||
contradicted_hashes is the one decision: a hash the code does not check
|
||||
contradicts nothing (checked_hashes), and a platform md5 that is a
|
||||
composite of a zip's members is no container md5 (comparable).
|
||||
"""
|
||||
from resolve.reconcile import contradicted_hashes
|
||||
|
||||
fields = contradicted_hashes(t_entry, s_entry)
|
||||
if not fields:
|
||||
return None
|
||||
h = fields[0]
|
||||
return {
|
||||
"name": s_entry["name"],
|
||||
"hash_type": h,
|
||||
f"truth_{h}": t_entry.get(h, ""),
|
||||
f"scraped_{h}": s_entry.get(h, ""),
|
||||
"truth_cores": list(t_entry.get("_cores", [])),
|
||||
}
|
||||
|
||||
|
||||
def _diff_system(truth_sys: dict, scraped_sys: dict) -> dict:
|
||||
"""Compare files between truth and scraped for a single system.
|
||||
|
||||
Entries are paired by pair_entries, the rule export_native applies. Two
|
||||
rules had diverged, and diff_truth flagged a hash the export did not
|
||||
correct while the export corrected hashes the diff never named. An entry
|
||||
never answers for two.
|
||||
"""
|
||||
from resolve.reconcile import is_placeholder, is_label, pair_entries, platform_declares
|
||||
|
||||
truth_files = [
|
||||
fe for fe in truth_sys.get("files", [])
|
||||
if fe.get("name") and not fe["name"].startswith("_")
|
||||
and not is_placeholder(fe["name"])
|
||||
]
|
||||
scraped_files = scraped_sys.get("files", [])
|
||||
|
||||
missing: list[dict] = []
|
||||
hash_mismatch: list[dict] = []
|
||||
required_mismatch: list[dict] = []
|
||||
extra_phantom: list[dict] = []
|
||||
extra_unprofiled: list[dict] = []
|
||||
|
||||
pairs = pair_entries(truth_files, scraped_files)
|
||||
claimed = set(pairs.values())
|
||||
for t_index, t_entry in enumerate(truth_files):
|
||||
s_position = pairs.get(t_index)
|
||||
if s_position is None:
|
||||
if (not is_label(t_entry) and not t_entry.get("bundled")
|
||||
and not platform_declares(t_entry, scraped_files)):
|
||||
missing.append(
|
||||
{
|
||||
"name": t_entry["name"],
|
||||
"destination": t_entry.get("path") or t_entry["name"],
|
||||
"cores": list(t_entry.get("_cores", [])),
|
||||
"source_refs": list(t_entry.get("_source_refs", [])),
|
||||
}
|
||||
)
|
||||
continue
|
||||
s_entry = scraped_files[s_position]
|
||||
mismatch = _hash_mismatch(t_entry, s_entry)
|
||||
if mismatch:
|
||||
mismatch["destination"] = s_entry.get("destination") or s_entry["name"]
|
||||
hash_mismatch.append(mismatch)
|
||||
t_req = t_entry.get("required")
|
||||
s_req = s_entry.get("required")
|
||||
if t_entry.get("one_of_required") and not t_req:
|
||||
# Needed as one of a set: no value of its own to compare.
|
||||
t_req = None
|
||||
if t_req is not None and s_req is not None and t_req != s_req:
|
||||
required_mismatch.append(
|
||||
{
|
||||
"name": s_entry["name"],
|
||||
"destination": s_entry.get("destination") or s_entry["name"],
|
||||
"truth_required": t_req,
|
||||
"scraped_required": s_req,
|
||||
}
|
||||
)
|
||||
|
||||
# A scraped entry no truth entry describes, by path, name or hash.
|
||||
unmatched_scraped = {
|
||||
position: s_entry
|
||||
for position, s_entry in enumerate(scraped_files)
|
||||
if position not in claimed
|
||||
and not any(platform_declares(t, [s_entry]) for t in truth_files)
|
||||
}
|
||||
|
||||
# Scraped files not in truth -> extra
|
||||
coverage = truth_sys.get("_coverage", {})
|
||||
has_unprofiled = bool(coverage.get("cores_unprofiled"))
|
||||
# An archive declared once per ROM it holds (zipped_file) is still one
|
||||
# file.
|
||||
seen_extra: set[tuple[str, str]] = set()
|
||||
for s_entry in unmatched_scraped.values():
|
||||
key = (s_entry["name"].lower(), _path_tail(s_entry.get("destination")))
|
||||
if key in seen_extra:
|
||||
continue
|
||||
seen_extra.add(key)
|
||||
# The destination tells apart two declarations of one name: the
|
||||
# report listed six `hiscore.dat` to add beside one to drop.
|
||||
entry = {
|
||||
"name": s_entry["name"],
|
||||
"destination": s_entry.get("destination") or s_entry["name"],
|
||||
}
|
||||
if has_unprofiled:
|
||||
extra_unprofiled.append(entry)
|
||||
else:
|
||||
extra_phantom.append(entry)
|
||||
|
||||
result: dict = {}
|
||||
if missing:
|
||||
result["missing"] = missing
|
||||
if hash_mismatch:
|
||||
result["hash_mismatch"] = hash_mismatch
|
||||
if required_mismatch:
|
||||
result["required_mismatch"] = required_mismatch
|
||||
if extra_phantom:
|
||||
result["extra_phantom"] = extra_phantom
|
||||
if extra_unprofiled:
|
||||
result["extra_unprofiled"] = extra_unprofiled
|
||||
return result
|
||||
|
||||
|
||||
def _has_divergences(sys_div: dict) -> bool:
|
||||
"""Check if a system divergence dict contains any actual divergences."""
|
||||
return bool(sys_div)
|
||||
|
||||
|
||||
def _update_summary(summary: dict, sys_div: dict) -> None:
|
||||
"""Update summary counters from a system divergence dict."""
|
||||
summary["total_missing"] += len(sys_div.get("missing", []))
|
||||
summary["total_extra_phantom"] += len(sys_div.get("extra_phantom", []))
|
||||
summary["total_extra_unprofiled"] += len(sys_div.get("extra_unprofiled", []))
|
||||
summary["total_hash_mismatch"] += len(sys_div.get("hash_mismatch", []))
|
||||
summary["total_required_mismatch"] += len(sys_div.get("required_mismatch", []))
|
||||
|
||||
|
||||
def diff_platform_truth(truth: dict, scraped: dict) -> dict:
|
||||
"""Compare truth YAML against scraped YAML, returning divergences.
|
||||
|
||||
System IDs are matched using normalized forms (via norm_system_id) to
|
||||
handle naming differences between emulator profiles and scraped platforms
|
||||
(e.g. 'sega-game-gear' vs 'sega-gamegear').
|
||||
"""
|
||||
truth_systems = truth.get("systems", {})
|
||||
scraped_systems = scraped.get("systems", {})
|
||||
|
||||
summary = {
|
||||
"systems_compared": 0,
|
||||
"systems_fully_covered": 0,
|
||||
"systems_partially_covered": 0,
|
||||
"systems_uncovered": 0,
|
||||
"total_missing": 0,
|
||||
"total_extra_phantom": 0,
|
||||
"total_extra_unprofiled": 0,
|
||||
"total_hash_mismatch": 0,
|
||||
"total_required_mismatch": 0,
|
||||
}
|
||||
|
||||
divergences: dict[str, dict] = {}
|
||||
uncovered_systems: list[str] = []
|
||||
|
||||
# Build normalized-ID lookup for truth systems
|
||||
norm_to_truth: dict[str, str] = {}
|
||||
for sid in truth_systems:
|
||||
norm_to_truth[norm_system_id(sid)] = sid
|
||||
|
||||
# Match scraped systems to truth via normalized IDs
|
||||
matched_truth: set[str] = set()
|
||||
|
||||
for s_sid in sorted(scraped_systems):
|
||||
norm = norm_system_id(s_sid)
|
||||
t_sid = norm_to_truth.get(norm)
|
||||
|
||||
if t_sid is None:
|
||||
# Also try exact match (in case normalization is lossy)
|
||||
if s_sid in truth_systems:
|
||||
t_sid = s_sid
|
||||
else:
|
||||
uncovered_systems.append(s_sid)
|
||||
summary["systems_uncovered"] += 1
|
||||
continue
|
||||
|
||||
matched_truth.add(t_sid)
|
||||
summary["systems_compared"] += 1
|
||||
sys_div = _diff_system(truth_systems[t_sid], scraped_systems[s_sid])
|
||||
|
||||
if _has_divergences(sys_div):
|
||||
divergences[s_sid] = sys_div
|
||||
_update_summary(summary, sys_div)
|
||||
summary["systems_partially_covered"] += 1
|
||||
else:
|
||||
summary["systems_fully_covered"] += 1
|
||||
|
||||
# Truth systems not matched by any scraped system: all files missing
|
||||
for t_sid in sorted(truth_systems):
|
||||
if t_sid in matched_truth:
|
||||
continue
|
||||
summary["systems_compared"] += 1
|
||||
sys_div = _diff_system(truth_systems[t_sid], {"files": []})
|
||||
if _has_divergences(sys_div):
|
||||
divergences[t_sid] = sys_div
|
||||
_update_summary(summary, sys_div)
|
||||
summary["systems_partially_covered"] += 1
|
||||
else:
|
||||
summary["systems_fully_covered"] += 1
|
||||
|
||||
result: dict = {"summary": summary}
|
||||
if divergences:
|
||||
result["divergences"] = divergences
|
||||
if uncovered_systems:
|
||||
result["uncovered_systems"] = uncovered_systems
|
||||
return result
|
||||
+12
-604
@@ -9,23 +9,27 @@ from __future__ import annotations
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
from model.declarations import OUTER_ROOTS
|
||||
from model.systems import norm_system_id
|
||||
from resolve.launches import PlatformLaunches
|
||||
from resolve.standalone import platform_layouts, platform_launches
|
||||
from resolve.cores import resolve_platform_cores
|
||||
from resolve.reconcile import contradicts, shares_hash
|
||||
from model.alternatives import groups_of
|
||||
from model.database import record_for_hash
|
||||
from core.hashing import HASH_FIELDS, compute_hashes, declared_hashes, lists_hashes, parse_hash_list
|
||||
from core.hashing import HASH_FIELDS, compute_hashes, declared_hashes, parse_hash_list
|
||||
from resolve.entryscope import (
|
||||
filter_files_by_mode,
|
||||
installed_with_emulator,
|
||||
opens_by_name,
|
||||
read_from_system_dir,
|
||||
unread_on,
|
||||
)
|
||||
from resolve.truthsystems import (
|
||||
_SystemMap,
|
||||
_brought,
|
||||
_cover,
|
||||
_enrich_hashes,
|
||||
_has_exploitable_data,
|
||||
_platform_entries,
|
||||
_require_by_slot,
|
||||
_serialize_systems,
|
||||
_sizes_clash,
|
||||
)
|
||||
|
||||
|
||||
@@ -46,47 +50,6 @@ def _serialize_source_ref(sr: object) -> str:
|
||||
return str(sr)
|
||||
|
||||
|
||||
def _enrich_hashes(entry: dict, db: dict) -> None:
|
||||
"""Fill the hashes a profile omits from the record its own hash names.
|
||||
|
||||
The record is found by sha1, sha256, then md5, then crc32 with the size
|
||||
when the profile gives one. Never by name: a file in bios/ under the same
|
||||
name may not be the bytes the source code expects. An entry listing
|
||||
several accepted values for a hash is left as is.
|
||||
"""
|
||||
if any(isinstance(entry.get(h), list) for h in HASH_FIELDS):
|
||||
return
|
||||
|
||||
files_db = db.get("files", {})
|
||||
record = None
|
||||
# rust_dos names its SC-55 ROMs by sha256 alone, ares 5200.rom too.
|
||||
for kind in ("sha1", "sha256", "md5"):
|
||||
sha1 = record_for_hash(db, kind, entry.get(kind))
|
||||
if sha1:
|
||||
record = files_db[sha1]
|
||||
break
|
||||
|
||||
# CRC32 (32-bit, collisions theoretically possible): the size must
|
||||
# match when the profile has one.
|
||||
if record is None:
|
||||
sha1 = record_for_hash(db, "crc32", entry.get("crc32"))
|
||||
candidate = files_db[sha1] if sha1 else None
|
||||
if candidate is not None:
|
||||
profile_size = entry.get("size")
|
||||
if not profile_size or candidate.get("size") == profile_size:
|
||||
record = candidate
|
||||
|
||||
if record is None:
|
||||
return
|
||||
|
||||
# Copy sibling hashes and size from the anchored record.
|
||||
for field in ("sha1", "md5", "sha256", "crc32"):
|
||||
if not entry.get(field) and record.get(field):
|
||||
entry[field] = record[field]
|
||||
if not entry.get("size") and record.get("size"):
|
||||
entry["size"] = record["size"]
|
||||
|
||||
|
||||
_FILLED_FIELDS = (
|
||||
"size",
|
||||
"min_size",
|
||||
@@ -186,44 +149,6 @@ def _same_file(files: list[dict], file_entry: dict, emu_name: str) -> dict | Non
|
||||
)
|
||||
|
||||
|
||||
def _require_by_slot(files: list[dict]) -> None:
|
||||
"""A core that requires a name an entry answers for requires the entry.
|
||||
|
||||
Merged by name, one core's alternatives land in several entries. Ymir
|
||||
reads sega_101.bin, mpr-17933.bin or saturn_bios.bin, so the sega_101.bin
|
||||
entry carries those aliases. kronos, yabause and yabasanshiro open
|
||||
saturn_bios.bin first and sega_101.bin as a fallback: they sat in that
|
||||
entry's _cores, out of its _required_by, while their saturn_bios.bin entry
|
||||
had them requiring it, and a platform line paired through the alias read
|
||||
them as optional. A core already among the entry's readers that requires
|
||||
one of its aliases, as another entry of the system, is one of its
|
||||
requirers. No reader is added.
|
||||
"""
|
||||
required_by_name: dict[str, set[str]] = {}
|
||||
for entry in files:
|
||||
required_by_name.setdefault(entry["name"].lower(), set()).update(
|
||||
entry.get("_required_by", ())
|
||||
)
|
||||
for entry in files:
|
||||
# Only the aliases: entries sharing the entry's own name are other
|
||||
# files that name already kept apart (pak0.pak under each game).
|
||||
names = {str(alias).lower() for alias in entry.get("aliases") or ()}
|
||||
names.discard(entry["name"].lower())
|
||||
requirers = set().union(*(required_by_name.get(n, set()) for n in names))
|
||||
added = (requirers & entry.get("_cores", set())) - entry.get("_required_by", set())
|
||||
if added:
|
||||
entry["_required_by"] = entry.get("_required_by", set()) | added
|
||||
entry["required"] = True
|
||||
|
||||
|
||||
def _brought(file_entry: dict, emu_name: str) -> set[str]:
|
||||
"""The core and build that need the file brought, empty when the
|
||||
emulator installs it. An entry read without layer (a test, a caller of
|
||||
its own) is brought by its core's libretro build."""
|
||||
brought = file_entry.get("_brought", f"{emu_name}:libretro")
|
||||
return {brought} if brought else set()
|
||||
|
||||
|
||||
def _shares_hash(a: dict, b: dict) -> bool:
|
||||
return shares_hash(declared_hashes(a), declared_hashes(b))
|
||||
|
||||
@@ -400,145 +325,6 @@ def _new_truth_entry(file_entry: dict, emu_name: str, db: dict | None) -> dict:
|
||||
return entry
|
||||
|
||||
|
||||
def _has_exploitable_data(entry: dict) -> bool:
|
||||
"""Check if an entry has any data beyond its name that can drive verification.
|
||||
|
||||
Applied AFTER merging all cores so entries benefit from enrichment by
|
||||
sibling cores before being judged empty.
|
||||
"""
|
||||
return bool(
|
||||
lists_hashes(entry)
|
||||
or entry.get("path")
|
||||
or entry.get("size")
|
||||
or entry.get("min_size")
|
||||
or entry.get("max_size")
|
||||
or entry.get("validation")
|
||||
or entry.get("contents")
|
||||
)
|
||||
|
||||
|
||||
def _system_dir_files(profile: dict, standalone: bool) -> list[dict]:
|
||||
"""Entries of the build the platform runs, read from the system directory.
|
||||
|
||||
An entry the platform's launchers leave outside the BIOS tree
|
||||
(``unplaced``) is not, nor one placed below its roms or an emulator
|
||||
folder (``root``): the platform has no file of its own there.
|
||||
"""
|
||||
return [
|
||||
f for f in filter_files_by_mode(profile.get("files", []), standalone=standalone)
|
||||
if read_from_system_dir(f) and not f.get("unplaced") and f.get("root") not in OUTER_ROOTS
|
||||
]
|
||||
|
||||
|
||||
def _archives_not_members(files: list[dict]) -> list[dict]:
|
||||
"""A profile's entries with the members of each archive folded into it.
|
||||
|
||||
fbneo declares bubsys.zip as the ROMs it holds, each carrying
|
||||
`archive: bubsys.zip`. The platform reads the archive, never a member:
|
||||
as loose files the members were added to RetroArch's System.dat, and
|
||||
the 480-byte boot.bin was filed under the Dreamcast by its bare name.
|
||||
The archive stands in their place with the members as its contents,
|
||||
the shape a profile that declares the archive itself already has.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
archives: dict[tuple[str, str], dict] = {}
|
||||
for fe in files:
|
||||
archive = fe.get("archive")
|
||||
if not archive:
|
||||
out.append(fe)
|
||||
continue
|
||||
key = (archive, fe.get("system", ""))
|
||||
entry = archives.get(key)
|
||||
if entry is None:
|
||||
entry = {"name": archive, "category": "bios_zip", "contents": [],
|
||||
"_brought": None}
|
||||
if fe.get("system"):
|
||||
entry["system"] = fe["system"]
|
||||
if fe.get("source_ref") is not None:
|
||||
entry["source_ref"] = fe["source_ref"]
|
||||
archives[key] = entry
|
||||
out.append(entry)
|
||||
if fe.get("required"):
|
||||
entry["required"] = True
|
||||
# The archive is brought when one member is: gngeo_data.zip, every
|
||||
# member of it installed by make install, is not a file to copy.
|
||||
if "_brought" not in fe:
|
||||
entry.pop("_brought", None)
|
||||
elif "_brought" in entry and entry["_brought"] is None:
|
||||
entry["_brought"] = fe["_brought"]
|
||||
entry["contents"].append({
|
||||
field: fe[field]
|
||||
for field in ("name", "size", "crc32", "sha1", "md5")
|
||||
if fe.get(field) is not None
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _sizes(entry: dict) -> tuple[set[int], tuple[int, float] | None]:
|
||||
"""The sizes an entry admits: exact values, then its window or None.
|
||||
|
||||
An entry that declares no size at all admits every size, an unbounded
|
||||
window. Exact sizes alone leave no window (size_refusal).
|
||||
"""
|
||||
raw = entry.get("size")
|
||||
values = raw if isinstance(raw, list) else [raw]
|
||||
exact = {int(v) for v in values if isinstance(v, int) and not isinstance(v, bool)}
|
||||
low, high = entry.get("min_size"), entry.get("max_size")
|
||||
low = low if isinstance(low, int) else None
|
||||
high = high if isinstance(high, int) else None
|
||||
if low is None and high is None:
|
||||
return exact, None if exact else (0, float("inf"))
|
||||
return exact, (low or 0, float("inf") if high is None else high)
|
||||
|
||||
|
||||
def _sizes_clash(a: dict, b: dict) -> bool:
|
||||
"""No size both entries admit, lists and windows included."""
|
||||
exact_a, window_a = _sizes(a)
|
||||
exact_b, window_b = _sizes(b)
|
||||
|
||||
def inside(value: int, window: tuple[int, float] | None) -> bool:
|
||||
return window is not None and window[0] <= value <= window[1]
|
||||
|
||||
if exact_a & exact_b:
|
||||
return False
|
||||
if any(inside(v, window_b) for v in exact_a) or any(inside(v, window_a) for v in exact_b):
|
||||
return False
|
||||
if window_a and window_b:
|
||||
return max(window_a[0], window_b[0]) > min(window_a[1], window_b[1])
|
||||
return True
|
||||
|
||||
|
||||
def _identity(entry: dict, db: dict | None) -> dict:
|
||||
"""The entry with the hashes and size the database knows for its hash."""
|
||||
probe = {k: entry[k] for k in ("sha1", "md5", "crc32", "size") if entry.get(k)}
|
||||
if db and probe and not any(isinstance(v, list) for v in probe.values()):
|
||||
_enrich_hashes(probe, db)
|
||||
return {**entry, **{k: v for k, v in probe.items() if not entry.get(k)}}
|
||||
|
||||
|
||||
def _identity_values(entry: dict) -> set[str]:
|
||||
"""Every hash an identity declares."""
|
||||
return {v for values in declared_hashes(entry).values() for v in values}
|
||||
|
||||
|
||||
def _declaration_verdict(entry: dict, declaration: dict, db: dict | None) -> str:
|
||||
"""same, other or undecided: can a platform declaration be this file?
|
||||
|
||||
A shared hash proves it. Sizes no value of which agrees refute it, as
|
||||
name_match_size_ok refutes a candidate. Two hashes at one size are two
|
||||
revisions of one slot, as slots.py reads them, so they refute nothing.
|
||||
The size the database holds for a declared hash counts as declared:
|
||||
Batocera's BK BASIC10.ROM names only an md5, of a 24576-byte file, and
|
||||
clk's 16 KB Oric basic10.rom was filed under the BK beside it.
|
||||
"""
|
||||
ours, theirs = _identity(entry, db), _identity(declaration, db)
|
||||
if _identity_values(ours) & _identity_values(theirs):
|
||||
return "same"
|
||||
if _sizes_clash(ours, theirs):
|
||||
return "other"
|
||||
return "undecided"
|
||||
|
||||
|
||||
def _fold_data_directory_readers(
|
||||
systems: dict,
|
||||
profiles: dict,
|
||||
@@ -620,160 +406,6 @@ def _fold_data_directory_readers(
|
||||
_fold_into(entry, dict(declaration), emu_name)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SystemMap:
|
||||
"""How a profile's systems and entries map onto a platform's systems."""
|
||||
|
||||
platform_sys_ids: set[str]
|
||||
# Every platform declaration of a name, in the platform's order. The
|
||||
# last one used to win, whatever the content.
|
||||
declared_by_name: dict[str, list[tuple[str, dict]]]
|
||||
# Normalized ID -> platform system ID. Walked in the platform's order,
|
||||
# not the set's: two IDs normalizing alike went to whichever the hash
|
||||
# seed put last.
|
||||
norm_to_platform: dict[str, str]
|
||||
db: dict | None
|
||||
|
||||
@classmethod
|
||||
def of(cls, config: dict, db: dict | None) -> _SystemMap:
|
||||
declared_by_name: dict[str, list[tuple[str, dict]]] = {}
|
||||
for psid, sys_data in config.get("systems", {}).items():
|
||||
for fe in sys_data.get("files", []):
|
||||
fname = fe.get("name", "").lower()
|
||||
if fname:
|
||||
declared_by_name.setdefault(fname, []).append((psid, fe))
|
||||
norm_to_platform: dict[str, str] = {}
|
||||
for psid in config.get("systems", {}):
|
||||
norm_to_platform.setdefault(norm_system_id(psid), psid)
|
||||
return cls(
|
||||
set(config.get("systems", {}).keys()), declared_by_name, norm_to_platform, db,
|
||||
)
|
||||
|
||||
def map_sys_id(self, profile_sid: str) -> str:
|
||||
"""Map a profile system ID to the platform's system ID."""
|
||||
if profile_sid in self.platform_sys_ids:
|
||||
return profile_sid
|
||||
return self.norm_to_platform.get(norm_system_id(profile_sid), profile_sid)
|
||||
|
||||
def attribute(self, fe: dict, own: str | None, on_platform: set[str]) -> list[str]:
|
||||
"""The platform systems an entry belongs to, [] when nothing decides.
|
||||
|
||||
A declaration of the same name settles the system only when it can
|
||||
be the same file: a shared hash, or no contradicting size. fmsx's
|
||||
16 KB DISK.ROM is not quasi88's 2 KB disk.rom, and dosbox's SC-55
|
||||
ROM1.BIN is not galaksija's. The same content declared under two
|
||||
systems is filed under both.
|
||||
"""
|
||||
verdicts = [
|
||||
(psid, _declaration_verdict(fe, decl, self.db))
|
||||
for psid, decl in self.declared_by_name.get(fe.get("name", "").lower(), [])
|
||||
]
|
||||
same = sorted({psid for psid, v in verdicts if v == "same"})
|
||||
undecided = sorted({psid for psid, v in verdicts if v == "undecided"})
|
||||
if own is not None:
|
||||
mapped = self.map_sys_id(own)
|
||||
if any(psid == mapped and v != "other" for psid, v in verdicts):
|
||||
return [mapped]
|
||||
if same:
|
||||
return same
|
||||
if len(undecided) == 1:
|
||||
return undecided
|
||||
return [mapped]
|
||||
if same:
|
||||
return same
|
||||
if len(undecided) == 1:
|
||||
return undecided
|
||||
if undecided:
|
||||
ours = [psid for psid in undecided if psid in on_platform]
|
||||
return ours if len(ours) == 1 else []
|
||||
return [next(iter(on_platform))] if len(on_platform) == 1 else []
|
||||
|
||||
def targets(self, fe: dict, profile: dict, on_platform: set[str]) -> list[str]:
|
||||
"""The platform systems an entry is filed under."""
|
||||
profile_sid = fe.get("system", "")
|
||||
sys_ids = profile.get("systems", [])
|
||||
if profile_sid:
|
||||
own: str | None = profile_sid
|
||||
elif len(sys_ids) == 1:
|
||||
own = sys_ids[0]
|
||||
elif not sys_ids:
|
||||
# A profile that names no system: a platform declaration of
|
||||
# the same file files it, and the placeholder takes only a
|
||||
# name the platform does not declare. mess2015's hiscore.dat
|
||||
# beside the arcade one put an "unknown" section in System.dat.
|
||||
own = None
|
||||
else:
|
||||
# A multi-system profile's entry without a system is filed by
|
||||
# the platform's own declaration of the same file, or the one
|
||||
# profile system the platform has. Otherwise it is not filed:
|
||||
# the first system was a guess, and CLK's Apple, Mac, ZX and
|
||||
# Amiga ROMs went to RomM as Amstrad CPC firmware.
|
||||
own = None
|
||||
sys_targets = self.attribute(fe, own, on_platform)
|
||||
if not sys_ids and not profile_sid and not sys_targets \
|
||||
and fe.get("name", "").lower() not in self.declared_by_name:
|
||||
sys_targets = [self.map_sys_id("unknown")]
|
||||
return sys_targets
|
||||
|
||||
|
||||
def _cover(
|
||||
system_cores: dict[str, dict[str, set[str]]], sys_id: str, kind: str, emu_name: str,
|
||||
) -> None:
|
||||
sys_cov = system_cores.setdefault(
|
||||
sys_id,
|
||||
{
|
||||
"profiled": set(),
|
||||
"unprofiled": set(),
|
||||
},
|
||||
)
|
||||
sys_cov[kind].add(emu_name)
|
||||
|
||||
|
||||
def _platform_entries(
|
||||
emu_name: str, profile: dict, launches: PlatformLaunches, platform_name: str,
|
||||
) -> list[dict]:
|
||||
# The pack's rule (validation.deliverable), per build: a file the
|
||||
# emulator installs is kept and marked, one the launcher never opens
|
||||
# is left out.
|
||||
return _archives_not_members([
|
||||
{
|
||||
**fe,
|
||||
"_opens_by_name": opens_by_name(fe, profile, standalone),
|
||||
"_brought": None if installed_with_emulator(fe, platform_name)
|
||||
else f"{emu_name}:{'standalone' if standalone else 'libretro'}",
|
||||
}
|
||||
for view, standalone in platform_layouts(emu_name, profile, launches)
|
||||
for fe in _system_dir_files(view, standalone)
|
||||
if not unread_on(fe, platform_name)
|
||||
])
|
||||
|
||||
|
||||
def _serialize_systems(
|
||||
systems: dict[str, dict], system_cores: dict[str, dict[str, set[str]]],
|
||||
) -> None:
|
||||
# Convert sets to sorted lists for serialization
|
||||
for sys_id, sys_data in systems.items():
|
||||
for fe in sys_data.get("files", []):
|
||||
fe.pop("_hash_by", None)
|
||||
fe.pop("_region_void", None)
|
||||
fe["_cores"] = sorted(fe.get("_cores", set()))
|
||||
fe["_required_by"] = sorted(fe.get("_required_by", set()))
|
||||
one_of = fe.pop("_one_of", None)
|
||||
if one_of:
|
||||
fe["one_of"] = sorted(one_of)
|
||||
fe["_named_by"] = sorted(fe.get("_named_by", set()))
|
||||
fe["_brought_by"] = sorted(fe.get("_brought_by", set()))
|
||||
if not fe["_brought_by"]:
|
||||
fe["bundled"] = True
|
||||
fe["_source_refs"] = sorted(fe.get("_source_refs", set()))
|
||||
# Add per-system coverage
|
||||
cov = system_cores.get(sys_id, {})
|
||||
sys_data["_coverage"] = {
|
||||
"cores_profiled": sorted(cov.get("profiled", set())),
|
||||
"cores_unprofiled": sorted(cov.get("unprofiled", set())),
|
||||
}
|
||||
|
||||
|
||||
def generate_platform_truth(
|
||||
platform_name: str,
|
||||
config: dict,
|
||||
@@ -891,227 +523,3 @@ def generate_platform_truth(
|
||||
"unattributed": dict(sorted(unattributed.items())),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# Platform truth diffing
|
||||
|
||||
|
||||
def _path_tail(value: object) -> str:
|
||||
return str(value or "").replace("\\", "/").casefold()
|
||||
|
||||
|
||||
def _hash_mismatch(t_entry: dict, s_entry: dict) -> dict | None:
|
||||
"""The first hash field the export would correct, by the export's rule.
|
||||
|
||||
contradicted_hashes is the one decision: a hash the code does not check
|
||||
contradicts nothing (checked_hashes), and a platform md5 that is a
|
||||
composite of a zip's members is no container md5 (comparable).
|
||||
"""
|
||||
from resolve.reconcile import contradicted_hashes
|
||||
|
||||
fields = contradicted_hashes(t_entry, s_entry)
|
||||
if not fields:
|
||||
return None
|
||||
h = fields[0]
|
||||
return {
|
||||
"name": s_entry["name"],
|
||||
"hash_type": h,
|
||||
f"truth_{h}": t_entry.get(h, ""),
|
||||
f"scraped_{h}": s_entry.get(h, ""),
|
||||
"truth_cores": list(t_entry.get("_cores", [])),
|
||||
}
|
||||
|
||||
|
||||
def _diff_system(truth_sys: dict, scraped_sys: dict) -> dict:
|
||||
"""Compare files between truth and scraped for a single system.
|
||||
|
||||
Entries are paired by pair_entries, the rule export_native applies. Two
|
||||
rules had diverged, and diff_truth flagged a hash the export did not
|
||||
correct while the export corrected hashes the diff never named. An entry
|
||||
never answers for two.
|
||||
"""
|
||||
from resolve.reconcile import is_placeholder, is_label, pair_entries, platform_declares
|
||||
|
||||
truth_files = [
|
||||
fe for fe in truth_sys.get("files", [])
|
||||
if fe.get("name") and not fe["name"].startswith("_")
|
||||
and not is_placeholder(fe["name"])
|
||||
]
|
||||
scraped_files = scraped_sys.get("files", [])
|
||||
|
||||
missing: list[dict] = []
|
||||
hash_mismatch: list[dict] = []
|
||||
required_mismatch: list[dict] = []
|
||||
extra_phantom: list[dict] = []
|
||||
extra_unprofiled: list[dict] = []
|
||||
|
||||
pairs = pair_entries(truth_files, scraped_files)
|
||||
claimed = set(pairs.values())
|
||||
for t_index, t_entry in enumerate(truth_files):
|
||||
s_position = pairs.get(t_index)
|
||||
if s_position is None:
|
||||
if (not is_label(t_entry) and not t_entry.get("bundled")
|
||||
and not platform_declares(t_entry, scraped_files)):
|
||||
missing.append(
|
||||
{
|
||||
"name": t_entry["name"],
|
||||
"destination": t_entry.get("path") or t_entry["name"],
|
||||
"cores": list(t_entry.get("_cores", [])),
|
||||
"source_refs": list(t_entry.get("_source_refs", [])),
|
||||
}
|
||||
)
|
||||
continue
|
||||
s_entry = scraped_files[s_position]
|
||||
mismatch = _hash_mismatch(t_entry, s_entry)
|
||||
if mismatch:
|
||||
mismatch["destination"] = s_entry.get("destination") or s_entry["name"]
|
||||
hash_mismatch.append(mismatch)
|
||||
t_req = t_entry.get("required")
|
||||
s_req = s_entry.get("required")
|
||||
if t_entry.get("one_of_required") and not t_req:
|
||||
# Needed as one of a set: no value of its own to compare.
|
||||
t_req = None
|
||||
if t_req is not None and s_req is not None and t_req != s_req:
|
||||
required_mismatch.append(
|
||||
{
|
||||
"name": s_entry["name"],
|
||||
"destination": s_entry.get("destination") or s_entry["name"],
|
||||
"truth_required": t_req,
|
||||
"scraped_required": s_req,
|
||||
}
|
||||
)
|
||||
|
||||
# A scraped entry no truth entry describes, by path, name or hash.
|
||||
unmatched_scraped = {
|
||||
position: s_entry
|
||||
for position, s_entry in enumerate(scraped_files)
|
||||
if position not in claimed
|
||||
and not any(platform_declares(t, [s_entry]) for t in truth_files)
|
||||
}
|
||||
|
||||
# Scraped files not in truth -> extra
|
||||
coverage = truth_sys.get("_coverage", {})
|
||||
has_unprofiled = bool(coverage.get("cores_unprofiled"))
|
||||
# An archive declared once per ROM it holds (zipped_file) is still one
|
||||
# file.
|
||||
seen_extra: set[tuple[str, str]] = set()
|
||||
for s_entry in unmatched_scraped.values():
|
||||
key = (s_entry["name"].lower(), _path_tail(s_entry.get("destination")))
|
||||
if key in seen_extra:
|
||||
continue
|
||||
seen_extra.add(key)
|
||||
# The destination tells apart two declarations of one name: the
|
||||
# report listed six `hiscore.dat` to add beside one to drop.
|
||||
entry = {
|
||||
"name": s_entry["name"],
|
||||
"destination": s_entry.get("destination") or s_entry["name"],
|
||||
}
|
||||
if has_unprofiled:
|
||||
extra_unprofiled.append(entry)
|
||||
else:
|
||||
extra_phantom.append(entry)
|
||||
|
||||
result: dict = {}
|
||||
if missing:
|
||||
result["missing"] = missing
|
||||
if hash_mismatch:
|
||||
result["hash_mismatch"] = hash_mismatch
|
||||
if required_mismatch:
|
||||
result["required_mismatch"] = required_mismatch
|
||||
if extra_phantom:
|
||||
result["extra_phantom"] = extra_phantom
|
||||
if extra_unprofiled:
|
||||
result["extra_unprofiled"] = extra_unprofiled
|
||||
return result
|
||||
|
||||
|
||||
def _has_divergences(sys_div: dict) -> bool:
|
||||
"""Check if a system divergence dict contains any actual divergences."""
|
||||
return bool(sys_div)
|
||||
|
||||
|
||||
def _update_summary(summary: dict, sys_div: dict) -> None:
|
||||
"""Update summary counters from a system divergence dict."""
|
||||
summary["total_missing"] += len(sys_div.get("missing", []))
|
||||
summary["total_extra_phantom"] += len(sys_div.get("extra_phantom", []))
|
||||
summary["total_extra_unprofiled"] += len(sys_div.get("extra_unprofiled", []))
|
||||
summary["total_hash_mismatch"] += len(sys_div.get("hash_mismatch", []))
|
||||
summary["total_required_mismatch"] += len(sys_div.get("required_mismatch", []))
|
||||
|
||||
|
||||
def diff_platform_truth(truth: dict, scraped: dict) -> dict:
|
||||
"""Compare truth YAML against scraped YAML, returning divergences.
|
||||
|
||||
System IDs are matched using normalized forms (via norm_system_id) to
|
||||
handle naming differences between emulator profiles and scraped platforms
|
||||
(e.g. 'sega-game-gear' vs 'sega-gamegear').
|
||||
"""
|
||||
truth_systems = truth.get("systems", {})
|
||||
scraped_systems = scraped.get("systems", {})
|
||||
|
||||
summary = {
|
||||
"systems_compared": 0,
|
||||
"systems_fully_covered": 0,
|
||||
"systems_partially_covered": 0,
|
||||
"systems_uncovered": 0,
|
||||
"total_missing": 0,
|
||||
"total_extra_phantom": 0,
|
||||
"total_extra_unprofiled": 0,
|
||||
"total_hash_mismatch": 0,
|
||||
"total_required_mismatch": 0,
|
||||
}
|
||||
|
||||
divergences: dict[str, dict] = {}
|
||||
uncovered_systems: list[str] = []
|
||||
|
||||
# Build normalized-ID lookup for truth systems
|
||||
norm_to_truth: dict[str, str] = {}
|
||||
for sid in truth_systems:
|
||||
norm_to_truth[norm_system_id(sid)] = sid
|
||||
|
||||
# Match scraped systems to truth via normalized IDs
|
||||
matched_truth: set[str] = set()
|
||||
|
||||
for s_sid in sorted(scraped_systems):
|
||||
norm = norm_system_id(s_sid)
|
||||
t_sid = norm_to_truth.get(norm)
|
||||
|
||||
if t_sid is None:
|
||||
# Also try exact match (in case normalization is lossy)
|
||||
if s_sid in truth_systems:
|
||||
t_sid = s_sid
|
||||
else:
|
||||
uncovered_systems.append(s_sid)
|
||||
summary["systems_uncovered"] += 1
|
||||
continue
|
||||
|
||||
matched_truth.add(t_sid)
|
||||
summary["systems_compared"] += 1
|
||||
sys_div = _diff_system(truth_systems[t_sid], scraped_systems[s_sid])
|
||||
|
||||
if _has_divergences(sys_div):
|
||||
divergences[s_sid] = sys_div
|
||||
_update_summary(summary, sys_div)
|
||||
summary["systems_partially_covered"] += 1
|
||||
else:
|
||||
summary["systems_fully_covered"] += 1
|
||||
|
||||
# Truth systems not matched by any scraped system: all files missing
|
||||
for t_sid in sorted(truth_systems):
|
||||
if t_sid in matched_truth:
|
||||
continue
|
||||
summary["systems_compared"] += 1
|
||||
sys_div = _diff_system(truth_systems[t_sid], {"files": []})
|
||||
if _has_divergences(sys_div):
|
||||
divergences[t_sid] = sys_div
|
||||
_update_summary(summary, sys_div)
|
||||
summary["systems_partially_covered"] += 1
|
||||
else:
|
||||
summary["systems_fully_covered"] += 1
|
||||
|
||||
result: dict = {"summary": summary}
|
||||
if divergences:
|
||||
result["divergences"] = divergences
|
||||
if uncovered_systems:
|
||||
result["uncovered_systems"] = uncovered_systems
|
||||
return result
|
||||
@@ -0,0 +1,391 @@
|
||||
"""The platform side of a truth: its entries by system, the system map, and how two declarations compare."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from core.hashing import HASH_FIELDS, declared_hashes, lists_hashes
|
||||
from model.database import record_for_hash
|
||||
from model.declarations import OUTER_ROOTS
|
||||
from model.systems import norm_system_id
|
||||
from resolve.entryscope import (
|
||||
filter_files_by_mode,
|
||||
installed_with_emulator,
|
||||
opens_by_name,
|
||||
read_from_system_dir,
|
||||
unread_on,
|
||||
)
|
||||
from resolve.launches import PlatformLaunches
|
||||
from resolve.standalone import platform_layouts
|
||||
|
||||
|
||||
def _enrich_hashes(entry: dict, db: dict) -> None:
|
||||
"""Fill the hashes a profile omits from the record its own hash names.
|
||||
|
||||
The record is found by sha1, sha256, then md5, then crc32 with the size
|
||||
when the profile gives one. Never by name: a file in bios/ under the same
|
||||
name may not be the bytes the source code expects. An entry listing
|
||||
several accepted values for a hash is left as is.
|
||||
"""
|
||||
if any(isinstance(entry.get(h), list) for h in HASH_FIELDS):
|
||||
return
|
||||
|
||||
files_db = db.get("files", {})
|
||||
record = None
|
||||
# rust_dos names its SC-55 ROMs by sha256 alone, ares 5200.rom too.
|
||||
for kind in ("sha1", "sha256", "md5"):
|
||||
sha1 = record_for_hash(db, kind, entry.get(kind))
|
||||
if sha1:
|
||||
record = files_db[sha1]
|
||||
break
|
||||
|
||||
# CRC32 (32-bit, collisions theoretically possible): the size must
|
||||
# match when the profile has one.
|
||||
if record is None:
|
||||
sha1 = record_for_hash(db, "crc32", entry.get("crc32"))
|
||||
candidate = files_db[sha1] if sha1 else None
|
||||
if candidate is not None:
|
||||
profile_size = entry.get("size")
|
||||
if not profile_size or candidate.get("size") == profile_size:
|
||||
record = candidate
|
||||
|
||||
if record is None:
|
||||
return
|
||||
|
||||
# Copy sibling hashes and size from the anchored record.
|
||||
for field in ("sha1", "md5", "sha256", "crc32"):
|
||||
if not entry.get(field) and record.get(field):
|
||||
entry[field] = record[field]
|
||||
if not entry.get("size") and record.get("size"):
|
||||
entry["size"] = record["size"]
|
||||
|
||||
|
||||
def _require_by_slot(files: list[dict]) -> None:
|
||||
"""A core that requires a name an entry answers for requires the entry.
|
||||
|
||||
Merged by name, one core's alternatives land in several entries. Ymir
|
||||
reads sega_101.bin, mpr-17933.bin or saturn_bios.bin, so the sega_101.bin
|
||||
entry carries those aliases. kronos, yabause and yabasanshiro open
|
||||
saturn_bios.bin first and sega_101.bin as a fallback: they sat in that
|
||||
entry's _cores, out of its _required_by, while their saturn_bios.bin entry
|
||||
had them requiring it, and a platform line paired through the alias read
|
||||
them as optional. A core already among the entry's readers that requires
|
||||
one of its aliases, as another entry of the system, is one of its
|
||||
requirers. No reader is added.
|
||||
"""
|
||||
required_by_name: dict[str, set[str]] = {}
|
||||
for entry in files:
|
||||
required_by_name.setdefault(entry["name"].lower(), set()).update(
|
||||
entry.get("_required_by", ())
|
||||
)
|
||||
for entry in files:
|
||||
# Only the aliases: entries sharing the entry's own name are other
|
||||
# files that name already kept apart (pak0.pak under each game).
|
||||
names = {str(alias).lower() for alias in entry.get("aliases") or ()}
|
||||
names.discard(entry["name"].lower())
|
||||
requirers = set().union(*(required_by_name.get(n, set()) for n in names))
|
||||
added = (requirers & entry.get("_cores", set())) - entry.get("_required_by", set())
|
||||
if added:
|
||||
entry["_required_by"] = entry.get("_required_by", set()) | added
|
||||
entry["required"] = True
|
||||
|
||||
|
||||
def _brought(file_entry: dict, emu_name: str) -> set[str]:
|
||||
"""The core and build that need the file brought, empty when the
|
||||
emulator installs it. An entry read without layer (a test, a caller of
|
||||
its own) is brought by its core's libretro build."""
|
||||
brought = file_entry.get("_brought", f"{emu_name}:libretro")
|
||||
return {brought} if brought else set()
|
||||
|
||||
|
||||
def _has_exploitable_data(entry: dict) -> bool:
|
||||
"""Check if an entry has any data beyond its name that can drive verification.
|
||||
|
||||
Applied AFTER merging all cores so entries benefit from enrichment by
|
||||
sibling cores before being judged empty.
|
||||
"""
|
||||
return bool(
|
||||
lists_hashes(entry)
|
||||
or entry.get("path")
|
||||
or entry.get("size")
|
||||
or entry.get("min_size")
|
||||
or entry.get("max_size")
|
||||
or entry.get("validation")
|
||||
or entry.get("contents")
|
||||
)
|
||||
|
||||
|
||||
def _system_dir_files(profile: dict, standalone: bool) -> list[dict]:
|
||||
"""Entries of the build the platform runs, read from the system directory.
|
||||
|
||||
An entry the platform's launchers leave outside the BIOS tree
|
||||
(``unplaced``) is not, nor one placed below its roms or an emulator
|
||||
folder (``root``): the platform has no file of its own there.
|
||||
"""
|
||||
return [
|
||||
f for f in filter_files_by_mode(profile.get("files", []), standalone=standalone)
|
||||
if read_from_system_dir(f) and not f.get("unplaced") and f.get("root") not in OUTER_ROOTS
|
||||
]
|
||||
|
||||
|
||||
def _archives_not_members(files: list[dict]) -> list[dict]:
|
||||
"""A profile's entries with the members of each archive folded into it.
|
||||
|
||||
fbneo declares bubsys.zip as the ROMs it holds, each carrying
|
||||
`archive: bubsys.zip`. The platform reads the archive, never a member:
|
||||
as loose files the members were added to RetroArch's System.dat, and
|
||||
the 480-byte boot.bin was filed under the Dreamcast by its bare name.
|
||||
The archive stands in their place with the members as its contents,
|
||||
the shape a profile that declares the archive itself already has.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
archives: dict[tuple[str, str], dict] = {}
|
||||
for fe in files:
|
||||
archive = fe.get("archive")
|
||||
if not archive:
|
||||
out.append(fe)
|
||||
continue
|
||||
key = (archive, fe.get("system", ""))
|
||||
entry = archives.get(key)
|
||||
if entry is None:
|
||||
entry = {"name": archive, "category": "bios_zip", "contents": [],
|
||||
"_brought": None}
|
||||
if fe.get("system"):
|
||||
entry["system"] = fe["system"]
|
||||
if fe.get("source_ref") is not None:
|
||||
entry["source_ref"] = fe["source_ref"]
|
||||
archives[key] = entry
|
||||
out.append(entry)
|
||||
if fe.get("required"):
|
||||
entry["required"] = True
|
||||
# The archive is brought when one member is: gngeo_data.zip, every
|
||||
# member of it installed by make install, is not a file to copy.
|
||||
if "_brought" not in fe:
|
||||
entry.pop("_brought", None)
|
||||
elif "_brought" in entry and entry["_brought"] is None:
|
||||
entry["_brought"] = fe["_brought"]
|
||||
entry["contents"].append({
|
||||
field: fe[field]
|
||||
for field in ("name", "size", "crc32", "sha1", "md5")
|
||||
if fe.get(field) is not None
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _sizes(entry: dict) -> tuple[set[int], tuple[int, float] | None]:
|
||||
"""The sizes an entry admits: exact values, then its window or None.
|
||||
|
||||
An entry that declares no size at all admits every size, an unbounded
|
||||
window. Exact sizes alone leave no window (size_refusal).
|
||||
"""
|
||||
raw = entry.get("size")
|
||||
values = raw if isinstance(raw, list) else [raw]
|
||||
exact = {int(v) for v in values if isinstance(v, int) and not isinstance(v, bool)}
|
||||
low, high = entry.get("min_size"), entry.get("max_size")
|
||||
low = low if isinstance(low, int) else None
|
||||
high = high if isinstance(high, int) else None
|
||||
if low is None and high is None:
|
||||
return exact, None if exact else (0, float("inf"))
|
||||
return exact, (low or 0, float("inf") if high is None else high)
|
||||
|
||||
|
||||
def _sizes_clash(a: dict, b: dict) -> bool:
|
||||
"""No size both entries admit, lists and windows included."""
|
||||
exact_a, window_a = _sizes(a)
|
||||
exact_b, window_b = _sizes(b)
|
||||
|
||||
def inside(value: int, window: tuple[int, float] | None) -> bool:
|
||||
return window is not None and window[0] <= value <= window[1]
|
||||
|
||||
if exact_a & exact_b:
|
||||
return False
|
||||
if any(inside(v, window_b) for v in exact_a) or any(inside(v, window_a) for v in exact_b):
|
||||
return False
|
||||
if window_a and window_b:
|
||||
return max(window_a[0], window_b[0]) > min(window_a[1], window_b[1])
|
||||
return True
|
||||
|
||||
|
||||
def _identity(entry: dict, db: dict | None) -> dict:
|
||||
"""The entry with the hashes and size the database knows for its hash."""
|
||||
probe = {k: entry[k] for k in ("sha1", "md5", "crc32", "size") if entry.get(k)}
|
||||
if db and probe and not any(isinstance(v, list) for v in probe.values()):
|
||||
_enrich_hashes(probe, db)
|
||||
return {**entry, **{k: v for k, v in probe.items() if not entry.get(k)}}
|
||||
|
||||
|
||||
def _identity_values(entry: dict) -> set[str]:
|
||||
"""Every hash an identity declares."""
|
||||
return {v for values in declared_hashes(entry).values() for v in values}
|
||||
|
||||
|
||||
def _declaration_verdict(entry: dict, declaration: dict, db: dict | None) -> str:
|
||||
"""same, other or undecided: can a platform declaration be this file?
|
||||
|
||||
A shared hash proves it. Sizes no value of which agrees refute it, as
|
||||
name_match_size_ok refutes a candidate. Two hashes at one size are two
|
||||
revisions of one slot, as slots.py reads them, so they refute nothing.
|
||||
The size the database holds for a declared hash counts as declared:
|
||||
Batocera's BK BASIC10.ROM names only an md5, of a 24576-byte file, and
|
||||
clk's 16 KB Oric basic10.rom was filed under the BK beside it.
|
||||
"""
|
||||
ours, theirs = _identity(entry, db), _identity(declaration, db)
|
||||
if _identity_values(ours) & _identity_values(theirs):
|
||||
return "same"
|
||||
if _sizes_clash(ours, theirs):
|
||||
return "other"
|
||||
return "undecided"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SystemMap:
|
||||
"""How a profile's systems and entries map onto a platform's systems."""
|
||||
|
||||
platform_sys_ids: set[str]
|
||||
# Every platform declaration of a name, in the platform's order. The
|
||||
# last one used to win, whatever the content.
|
||||
declared_by_name: dict[str, list[tuple[str, dict]]]
|
||||
# Normalized ID -> platform system ID. Walked in the platform's order,
|
||||
# not the set's: two IDs normalizing alike went to whichever the hash
|
||||
# seed put last.
|
||||
norm_to_platform: dict[str, str]
|
||||
db: dict | None
|
||||
|
||||
@classmethod
|
||||
def of(cls, config: dict, db: dict | None) -> _SystemMap:
|
||||
declared_by_name: dict[str, list[tuple[str, dict]]] = {}
|
||||
for psid, sys_data in config.get("systems", {}).items():
|
||||
for fe in sys_data.get("files", []):
|
||||
fname = fe.get("name", "").lower()
|
||||
if fname:
|
||||
declared_by_name.setdefault(fname, []).append((psid, fe))
|
||||
norm_to_platform: dict[str, str] = {}
|
||||
for psid in config.get("systems", {}):
|
||||
norm_to_platform.setdefault(norm_system_id(psid), psid)
|
||||
return cls(
|
||||
set(config.get("systems", {}).keys()), declared_by_name, norm_to_platform, db,
|
||||
)
|
||||
|
||||
def map_sys_id(self, profile_sid: str) -> str:
|
||||
"""Map a profile system ID to the platform's system ID."""
|
||||
if profile_sid in self.platform_sys_ids:
|
||||
return profile_sid
|
||||
return self.norm_to_platform.get(norm_system_id(profile_sid), profile_sid)
|
||||
|
||||
def attribute(self, fe: dict, own: str | None, on_platform: set[str]) -> list[str]:
|
||||
"""The platform systems an entry belongs to, [] when nothing decides.
|
||||
|
||||
A declaration of the same name settles the system only when it can
|
||||
be the same file: a shared hash, or no contradicting size. fmsx's
|
||||
16 KB DISK.ROM is not quasi88's 2 KB disk.rom, and dosbox's SC-55
|
||||
ROM1.BIN is not galaksija's. The same content declared under two
|
||||
systems is filed under both.
|
||||
"""
|
||||
verdicts = [
|
||||
(psid, _declaration_verdict(fe, decl, self.db))
|
||||
for psid, decl in self.declared_by_name.get(fe.get("name", "").lower(), [])
|
||||
]
|
||||
same = sorted({psid for psid, v in verdicts if v == "same"})
|
||||
undecided = sorted({psid for psid, v in verdicts if v == "undecided"})
|
||||
if own is not None:
|
||||
mapped = self.map_sys_id(own)
|
||||
if any(psid == mapped and v != "other" for psid, v in verdicts):
|
||||
return [mapped]
|
||||
if same:
|
||||
return same
|
||||
if len(undecided) == 1:
|
||||
return undecided
|
||||
return [mapped]
|
||||
if same:
|
||||
return same
|
||||
if len(undecided) == 1:
|
||||
return undecided
|
||||
if undecided:
|
||||
ours = [psid for psid in undecided if psid in on_platform]
|
||||
return ours if len(ours) == 1 else []
|
||||
return [next(iter(on_platform))] if len(on_platform) == 1 else []
|
||||
|
||||
def targets(self, fe: dict, profile: dict, on_platform: set[str]) -> list[str]:
|
||||
"""The platform systems an entry is filed under."""
|
||||
profile_sid = fe.get("system", "")
|
||||
sys_ids = profile.get("systems", [])
|
||||
if profile_sid:
|
||||
own: str | None = profile_sid
|
||||
elif len(sys_ids) == 1:
|
||||
own = sys_ids[0]
|
||||
elif not sys_ids:
|
||||
# A profile that names no system: a platform declaration of
|
||||
# the same file files it, and the placeholder takes only a
|
||||
# name the platform does not declare. mess2015's hiscore.dat
|
||||
# beside the arcade one put an "unknown" section in System.dat.
|
||||
own = None
|
||||
else:
|
||||
# A multi-system profile's entry without a system is filed by
|
||||
# the platform's own declaration of the same file, or the one
|
||||
# profile system the platform has. Otherwise it is not filed:
|
||||
# the first system was a guess, and CLK's Apple, Mac, ZX and
|
||||
# Amiga ROMs went to RomM as Amstrad CPC firmware.
|
||||
own = None
|
||||
sys_targets = self.attribute(fe, own, on_platform)
|
||||
if not sys_ids and not profile_sid and not sys_targets \
|
||||
and fe.get("name", "").lower() not in self.declared_by_name:
|
||||
sys_targets = [self.map_sys_id("unknown")]
|
||||
return sys_targets
|
||||
|
||||
|
||||
def _cover(
|
||||
system_cores: dict[str, dict[str, set[str]]], sys_id: str, kind: str, emu_name: str,
|
||||
) -> None:
|
||||
sys_cov = system_cores.setdefault(
|
||||
sys_id,
|
||||
{
|
||||
"profiled": set(),
|
||||
"unprofiled": set(),
|
||||
},
|
||||
)
|
||||
sys_cov[kind].add(emu_name)
|
||||
|
||||
|
||||
def _platform_entries(
|
||||
emu_name: str, profile: dict, launches: PlatformLaunches, platform_name: str,
|
||||
) -> list[dict]:
|
||||
# The pack's rule (validation.deliverable), per build: a file the
|
||||
# emulator installs is kept and marked, one the launcher never opens
|
||||
# is left out.
|
||||
return _archives_not_members([
|
||||
{
|
||||
**fe,
|
||||
"_opens_by_name": opens_by_name(fe, profile, standalone),
|
||||
"_brought": None if installed_with_emulator(fe, platform_name)
|
||||
else f"{emu_name}:{'standalone' if standalone else 'libretro'}",
|
||||
}
|
||||
for view, standalone in platform_layouts(emu_name, profile, launches)
|
||||
for fe in _system_dir_files(view, standalone)
|
||||
if not unread_on(fe, platform_name)
|
||||
])
|
||||
|
||||
|
||||
def _serialize_systems(
|
||||
systems: dict[str, dict], system_cores: dict[str, dict[str, set[str]]],
|
||||
) -> None:
|
||||
# Convert sets to sorted lists for serialization
|
||||
for sys_id, sys_data in systems.items():
|
||||
for fe in sys_data.get("files", []):
|
||||
fe.pop("_hash_by", None)
|
||||
fe.pop("_region_void", None)
|
||||
fe["_cores"] = sorted(fe.get("_cores", set()))
|
||||
fe["_required_by"] = sorted(fe.get("_required_by", set()))
|
||||
one_of = fe.pop("_one_of", None)
|
||||
if one_of:
|
||||
fe["one_of"] = sorted(one_of)
|
||||
fe["_named_by"] = sorted(fe.get("_named_by", set()))
|
||||
fe["_brought_by"] = sorted(fe.get("_brought_by", set()))
|
||||
if not fe["_brought_by"]:
|
||||
fe["bundled"] = True
|
||||
fe["_source_refs"] = sorted(fe.get("_source_refs", set()))
|
||||
# Add per-system coverage
|
||||
cov = system_cores.get(sys_id, {})
|
||||
sys_data["_coverage"] = {
|
||||
"cores_profiled": sorted(cov.get("profiled", set())),
|
||||
"cores_unprofiled": sorted(cov.get("unprofiled", set())),
|
||||
}
|
||||
@@ -471,7 +471,8 @@ def _divergence_rows(
|
||||
coverages: dict, registries: PlatformRegistries, profiles: dict, db: dict,
|
||||
) -> list[str]:
|
||||
"""Section 1b: platform lists vs emulator source, one row a platform."""
|
||||
from resolve.truth import diff_platform_truth, generate_platform_truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
from resolve.truth import generate_platform_truth
|
||||
|
||||
div_rows = []
|
||||
for pname, cov in _by_platform_name(coverages):
|
||||
|
||||
@@ -7626,7 +7626,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
|
||||
def test_the_truth_anchors_a_sha256_only_entry(self):
|
||||
"""rust_dos and ares name files by sha256 alone: the truth left their
|
||||
md5 empty, so md5 platforms never received them."""
|
||||
from scripts.resolve.truth import _enrich_hashes
|
||||
from scripts.resolve.truthsystems import _enrich_hashes
|
||||
|
||||
db = {"files": {"s" * 40: {"sha1": "s" * 40, "md5": "m" * 32, "sha256": "f" * 64,
|
||||
"crc32": "0badf00d", "size": 16}},
|
||||
|
||||
+5
-4
@@ -42,7 +42,8 @@ from model.profiles import ProfileSelectionError, load_emulator_profiles
|
||||
from model.platforms import load_platform_config
|
||||
from resolve.localfile import resolve_local_file
|
||||
from resolve.cores import resolve_platform_cores
|
||||
from resolve.truth import diff_platform_truth, generate_platform_truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
from resolve.truth import generate_platform_truth
|
||||
from resolve.validation import build_validation_index, check_file_validation
|
||||
from resolve.entryscope import filter_files_by_mode
|
||||
from packs.verdicts import Severity, Status
|
||||
@@ -4310,7 +4311,7 @@ class TestE2E(unittest.TestCase):
|
||||
|
||||
def test_104_diff_truth_normalized_system_ids(self):
|
||||
"""Diff matches systems with different ID formats via normalization."""
|
||||
from resolve.truth import diff_platform_truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
|
||||
truth = {
|
||||
"systems": {
|
||||
@@ -4681,7 +4682,7 @@ class TestE2E(unittest.TestCase):
|
||||
|
||||
def test_177_diff_hash_fallback_rename(self):
|
||||
"""Diff detects platform renames via hash fallback."""
|
||||
from resolve.truth import diff_platform_truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
|
||||
truth = {
|
||||
"systems": {
|
||||
@@ -4716,7 +4717,7 @@ class TestE2E(unittest.TestCase):
|
||||
|
||||
def test_178_diff_system_normalization(self):
|
||||
"""Diff matches systems with different IDs via normalization."""
|
||||
from resolve.truth import diff_platform_truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
|
||||
truth = {
|
||||
"systems": {
|
||||
|
||||
@@ -355,7 +355,7 @@ class Reconciliation(unittest.TestCase):
|
||||
self.assertEqual(report.hashes_corrected, [])
|
||||
|
||||
def test_the_diff_names_no_mismatch_the_code_does_not_check(self):
|
||||
from resolve.truth import _diff_system
|
||||
from resolve.platformdiff import _diff_system
|
||||
truth_sys = {"files": [{"name": "scph1001.bin", "md5": "a" * 32,
|
||||
"validation": ["size"]}]}
|
||||
scraped_sys = {"files": [{"name": "scph1001.bin", "md5": "b" * 32}]}
|
||||
@@ -399,7 +399,7 @@ class Reconciliation(unittest.TestCase):
|
||||
self.assertEqual(report.hashes_corrected, [])
|
||||
|
||||
def test_the_diff_names_no_missing_label(self):
|
||||
from resolve.truth import _diff_system
|
||||
from resolve.platformdiff import _diff_system
|
||||
truth_sys = {"files": [{"name": "scph1001_v20.bin", "md5": "a" * 32,
|
||||
"_cores": ["duckstation"], "_named_by": []}]}
|
||||
self.assertNotIn("missing", _diff_system(truth_sys, {"files": []}))
|
||||
@@ -440,7 +440,7 @@ class Reconciliation(unittest.TestCase):
|
||||
self.assertEqual(added.runners, [(False, "armsx2")])
|
||||
|
||||
def test_the_diff_names_no_missing_bundled_file(self):
|
||||
from resolve.truth import _diff_system
|
||||
from resolve.platformdiff import _diff_system
|
||||
truth_sys = {"files": [{"name": "gngeo_data.zip", "md5": "a" * 32, "bundled": True,
|
||||
"_cores": ["gngeopi"], "_named_by": ["gngeopi"],
|
||||
"_brought_by": []}]}
|
||||
@@ -449,7 +449,7 @@ class Reconciliation(unittest.TestCase):
|
||||
def test_the_diff_pairs_by_the_same_rule(self):
|
||||
"""diff_truth reads the same pairing, or it names a mismatch the
|
||||
export does not correct."""
|
||||
from resolve.truth import _diff_system
|
||||
from resolve.platformdiff import _diff_system
|
||||
truth_sys = {"files": [
|
||||
{"name": "system.rom", "aliases": ["bios.rom"], "md5": "c" * 32},
|
||||
{"name": "bios.rom", "path": "np2kai/bios.rom"},
|
||||
|
||||
@@ -24,6 +24,7 @@ from exporter import diffreport
|
||||
import pipeline
|
||||
from orchestrate import guards, labels, prepare, runner
|
||||
from resolve import truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
from packs import coverage
|
||||
from packs import report as packs_report
|
||||
from packs import verdicts
|
||||
@@ -500,7 +501,7 @@ class TheTruthDiffShowsWhereAndAsksNothing(unittest.TestCase):
|
||||
scraped_sys = {"files": [
|
||||
{"name": "hiscore.dat", "destination": "fbneo/hiscore.dat", "md5": "b" * 32},
|
||||
]}
|
||||
report = truth.diff_platform_truth(
|
||||
report = diff_platform_truth(
|
||||
{"systems": {"arcade": truth_sys}}, {"systems": {"arcade": scraped_sys}}
|
||||
)
|
||||
report["platform"] = "p"
|
||||
|
||||
@@ -18,7 +18,8 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
from resolve.reconcile import pair_entries
|
||||
from resolve.truth import _diff_system, _merge_file_into_system, generate_platform_truth
|
||||
from resolve.platformdiff import _diff_system
|
||||
from resolve.truth import _merge_file_into_system, generate_platform_truth
|
||||
|
||||
|
||||
def _entry(name: str, **hashes) -> dict:
|
||||
|
||||
@@ -181,7 +181,7 @@ class EveryRevisionACoreAcceptsStays(unittest.TestCase):
|
||||
giving 1.07's sha1 and md5 is that revision, not a mismatch. dosbox
|
||||
checks the sha1 (validation), so its md5 describes one revision and
|
||||
contradicts nothing, the rule the export applies too."""
|
||||
from resolve.truth import _hash_mismatch
|
||||
from resolve.platformdiff import _hash_mismatch
|
||||
|
||||
truth = {"name": "MT32_CONTROL.ROM", "md5": "c" * 32, "sha1": ["a" * 40, "b" * 40],
|
||||
"validation": ["sha1"]}
|
||||
@@ -206,7 +206,7 @@ class DiffAndExportShareOneMismatchRule(unittest.TestCase):
|
||||
|
||||
def test_the_diff_names_what_the_export_corrects(self):
|
||||
from resolve.reconcile import build_native_model
|
||||
from resolve.truth import diff_platform_truth
|
||||
from resolve.platformdiff import diff_platform_truth
|
||||
|
||||
for t_hashes, p_hashes in self.CASES:
|
||||
with self.subTest(truth=t_hashes, platform=p_hashes):
|
||||
@@ -338,7 +338,7 @@ class ASizeOutsideARangeIsAnotherFile(unittest.TestCase):
|
||||
def test_exact_sizes_and_a_window_admit_both(self):
|
||||
"""An entry admits its exact sizes and the window declared beside
|
||||
them, as size_refusal reads it. Two windows with no common size clash."""
|
||||
from resolve.truth import _sizes_clash
|
||||
from resolve.truthsystems import _sizes_clash
|
||||
|
||||
disk = {"size": [143360, 143403, 143488], "min_size": 143105, "max_size": 143364}
|
||||
self.assertFalse(_sizes_clash(disk, {"size": 143200}))
|
||||
|
||||
Reference in new issue
Block a user