mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-30 21:38:55 -06:00
chore: merge the verify and truth quality work
This commit is contained in:
commit
e14a7d79bb
26 files changed
+3555
-2651
No files matched your search
+445
-311
@@ -20,7 +20,10 @@ import sys
|
|||||||
import zipfile
|
import zipfile
|
||||||
import zlib
|
import zlib
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
|
import dataclasses
|
||||||
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING, TypedDict
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(__file__))
|
sys.path.insert(0, os.path.dirname(__file__))
|
||||||
from alternatives import set_keys, set_requirements, settle_sets
|
from alternatives import set_keys, set_requirements, settle_sets
|
||||||
@@ -79,6 +82,9 @@ from validation import (
|
|||||||
with_archive_members,
|
with_archive_members,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from typing_extensions import Unpack
|
||||||
|
|
||||||
yaml = require_yaml()
|
yaml = require_yaml()
|
||||||
|
|
||||||
DEFAULT_EMULATORS_DIR = "emulators"
|
DEFAULT_EMULATORS_DIR = "emulators"
|
||||||
@@ -97,8 +103,8 @@ def load_platform_files(
|
|||||||
RetroArch writes `sega-mega-cd`, and an exact match called 924 declared
|
RetroArch writes `sega-mega-cd`, and an exact match called 924 declared
|
||||||
files undeclared.
|
files undeclared.
|
||||||
"""
|
"""
|
||||||
declared = {}
|
declared: dict[str, set[str]] = {}
|
||||||
platform_data_dirs = {}
|
platform_data_dirs: dict[str, set[str]] = {}
|
||||||
for platform_name in platforms or list_registered_platforms(
|
for platform_name in platforms or list_registered_platforms(
|
||||||
platforms_dir
|
platforms_dir
|
||||||
):
|
):
|
||||||
@@ -277,11 +283,10 @@ def _resolve_source(
|
|||||||
key = fname.lower()
|
key = fname.lower()
|
||||||
if key in by_name_lower and _folded_hit(by_name_lower[key]):
|
if key in by_name_lower and _folded_hit(by_name_lower[key]):
|
||||||
return "bios"
|
return "bios"
|
||||||
if basename:
|
if basename and basename.lower() in by_name_lower and _folded_hit(
|
||||||
if basename.lower() in by_name_lower and _folded_hit(
|
by_name_lower[basename.lower()]
|
||||||
by_name_lower[basename.lower()]
|
):
|
||||||
):
|
return "bios"
|
||||||
return "bios"
|
|
||||||
# bios/ via by_path_suffix (regional variants)
|
# bios/ via by_path_suffix (regional variants)
|
||||||
if by_path_suffix and fname in by_path_suffix and _can_be(by_path_suffix[fname]):
|
if by_path_suffix and fname in by_path_suffix and _can_be(by_path_suffix[fname]):
|
||||||
return "bios"
|
return "bios"
|
||||||
@@ -749,129 +754,89 @@ def profile_breakdown(data: dict) -> str:
|
|||||||
return ", ".join(parts)
|
return ", ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
def _cross_reference_profile(
|
def _effective_path(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str:
|
||||||
emu_name: str,
|
# The destination the running build reads, as find_undeclared_files
|
||||||
profile: dict,
|
# takes it: Batocera's standalone Cemu reads keys.txt at
|
||||||
declared: dict[str, set[str]],
|
# standalone_path, and the libretro Cemu/keys.txt reported here
|
||||||
report: dict,
|
# settled the declaration on a slot the platform never fills.
|
||||||
index: dict,
|
if is_standalone:
|
||||||
standalone_cores: set[str] | None = None,
|
return f.get("standalone_path") or f.get("path") or fname
|
||||||
platform: str = "",
|
if save_root:
|
||||||
) -> None:
|
return f.get("path") or fname
|
||||||
"""Compare one emulator profile against what the platforms declare.
|
return system_dir_path(f, f.get("path") or fname)
|
||||||
|
|
||||||
*platform* is the platform key under --platform, empty for the whole
|
|
||||||
tree. It decides, through the functions verify reads, which entries the
|
|
||||||
platform's launcher never opens and which ones its emulator package
|
|
||||||
already installs.
|
|
||||||
|
|
||||||
Split out of cross_reference, where it was a 200-line loop body that
|
@dataclass
|
||||||
carried the whole function's branching: every file is resolved by name,
|
class _ProfileComparison:
|
||||||
by path, by hash and by archive membership before it can be called a
|
"""One profile's entries against the platforms' declarations."""
|
||||||
gap. *index* carries the database lookups those steps share.
|
|
||||||
"""
|
|
||||||
by_name = index["by_name"]
|
|
||||||
by_name_lower = index["by_name_lower"]
|
|
||||||
by_path_suffix = index["by_path_suffix"]
|
|
||||||
data_names = index["data_names"]
|
|
||||||
all_declared = index["all_declared"]
|
|
||||||
emu_files = profile.get("files", [])
|
|
||||||
systems = profile.get("systems", [])
|
|
||||||
|
|
||||||
# Skip filename-agnostic profiles (BIOS detected without fixed names)
|
emu_name: str
|
||||||
if profile.get("bios_mode") == "agnostic":
|
profile: dict
|
||||||
return
|
index: dict
|
||||||
|
platform_names: set[str]
|
||||||
if all_declared is not None:
|
platform: str
|
||||||
platform_names = all_declared
|
layouts: list
|
||||||
else:
|
versions: dict[tuple, list[dict]] = dataclasses.field(default_factory=dict)
|
||||||
platform_names = set()
|
position: dict[int, int] = dataclasses.field(default_factory=dict)
|
||||||
for sys_id in systems:
|
gaps: list[dict] = dataclasses.field(default_factory=list)
|
||||||
platform_names.update(declared.get(_norm_system_id(sys_id), set()))
|
covered: list[dict] = dataclasses.field(default_factory=list)
|
||||||
|
unsourceable_list: list[dict] = dataclasses.field(default_factory=list)
|
||||||
# The build a platform runs decides which entries it reads, as in
|
archive_gaps: dict[tuple, dict] = dataclasses.field(default_factory=dict)
|
||||||
# find_undeclared_files: without a platform, the libretro build.
|
seen_files: set[tuple] = dataclasses.field(default_factory=set)
|
||||||
layouts = platform_layouts(emu_name, profile, standalone_cores or set())
|
fates: dict[int, str] = dataclasses.field(default_factory=dict)
|
||||||
# Each file under each layout the platform gives the emulator: both, for
|
|
||||||
# one it launches as a libretro core and standalone.
|
|
||||||
layout_files = [(f, standalone) for view, standalone in layouts for f in view.get("files", [])]
|
|
||||||
gaps = []
|
|
||||||
covered = []
|
|
||||||
unsourceable_list: list[dict] = []
|
|
||||||
archive_gaps: dict[tuple, dict] = {}
|
|
||||||
seen_files: set[tuple] = set()
|
|
||||||
|
|
||||||
# The entries of one profile on one slot are the versions its code
|
|
||||||
# accepts there (raze's ten DUKE3D.GRP): holding any of them fills the
|
|
||||||
# slot, as verify --emulator credits it.
|
|
||||||
versions: dict[tuple, list[dict]] = {}
|
|
||||||
for f, is_standalone in layout_files:
|
|
||||||
versions.setdefault(slot_key(f, is_standalone), []).append(f)
|
|
||||||
|
|
||||||
# What became of each entry, so the heading adds up: a file a platform
|
|
||||||
# declares, one it does not, or one set aside and why. An entry read by
|
|
||||||
# two builds keeps the first answer that compares it. Each layout lists
|
|
||||||
# the profile's entries in their order, so a position names one entry.
|
|
||||||
position = {id(f): i for view, _ in layouts for i, f in enumerate(view.get("files", []))}
|
|
||||||
fates: dict[int, str] = {}
|
|
||||||
# Grouped entries met, as (set keys, entry, fills, the list holding
|
# Grouped entries met, as (set keys, entry, fills, the list holding
|
||||||
# its row, the row): settled once the profile is read.
|
# its row, the row): settled once the profile is read.
|
||||||
set_records: list[tuple[tuple, dict, bool, list | None, dict | None]] = []
|
set_records: list[tuple[tuple, dict, bool, list | None, dict | None]] = dataclasses.field(
|
||||||
archive_rows: list[dict] = []
|
default_factory=list
|
||||||
|
)
|
||||||
|
archive_rows: list[dict] = dataclasses.field(default_factory=list)
|
||||||
|
|
||||||
def fate(f: dict, what: str) -> None:
|
def fate(self, f: dict, what: str) -> None:
|
||||||
key = position[id(f)]
|
key = self.position[id(f)]
|
||||||
current = fates.get(key)
|
current = self.fates.get(key)
|
||||||
if current is None or (current in SET_ASIDE and what not in SET_ASIDE):
|
if current is None or (current in SET_ASIDE and what not in SET_ASIDE):
|
||||||
fates[key] = what
|
self.fates[key] = what
|
||||||
|
|
||||||
for f, is_standalone in layout_files:
|
def compare(self, f: dict, is_standalone: bool) -> None:
|
||||||
|
"""File one entry of one build: declared, a gap, or set aside."""
|
||||||
fname = f.get("name", "")
|
fname = f.get("name", "")
|
||||||
# The destination the running build reads, as find_undeclared_files
|
platform = self.platform
|
||||||
# takes it: Batocera's standalone Cemu reads keys.txt at
|
|
||||||
# standalone_path, and the libretro Cemu/keys.txt reported here
|
|
||||||
# settled the declaration on a slot the platform never fills.
|
|
||||||
save_root = read_from_save_dir(f, is_standalone)
|
save_root = read_from_save_dir(f, is_standalone)
|
||||||
if is_standalone:
|
effective_path = _effective_path(f, fname, is_standalone, save_root)
|
||||||
effective_path = f.get("standalone_path") or f.get("path") or fname
|
|
||||||
elif save_root:
|
|
||||||
effective_path = f.get("path") or fname
|
|
||||||
else:
|
|
||||||
effective_path = system_dir_path(f, f.get("path") or fname)
|
|
||||||
slot = slot_key(f, is_standalone)
|
slot = slot_key(f, is_standalone)
|
||||||
seen_key = slot
|
seen_key = slot
|
||||||
if len(layouts) > 1:
|
if len(self.layouts) > 1:
|
||||||
# One file read at one path by both builds counts once.
|
# One file read at one path by both builds counts once.
|
||||||
seen_key = (effective_path.casefold(), seen_key)
|
seen_key = (effective_path.casefold(), seen_key)
|
||||||
if not fname:
|
if not fname:
|
||||||
fate(f, "outside_scope")
|
self.fate(f, "outside_scope")
|
||||||
continue
|
return
|
||||||
if seen_key in seen_files:
|
if seen_key in self.seen_files:
|
||||||
fate(f, "other_versions")
|
self.fate(f, "other_versions")
|
||||||
continue
|
return
|
||||||
if unread_on(f, platform):
|
if unread_on(f, platform):
|
||||||
fate(f, "not_read")
|
self.fate(f, "not_read")
|
||||||
continue
|
return
|
||||||
|
|
||||||
# Collect unsourceable files separately (documented, not a gap)
|
# Collect unsourceable files separately (documented, not a gap)
|
||||||
unsourceable_reason = f.get("unsourceable", "")
|
unsourceable_reason = f.get("unsourceable", "")
|
||||||
keys = set_keys((emu_name, is_standalone), f)
|
keys = set_keys((self.emu_name, is_standalone), f)
|
||||||
if unsourceable_reason:
|
if unsourceable_reason:
|
||||||
seen_files.add(seen_key)
|
self.seen_files.add(seen_key)
|
||||||
fate(f, "unsourceable")
|
self.fate(f, "unsourceable")
|
||||||
row = {
|
row = {
|
||||||
"name": fname,
|
"name": fname,
|
||||||
"required": f.get("required", False),
|
"required": f.get("required", False),
|
||||||
"reason": unsourceable_reason,
|
"reason": unsourceable_reason,
|
||||||
"source_ref": f.get("source_ref", ""),
|
"source_ref": f.get("source_ref", ""),
|
||||||
}
|
}
|
||||||
unsourceable_list.append(row)
|
self.unsourceable_list.append(row)
|
||||||
set_records.append((keys, f, False, unsourceable_list, row))
|
self.set_records.append((keys, f, False, self.unsourceable_list, row))
|
||||||
continue
|
return
|
||||||
|
|
||||||
if outside_gap_scope(f, is_standalone):
|
if outside_gap_scope(f, is_standalone):
|
||||||
fate(f, "outside_scope")
|
self.fate(f, "outside_scope")
|
||||||
continue
|
return
|
||||||
|
|
||||||
archive = f.get("archive")
|
archive = f.get("archive")
|
||||||
|
|
||||||
@@ -881,77 +846,88 @@ def _cross_reference_profile(
|
|||||||
# A platform declares files of its BIOS tree: none answers for one
|
# A platform declares files of its BIOS tree: none answers for one
|
||||||
# the core reads below the save directory.
|
# the core reads below the save directory.
|
||||||
in_platform = not save_root and f.get("root") not in OUTER_ROOTS and declaration_settles(
|
in_platform = not save_root and f.get("root") not in OUTER_ROOTS and declaration_settles(
|
||||||
f, fname, platform_names, effective_path, index.get("folded_slots", frozenset()),
|
f, fname, self.platform_names, effective_path,
|
||||||
index.get("declared_contents"),
|
self.index.get("folded_slots", frozenset()),
|
||||||
|
self.index.get("declared_contents"),
|
||||||
)
|
)
|
||||||
|
|
||||||
if in_platform:
|
if in_platform:
|
||||||
seen_files.add(seen_key)
|
self.seen_files.add(seen_key)
|
||||||
fate(f, "declared")
|
self.fate(f, "declared")
|
||||||
set_records.append((keys, f, True, None, None))
|
self.set_records.append((keys, f, True, None, None))
|
||||||
covered.append({
|
self.covered.append({
|
||||||
"name": fname,
|
"name": fname,
|
||||||
"path": effective_path,
|
"path": effective_path,
|
||||||
"required": f.get("required", False),
|
"required": f.get("required", False),
|
||||||
"in_platform": True,
|
"in_platform": True,
|
||||||
})
|
})
|
||||||
continue
|
return
|
||||||
|
|
||||||
seen_files.add(seen_key)
|
self.seen_files.add(seen_key)
|
||||||
fate(f, "undeclared")
|
self.fate(f, "undeclared")
|
||||||
|
|
||||||
if archive:
|
if archive:
|
||||||
archive_key = (
|
self._archive_gap(f, archive, is_standalone)
|
||||||
archive,
|
return
|
||||||
f.get("system"),
|
self._loose_gap(f, fname, is_standalone, save_root, effective_path, slot, keys)
|
||||||
f.get("selection_slot"),
|
|
||||||
f.get("mode", "both"),
|
|
||||||
)
|
|
||||||
if archive_key not in archive_gaps:
|
|
||||||
source = _resolve_archive_source(
|
|
||||||
archive, by_name, by_name_lower, data_names,
|
|
||||||
by_path_suffix,
|
|
||||||
)
|
|
||||||
archive_gaps[archive_key] = {
|
|
||||||
"name": archive,
|
|
||||||
"path": archive,
|
|
||||||
"required": False,
|
|
||||||
"note": "",
|
|
||||||
"source_ref": "",
|
|
||||||
"in_platform": False,
|
|
||||||
"in_repo": source != "missing",
|
|
||||||
"source": source,
|
|
||||||
"archive": archive,
|
|
||||||
"archive_file_count": 0,
|
|
||||||
"archive_required_count": 0,
|
|
||||||
}
|
|
||||||
entry = archive_gaps[archive_key]
|
|
||||||
if entry["archive_file_count"] == 0:
|
|
||||||
# The archive's own declaration names its sets: an archive
|
|
||||||
# is a member like a loose file (Kronos' stvbios.zip).
|
|
||||||
own = archive_entry(archive, emu_files)
|
|
||||||
set_records.append((
|
|
||||||
set_keys((emu_name, is_standalone), own), own,
|
|
||||||
entry["in_repo"], archive_rows, entry,
|
|
||||||
))
|
|
||||||
archive_rows.append(entry)
|
|
||||||
entry["archive_file_count"] += 1
|
|
||||||
if f.get("required", False):
|
|
||||||
entry["archive_required_count"] += 1
|
|
||||||
entry["required"] = True
|
|
||||||
if not entry["source_ref"] and f.get("source_ref"):
|
|
||||||
entry["source_ref"] = f["source_ref"]
|
|
||||||
continue
|
|
||||||
|
|
||||||
|
def _archive_gap(self, f: dict, archive: str, is_standalone: bool) -> None:
|
||||||
|
archive_key = (
|
||||||
|
archive,
|
||||||
|
f.get("system"),
|
||||||
|
f.get("selection_slot"),
|
||||||
|
f.get("mode", "both"),
|
||||||
|
)
|
||||||
|
if archive_key not in self.archive_gaps:
|
||||||
|
source = _resolve_archive_source(
|
||||||
|
archive, self.index["by_name"], self.index["by_name_lower"],
|
||||||
|
self.index["data_names"], self.index["by_path_suffix"],
|
||||||
|
)
|
||||||
|
self.archive_gaps[archive_key] = {
|
||||||
|
"name": archive,
|
||||||
|
"path": archive,
|
||||||
|
"required": False,
|
||||||
|
"note": "",
|
||||||
|
"source_ref": "",
|
||||||
|
"in_platform": False,
|
||||||
|
"in_repo": source != "missing",
|
||||||
|
"source": source,
|
||||||
|
"archive": archive,
|
||||||
|
"archive_file_count": 0,
|
||||||
|
"archive_required_count": 0,
|
||||||
|
}
|
||||||
|
entry = self.archive_gaps[archive_key]
|
||||||
|
if entry["archive_file_count"] == 0:
|
||||||
|
# The archive's own declaration names its sets: an archive
|
||||||
|
# is a member like a loose file (Kronos' stvbios.zip).
|
||||||
|
own = archive_entry(archive, self.profile.get("files", []))
|
||||||
|
self.set_records.append((
|
||||||
|
set_keys((self.emu_name, is_standalone), own), own,
|
||||||
|
entry["in_repo"], self.archive_rows, entry,
|
||||||
|
))
|
||||||
|
self.archive_rows.append(entry)
|
||||||
|
entry["archive_file_count"] += 1
|
||||||
|
if f.get("required", False):
|
||||||
|
entry["archive_required_count"] += 1
|
||||||
|
entry["required"] = True
|
||||||
|
if not entry["source_ref"] and f.get("source_ref"):
|
||||||
|
entry["source_ref"] = f["source_ref"]
|
||||||
|
|
||||||
|
def _loose_gap(
|
||||||
|
self, f: dict, fname: str, is_standalone: bool, save_root: bool,
|
||||||
|
effective_path: str, slot: tuple, keys: tuple,
|
||||||
|
) -> None:
|
||||||
|
emu_name = self.emu_name
|
||||||
|
platform = self.platform
|
||||||
# --- resolve source provenance ---
|
# --- resolve source provenance ---
|
||||||
# A release asset is held when the database records it, as any other
|
# A release asset is held when the database records it, as any other
|
||||||
# file: storage says where the bytes are served from, not that the
|
# file: storage says where the bytes are served from, not that the
|
||||||
# collection has them (kenji-nx's user-picked firmware package).
|
# collection has them (kenji-nx's user-picked firmware package).
|
||||||
source = next(
|
source = next(
|
||||||
(
|
(
|
||||||
found for version in versions[slot]
|
found for version in self.versions[slot]
|
||||||
if (found := entry_source(
|
if (found := entry_source(
|
||||||
{**version, "source_profile": emu_name}, index,
|
{**version, "source_profile": emu_name}, self.index,
|
||||||
)) is not None
|
)) is not None
|
||||||
),
|
),
|
||||||
"missing",
|
"missing",
|
||||||
@@ -980,65 +956,131 @@ def _cross_reference_profile(
|
|||||||
entry["unplaced"] = f["unplaced"]
|
entry["unplaced"] = f["unplaced"]
|
||||||
elif f.get("root") in OUTER_ROOTS:
|
elif f.get("root") in OUTER_ROOTS:
|
||||||
entry["root"] = f["root"]
|
entry["root"] = f["root"]
|
||||||
elif index.get("launcher_candidates") is not None:
|
elif self.index.get("launcher_candidates") is not None:
|
||||||
# What verify hands the launcher layer for the same entry.
|
# What verify hands the launcher layer for the same entry.
|
||||||
probe = {
|
probe = {
|
||||||
**f,
|
**f,
|
||||||
"profile": emu_name,
|
"profile": emu_name,
|
||||||
"emulator": profile.get("emulator", emu_name),
|
"emulator": self.profile.get("emulator", emu_name),
|
||||||
"path": effective_path,
|
"path": effective_path,
|
||||||
"in_repo": in_repo,
|
"in_repo": in_repo,
|
||||||
"bundled": entry["bundled"],
|
"bundled": entry["bundled"],
|
||||||
}
|
}
|
||||||
index["launcher_candidates"].append(
|
self.index["launcher_candidates"].append(
|
||||||
(emu_name, is_standalone, f, probe, entry)
|
(emu_name, is_standalone, f, probe, entry)
|
||||||
)
|
)
|
||||||
gaps.append(entry)
|
self.gaps.append(entry)
|
||||||
set_records.append((keys, f, in_repo, gaps, entry))
|
self.set_records.append((keys, f, in_repo, self.gaps, entry))
|
||||||
|
|
||||||
# One need per set: a member another one fills is not a gap, and a set
|
def settle(self) -> None:
|
||||||
# nobody holds is one gap under its first member (alternatives.py), as
|
# One need per set: a member another one fills is not a gap, and a set
|
||||||
# verify and the packs count it.
|
# nobody holds is one gap under its first member (alternatives.py), as
|
||||||
# Archive units rank first among equals, as the builder orders them.
|
# verify and the packs count it.
|
||||||
grouped = sorted(
|
# Archive units rank first among equals, as the builder orders them.
|
||||||
(r for r in set_records if r[0]), key=lambda r: r[3] is not archive_rows
|
grouped = sorted(
|
||||||
)
|
(r for r in self.set_records if r[0]), key=lambda r: r[3] is not self.archive_rows
|
||||||
requirements = set_requirements(profile)
|
)
|
||||||
excused, standing = settle_sets(
|
requirements = set_requirements(self.profile)
|
||||||
[(keys, f, fills) for keys, f, fills, _l, _r in grouped],
|
excused, standing = settle_sets(
|
||||||
lambda key: requirements.get(key[1], True),
|
[(keys, f, fills) for keys, f, fills, _l, _r in grouped],
|
||||||
)
|
lambda key: requirements.get(key[1], True),
|
||||||
for at, (_keys, member, _fills, rows, set_row) in enumerate(grouped):
|
)
|
||||||
if set_row is None or rows is None:
|
for at, (_keys, member, _fills, rows, set_row) in enumerate(grouped):
|
||||||
continue
|
if set_row is None or rows is None:
|
||||||
if at in standing:
|
continue
|
||||||
set_row["alternatives"] = standing[at].others
|
if at in standing:
|
||||||
set_row["required"] = standing[at].required
|
set_row["alternatives"] = standing[at].others
|
||||||
if at in excused:
|
set_row["required"] = standing[at].required
|
||||||
rows.remove(set_row)
|
if at in excused:
|
||||||
if id(member) in position:
|
rows.remove(set_row)
|
||||||
fates[position[id(member)]] = "other_versions"
|
if id(member) in self.position:
|
||||||
|
self.fates[self.position[id(member)]] = "other_versions"
|
||||||
|
|
||||||
for ag in sorted(archive_gaps.values(), key=lambda e: e["name"]):
|
for ag in sorted(self.archive_gaps.values(), key=lambda e: e["name"]):
|
||||||
if any(ag is row for row in archive_rows):
|
if any(ag is row for row in self.archive_rows):
|
||||||
gaps.append(ag)
|
self.gaps.append(ag)
|
||||||
|
|
||||||
tally = Counter(fates.values())
|
def summary(self) -> dict:
|
||||||
report[emu_name] = {
|
tally = Counter(self.fates.values())
|
||||||
"emulator": profile.get("emulator", emu_name),
|
profile = self.profile
|
||||||
"systems": systems,
|
return {
|
||||||
"total_files": len(emu_files),
|
"emulator": profile.get("emulator", self.emu_name),
|
||||||
"platform_covered": len(covered),
|
"systems": profile.get("systems", []),
|
||||||
**_gap_counts(gaps),
|
"total_files": len(profile.get("files", [])),
|
||||||
"gap_details": gaps,
|
"platform_covered": len(self.covered),
|
||||||
"unsourceable": unsourceable_list,
|
**_gap_counts(self.gaps),
|
||||||
# Entries, not rows: an archive's members are one gap row.
|
"gap_details": self.gaps,
|
||||||
"declared_files": tally["declared"],
|
"unsourceable": self.unsourceable_list,
|
||||||
"undeclared_files": tally["undeclared"],
|
# Entries, not rows: an archive's members are one gap row.
|
||||||
"unsourceable_files": tally["unsourceable"],
|
"declared_files": tally["declared"],
|
||||||
"set_aside": {key: tally[key] for key in SET_ASIDE},
|
"undeclared_files": tally["undeclared"],
|
||||||
|
"unsourceable_files": tally["unsourceable"],
|
||||||
|
"set_aside": {key: tally[key] for key in SET_ASIDE},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _cross_reference_profile(
|
||||||
|
emu_name: str,
|
||||||
|
profile: dict,
|
||||||
|
declared: dict[str, set[str]],
|
||||||
|
report: dict,
|
||||||
|
index: dict,
|
||||||
|
standalone_cores: set[str] | None = None,
|
||||||
|
platform: str = "",
|
||||||
|
) -> None:
|
||||||
|
"""Compare one emulator profile against what the platforms declare.
|
||||||
|
|
||||||
|
*platform* is the platform key under --platform, empty for the whole
|
||||||
|
tree. It decides, through the functions verify reads, which entries the
|
||||||
|
platform's launcher never opens and which ones its emulator package
|
||||||
|
already installs.
|
||||||
|
|
||||||
|
Split out of cross_reference, where it was a 200-line loop body that
|
||||||
|
carried the whole function's branching: every file is resolved by name,
|
||||||
|
by path, by hash and by archive membership before it can be called a
|
||||||
|
gap. *index* carries the database lookups those steps share.
|
||||||
|
"""
|
||||||
|
all_declared = index["all_declared"]
|
||||||
|
systems = profile.get("systems", [])
|
||||||
|
|
||||||
|
# Skip filename-agnostic profiles (BIOS detected without fixed names)
|
||||||
|
if profile.get("bios_mode") == "agnostic":
|
||||||
|
return
|
||||||
|
|
||||||
|
if all_declared is not None:
|
||||||
|
platform_names = all_declared
|
||||||
|
else:
|
||||||
|
platform_names = set()
|
||||||
|
for sys_id in systems:
|
||||||
|
platform_names.update(declared.get(_norm_system_id(sys_id), set()))
|
||||||
|
|
||||||
|
# The build a platform runs decides which entries it reads, as in
|
||||||
|
# find_undeclared_files: without a platform, the libretro build.
|
||||||
|
layouts = platform_layouts(emu_name, profile, standalone_cores or set())
|
||||||
|
comparison = _ProfileComparison(emu_name, profile, index, platform_names, platform, layouts)
|
||||||
|
# Each file under each layout the platform gives the emulator: both, for
|
||||||
|
# one it launches as a libretro core and standalone.
|
||||||
|
layout_files = [(f, standalone) for view, standalone in layouts for f in view.get("files", [])]
|
||||||
|
|
||||||
|
# The entries of one profile on one slot are the versions its code
|
||||||
|
# accepts there (raze's ten DUKE3D.GRP): holding any of them fills the
|
||||||
|
# slot, as verify --emulator credits it.
|
||||||
|
for f, is_standalone in layout_files:
|
||||||
|
comparison.versions.setdefault(slot_key(f, is_standalone), []).append(f)
|
||||||
|
|
||||||
|
# What became of each entry, so the heading adds up: a file a platform
|
||||||
|
# declares, one it does not, or one set aside and why. An entry read by
|
||||||
|
# two builds keeps the first answer that compares it. Each layout lists
|
||||||
|
# the profile's entries in their order, so a position names one entry.
|
||||||
|
comparison.position = {
|
||||||
|
id(f): i for view, _ in layouts for i, f in enumerate(view.get("files", []))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for f, is_standalone in layout_files:
|
||||||
|
comparison.compare(f, is_standalone)
|
||||||
|
comparison.settle()
|
||||||
|
report[emu_name] = comparison.summary()
|
||||||
|
|
||||||
|
|
||||||
def _gap_counts(gaps: list[dict]) -> dict[str, int]:
|
def _gap_counts(gaps: list[dict]) -> dict[str, int]:
|
||||||
"""The per-source tallies of a profile's gap rows."""
|
"""The per-source tallies of a profile's gap rows."""
|
||||||
@@ -1208,6 +1250,76 @@ class _NameHolder:
|
|||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _held_by_setting(
|
||||||
|
name: str,
|
||||||
|
settings: dict,
|
||||||
|
readers: list[str],
|
||||||
|
profiles: dict[str, dict],
|
||||||
|
holder: _NameHolder,
|
||||||
|
db: dict,
|
||||||
|
) -> bool:
|
||||||
|
"""Whether the setting the name is written to reads a held file.
|
||||||
|
|
||||||
|
A placeholder read from the setting takes the held dump the
|
||||||
|
catalogues name after the model the launcher's name spells.
|
||||||
|
"""
|
||||||
|
entries = [
|
||||||
|
entry
|
||||||
|
for key in readers
|
||||||
|
for entry in profiles[key].get("files") or []
|
||||||
|
if settings[name] and set_by(entry, settings[name])
|
||||||
|
]
|
||||||
|
return any(holder._entry_held(entry) for entry in entries) or any(
|
||||||
|
"<" in str(entry.get("name", ""))
|
||||||
|
and any(
|
||||||
|
name_match_size_ok(entry, found.get("size"))
|
||||||
|
for found in catalogued_model_files(name, db)
|
||||||
|
)
|
||||||
|
for entry in entries
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _unsourceable_names(readers: list[str], profiles: dict[str, dict]) -> dict[str, str]:
|
||||||
|
return {
|
||||||
|
str(n).rsplit("/", 1)[-1]: str(entry["unsourceable"])
|
||||||
|
for key in readers
|
||||||
|
for entry in profiles[key].get("files") or []
|
||||||
|
if entry.get("unsourceable")
|
||||||
|
for n in (entry.get("name"), *(entry.get("aliases") or []))
|
||||||
|
if n
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _add_name_row(
|
||||||
|
by_key: dict[str, dict],
|
||||||
|
platform: str,
|
||||||
|
name: str,
|
||||||
|
found: tuple[str, bool] | None,
|
||||||
|
folds: bool,
|
||||||
|
reader: dict,
|
||||||
|
unsourceable: dict[str, str],
|
||||||
|
) -> None:
|
||||||
|
"""Add a launcher record to the row of a name the collection lacks."""
|
||||||
|
key = name.casefold() if folds else name
|
||||||
|
row = by_key.get(key)
|
||||||
|
if row is None:
|
||||||
|
row = by_key[key] = {
|
||||||
|
"platform": platform,
|
||||||
|
"name": name,
|
||||||
|
"emulators": [],
|
||||||
|
"readers": [],
|
||||||
|
}
|
||||||
|
if found:
|
||||||
|
row["held_as"] = found[0]
|
||||||
|
reason = unsourceable.get(name.rsplit("/", 1)[-1])
|
||||||
|
if reason and "unsourceable" not in row:
|
||||||
|
row["unsourceable"] = reason
|
||||||
|
if reader["emulator"] not in row["emulators"]:
|
||||||
|
row["emulators"].append(reader["emulator"])
|
||||||
|
if reader not in row["readers"]:
|
||||||
|
row["readers"].append(reader)
|
||||||
|
|
||||||
|
|
||||||
def launcher_reads_not_held(
|
def launcher_reads_not_held(
|
||||||
configs: dict[str, dict],
|
configs: dict[str, dict],
|
||||||
db: dict,
|
db: dict,
|
||||||
@@ -1265,29 +1377,10 @@ def launcher_reads_not_held(
|
|||||||
if str(record.get("search_dir") or "") in PLATFORM_OWN_FOLDERS:
|
if str(record.get("search_dir") or "") in PLATFORM_OWN_FOLDERS:
|
||||||
continue
|
continue
|
||||||
settings = name_settings(record, names)
|
settings = name_settings(record, names)
|
||||||
|
by_model = {
|
||||||
def by_setting(name: str) -> bool:
|
name for name in names
|
||||||
"""Whether the setting the name is written to reads a held file.
|
if _held_by_setting(name, settings, readers, profiles, holder, db)
|
||||||
|
}
|
||||||
A placeholder read from the setting takes the held dump the
|
|
||||||
catalogues name after the model the launcher's name spells.
|
|
||||||
"""
|
|
||||||
entries = [
|
|
||||||
entry
|
|
||||||
for key in readers
|
|
||||||
for entry in profiles[key].get("files") or []
|
|
||||||
if settings[name] and set_by(entry, settings[name])
|
|
||||||
]
|
|
||||||
return any(holder._entry_held(entry) for entry in entries) or any(
|
|
||||||
"<" in str(entry.get("name", ""))
|
|
||||||
and any(
|
|
||||||
name_match_size_ok(entry, found.get("size"))
|
|
||||||
for found in catalogued_model_files(name, db)
|
|
||||||
)
|
|
||||||
for entry in entries
|
|
||||||
)
|
|
||||||
|
|
||||||
by_model = {name for name in names if by_setting(name)}
|
|
||||||
if record.get("kind") == "names_searched" and any(
|
if record.get("kind") == "names_searched" and any(
|
||||||
(found := holder.held(name)) and (found[1] or folds) for name in names
|
(found := holder.held(name)) and (found[1] or folds) for name in names
|
||||||
):
|
):
|
||||||
@@ -1301,36 +1394,12 @@ def launcher_reads_not_held(
|
|||||||
}
|
}
|
||||||
# A name a reader's entry declares unsourceable is no gap: its
|
# A name a reader's entry declares unsourceable is no gap: its
|
||||||
# row carries the reason and is counted apart.
|
# row carries the reason and is counted apart.
|
||||||
unsourceable = {
|
unsourceable = _unsourceable_names(readers, profiles)
|
||||||
str(n).rsplit("/", 1)[-1]: str(entry["unsourceable"])
|
|
||||||
for key in readers
|
|
||||||
for entry in profiles[key].get("files") or []
|
|
||||||
if entry.get("unsourceable")
|
|
||||||
for n in (entry.get("name"), *(entry.get("aliases") or []))
|
|
||||||
if n
|
|
||||||
}
|
|
||||||
for name in names:
|
for name in names:
|
||||||
found = holder.held(name)
|
found = holder.held(name)
|
||||||
if found and (found[1] or folds) or name in by_model:
|
if found and (found[1] or folds) or name in by_model:
|
||||||
continue
|
continue
|
||||||
key = name.casefold() if folds else name
|
_add_name_row(by_key, platform, name, found, folds, reader, unsourceable)
|
||||||
row = by_key.get(key)
|
|
||||||
if row is None:
|
|
||||||
row = by_key[key] = {
|
|
||||||
"platform": platform,
|
|
||||||
"name": name,
|
|
||||||
"emulators": [],
|
|
||||||
"readers": [],
|
|
||||||
}
|
|
||||||
if found:
|
|
||||||
row["held_as"] = found[0]
|
|
||||||
reason = unsourceable.get(name.rsplit("/", 1)[-1])
|
|
||||||
if reason and "unsourceable" not in row:
|
|
||||||
row["unsourceable"] = reason
|
|
||||||
if reader["emulator"] not in row["emulators"]:
|
|
||||||
row["emulators"].append(reader["emulator"])
|
|
||||||
if reader not in row["readers"]:
|
|
||||||
row["readers"].append(reader)
|
|
||||||
rows.extend(by_key[key] for key in sorted(by_key, key=str.casefold))
|
rows.extend(by_key[key] for key in sorted(by_key, key=str.casefold))
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
@@ -1390,18 +1459,24 @@ def print_launcher_reads(rows: list[dict]) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ReportScope(TypedDict, total=False):
|
||||||
|
"""What a cross_reference run compares against and answers for."""
|
||||||
|
|
||||||
|
all_declared: dict[str, list[tuple[int | None, str]]] | None
|
||||||
|
standalone_cores: set[str] | None
|
||||||
|
folded_slots: frozenset[str]
|
||||||
|
platform: str
|
||||||
|
launcher_layer: LauncherLayer | None
|
||||||
|
declared_contents: dict[str, set[str]] | None
|
||||||
|
|
||||||
|
|
||||||
def cross_reference(
|
def cross_reference(
|
||||||
profiles: dict[str, dict],
|
profiles: dict[str, dict],
|
||||||
declared: dict[str, set[str]],
|
declared: dict[str, set[str]],
|
||||||
db: dict,
|
db: dict,
|
||||||
platform_data_dirs: dict[str, set[str]] | None = None,
|
platform_data_dirs: dict[str, set[str]] | None = None,
|
||||||
data_names: set[str] | None = None,
|
data_names: set[str] | None = None,
|
||||||
all_declared: dict[str, list[tuple[int | None, str]]] | None = None,
|
**scope: Unpack[ReportScope],
|
||||||
standalone_cores: set[str] | None = None,
|
|
||||||
folded_slots: frozenset[str] = frozenset(),
|
|
||||||
platform: str = "",
|
|
||||||
launcher_layer: LauncherLayer | None = None,
|
|
||||||
declared_contents: dict[str, set[str]] | None = None,
|
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Compare emulator profiles against platform declarations.
|
"""Compare emulator profiles against platform declarations.
|
||||||
|
|
||||||
@@ -1418,6 +1493,15 @@ def cross_reference(
|
|||||||
instead of the per-system lookup. This is appropriate for the global
|
instead of the per-system lookup. This is appropriate for the global
|
||||||
gap analysis page where "undeclared" means "no platform declares it at all".
|
gap analysis page where "undeclared" means "no platform declares it at all".
|
||||||
"""
|
"""
|
||||||
|
unknown = sorted(set(scope) - set(ReportScope.__annotations__))
|
||||||
|
if unknown:
|
||||||
|
raise TypeError(f"cross_reference() got an unexpected keyword argument '{unknown[0]}'")
|
||||||
|
all_declared = scope.get("all_declared")
|
||||||
|
standalone_cores = scope.get("standalone_cores")
|
||||||
|
folded_slots = scope.get("folded_slots", frozenset())
|
||||||
|
platform = scope.get("platform", "")
|
||||||
|
launcher_layer = scope.get("launcher_layer")
|
||||||
|
declared_contents = scope.get("declared_contents")
|
||||||
platform_data_dirs = platform_data_dirs or {}
|
platform_data_dirs = platform_data_dirs or {}
|
||||||
by_name = db.get("indexes", {}).get("by_name", {})
|
by_name = db.get("indexes", {}).get("by_name", {})
|
||||||
by_name_lower = {k.lower(): k for k in by_name}
|
by_name_lower = {k.lower(): k for k in by_name}
|
||||||
@@ -1426,7 +1510,7 @@ def cross_reference(
|
|||||||
by_sha256 = db.get("indexes", {}).get("by_sha256", {})
|
by_sha256 = db.get("indexes", {}).get("by_sha256", {})
|
||||||
by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {})
|
by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {})
|
||||||
db_files = db.get("files", {})
|
db_files = db.get("files", {})
|
||||||
report = {}
|
report: dict[str, dict] = {}
|
||||||
|
|
||||||
index = {
|
index = {
|
||||||
"by_name": by_name,
|
"by_name": by_name,
|
||||||
@@ -1474,7 +1558,7 @@ def print_report(
|
|||||||
# collection by design, as verify and the gaps page say: not a file to find.
|
# collection by design, as verify and the gaps page say: not a file to find.
|
||||||
bundled = 0
|
bundled = 0
|
||||||
|
|
||||||
for emu_name, data in sorted(report.items()):
|
for _emu_name, data in sorted(report.items()):
|
||||||
gaps = data["gaps"]
|
gaps = data["gaps"]
|
||||||
if gaps == 0 and not show_clean:
|
if gaps == 0 and not show_clean:
|
||||||
continue
|
continue
|
||||||
@@ -1528,7 +1612,7 @@ def print_report(
|
|||||||
print(f" {bundled} bundled with their emulator, not packed")
|
print(f" {bundled} bundled with their emulator, not packed")
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def _build_parser() -> argparse.ArgumentParser:
|
||||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Emulator vs platform gap analysis")
|
parser = argparse.ArgumentParser(allow_abbrev=False, description="Emulator vs platform gap analysis")
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--emulators-dir", default=DEFAULT_EMULATORS_DIR,
|
"--emulators-dir", default=DEFAULT_EMULATORS_DIR,
|
||||||
@@ -1551,6 +1635,87 @@ def main() -> None:
|
|||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--list-emulators", action="store_true", help="List available emulators"
|
"--list-emulators", action="store_true", help="List available emulators"
|
||||||
)
|
)
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class _PlatformScope:
|
||||||
|
"""The profiles a --platform run compares, and how the platform runs them."""
|
||||||
|
|
||||||
|
profiles: dict[str, dict]
|
||||||
|
standalone_cores: set[str]
|
||||||
|
config: dict
|
||||||
|
relevant: set[str]
|
||||||
|
run_anywhere: set[str]
|
||||||
|
|
||||||
|
|
||||||
|
def _platform_scope(
|
||||||
|
args: argparse.Namespace, parser: argparse.ArgumentParser, profiles: dict[str, dict],
|
||||||
|
) -> _PlatformScope:
|
||||||
|
from common import load_target_config, resolve_platform_cores
|
||||||
|
|
||||||
|
try:
|
||||||
|
target_cores = (
|
||||||
|
load_target_config(args.platform, args.target, args.platforms_dir)
|
||||||
|
if args.target
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
except (FileNotFoundError, ValueError) as exc:
|
||||||
|
# A typo ended in a traceback where verify and slots name the
|
||||||
|
# closest target.
|
||||||
|
parser.error(str(exc))
|
||||||
|
config = load_platform_config(args.platform, args.platforms_dir)
|
||||||
|
relevant = resolve_platform_cores(config, profiles, target_cores=target_cores)
|
||||||
|
run_anywhere = (
|
||||||
|
set(resolve_platform_cores(config, profiles)) if args.target else relevant
|
||||||
|
)
|
||||||
|
return _PlatformScope(
|
||||||
|
{k: v for k, v in profiles.items() if k in relevant},
|
||||||
|
standalone_set(config),
|
||||||
|
config,
|
||||||
|
relevant,
|
||||||
|
run_anywhere,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _launcher_rows(
|
||||||
|
args: argparse.Namespace,
|
||||||
|
selected: list[str] | None,
|
||||||
|
db: dict,
|
||||||
|
all_profiles: dict[str, dict],
|
||||||
|
registry: dict,
|
||||||
|
emulator: str | None,
|
||||||
|
) -> tuple[list[dict], list[dict]]:
|
||||||
|
"""The names a launcher reads that the collection lacks, and the
|
||||||
|
launcher records nothing proves."""
|
||||||
|
# Counted apart from the profile gaps: a name only a launcher reads is
|
||||||
|
# reported, not yet judged.
|
||||||
|
launcher_reads = launcher_reads_not_held(
|
||||||
|
{
|
||||||
|
name: load_platform_config(name, args.platforms_dir)
|
||||||
|
for name in (selected or list_registered_platforms(args.platforms_dir))
|
||||||
|
},
|
||||||
|
db, all_profiles, registry, emulator or "",
|
||||||
|
)
|
||||||
|
|
||||||
|
unproven = [
|
||||||
|
row for row in launcher_unproven(
|
||||||
|
{
|
||||||
|
name: load_platform_config(name, args.platforms_dir)
|
||||||
|
for name in (selected or list_registered_platforms(args.platforms_dir))
|
||||||
|
},
|
||||||
|
all_profiles,
|
||||||
|
)
|
||||||
|
if not emulator or any(
|
||||||
|
emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles))
|
||||||
|
for part in row["emulator"].split(", ")
|
||||||
|
)
|
||||||
|
]
|
||||||
|
return launcher_reads, unproven
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = _build_parser()
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
from common import work_from_repo_root
|
from common import work_from_repo_root
|
||||||
|
|
||||||
@@ -1595,32 +1760,17 @@ def main() -> None:
|
|||||||
if args.target and not args.platform:
|
if args.target and not args.platform:
|
||||||
parser.error("--target requires --platform")
|
parser.error("--target requires --platform")
|
||||||
|
|
||||||
|
platform_scope: _PlatformScope | None = None
|
||||||
standalone_cores: set[str] = set()
|
standalone_cores: set[str] = set()
|
||||||
if args.platform:
|
if args.platform:
|
||||||
from common import load_target_config, resolve_platform_cores
|
platform_scope = _platform_scope(args, parser, profiles)
|
||||||
|
profiles = platform_scope.profiles
|
||||||
try:
|
standalone_cores = platform_scope.standalone_cores
|
||||||
target_cores = (
|
|
||||||
load_target_config(args.platform, args.target, args.platforms_dir)
|
|
||||||
if args.target
|
|
||||||
else None
|
|
||||||
)
|
|
||||||
except (FileNotFoundError, ValueError) as exc:
|
|
||||||
# A typo ended in a traceback where verify and slots name the
|
|
||||||
# closest target.
|
|
||||||
parser.error(str(exc))
|
|
||||||
config = load_platform_config(args.platform, args.platforms_dir)
|
|
||||||
relevant = resolve_platform_cores(config, profiles, target_cores=target_cores)
|
|
||||||
run_anywhere = (
|
|
||||||
set(resolve_platform_cores(config, profiles)) if args.target else relevant
|
|
||||||
)
|
|
||||||
profiles = {k: v for k, v in profiles.items() if k in relevant}
|
|
||||||
standalone_cores = standalone_set(config)
|
|
||||||
else:
|
else:
|
||||||
# The tree as every platform runs it: a profile some platform runs
|
# The tree as every platform runs it: a profile some platform runs
|
||||||
# standalone keeps its standalone entries. Laid out as libretro only,
|
# standalone keeps its standalone entries. Laid out as libretro only,
|
||||||
# eka2l1, dolphin and xenia-edge lost 133 files no platform declares.
|
# eka2l1, dolphin and xenia-edge lost 133 files no platform declares.
|
||||||
from common import list_registered_platforms, merged_standalone_set
|
from common import merged_standalone_set
|
||||||
|
|
||||||
standalone_cores = merged_standalone_set(
|
standalone_cores = merged_standalone_set(
|
||||||
load_platform_config(name, args.platforms_dir)
|
load_platform_config(name, args.platforms_dir)
|
||||||
@@ -1628,7 +1778,8 @@ def main() -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
if not profiles:
|
if not profiles:
|
||||||
if emulator and args.target and emulator in run_anywhere:
|
if (emulator and args.target and platform_scope is not None
|
||||||
|
and emulator in platform_scope.run_anywhere):
|
||||||
raise SystemExit(
|
raise SystemExit(
|
||||||
f"ERROR: {emulator} is not built for {args.platform}'s "
|
f"ERROR: {emulator} is not built for {args.platform}'s "
|
||||||
f"{args.target} target; {args.platform} runs it elsewhere "
|
f"{args.target} target; {args.platform} runs it elsewhere "
|
||||||
@@ -1655,52 +1806,35 @@ def main() -> None:
|
|||||||
],
|
],
|
||||||
db,
|
db,
|
||||||
),
|
),
|
||||||
platform=config.get("_key", args.platform) if args.platform else "",
|
platform=(
|
||||||
|
platform_scope.config.get("_key", args.platform) if platform_scope else ""
|
||||||
|
),
|
||||||
# What the platform's launchers open, as verify and the builder read it.
|
# What the platform's launchers open, as verify and the builder read it.
|
||||||
launcher_layer=LauncherLayer(
|
launcher_layer=LauncherLayer(
|
||||||
config, profiles, relevant, db, declared_destinations(config)
|
platform_scope.config, profiles, platform_scope.relevant, db,
|
||||||
) if args.platform else None,
|
declared_destinations(platform_scope.config),
|
||||||
|
) if platform_scope else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Counted apart from the profile gaps: a name only a launcher reads is
|
launcher_reads, unproven = _launcher_rows(
|
||||||
# reported, not yet judged.
|
args, selected, db, all_profiles, registry, emulator,
|
||||||
launcher_reads = launcher_reads_not_held(
|
|
||||||
{
|
|
||||||
name: load_platform_config(name, args.platforms_dir)
|
|
||||||
for name in (selected or list_registered_platforms(args.platforms_dir))
|
|
||||||
},
|
|
||||||
db, all_profiles, registry, emulator or "",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
unproven = [
|
|
||||||
row for row in launcher_unproven(
|
|
||||||
{
|
|
||||||
name: load_platform_config(name, args.platforms_dir)
|
|
||||||
for name in (selected or list_registered_platforms(args.platforms_dir))
|
|
||||||
},
|
|
||||||
all_profiles,
|
|
||||||
)
|
|
||||||
if not emulator or any(
|
|
||||||
emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles))
|
|
||||||
for part in row["emulator"].split(", ")
|
|
||||||
)
|
|
||||||
]
|
|
||||||
|
|
||||||
if args.json:
|
if args.json:
|
||||||
print(json.dumps(
|
print(json.dumps(
|
||||||
{**report, LAUNCHER_READS_KEY: launcher_reads, LAUNCHER_UNPROVEN_KEY: unproven},
|
{**report, LAUNCHER_READS_KEY: launcher_reads, LAUNCHER_UNPROVEN_KEY: unproven},
|
||||||
indent=2,
|
indent=2,
|
||||||
))
|
))
|
||||||
|
return
|
||||||
|
if emulator:
|
||||||
|
scope = emulator
|
||||||
|
elif args.platform:
|
||||||
|
scope = f"the emulators {args.platform} runs"
|
||||||
else:
|
else:
|
||||||
if emulator:
|
scope = "all emulators"
|
||||||
scope = emulator
|
print_report(report, scope, show_clean=bool(args.emulator))
|
||||||
elif args.platform:
|
print_launcher_reads(launcher_reads)
|
||||||
scope = f"the emulators {args.platform} runs"
|
print_launcher_unproven(unproven)
|
||||||
else:
|
|
||||||
scope = "all emulators"
|
|
||||||
print_report(report, scope, show_clean=bool(args.emulator))
|
|
||||||
print_launcher_reads(launcher_reads)
|
|
||||||
print_launcher_unproven(unproven)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+81
-72
@@ -44,6 +44,50 @@ def _where(entry: dict) -> str:
|
|||||||
return entry.get("destination") or entry["name"]
|
return entry.get("destination") or entry["name"]
|
||||||
|
|
||||||
|
|
||||||
|
_TOTAL_LABELS = (
|
||||||
|
("total_missing", "missing"),
|
||||||
|
("total_extra_phantom", "unpaired"),
|
||||||
|
("total_extra_unprofiled", "unprofiled"),
|
||||||
|
("total_hash_mismatch", "hash"),
|
||||||
|
("total_required_mismatch", "required"),
|
||||||
|
)
|
||||||
|
|
||||||
|
_DIVERGENCE_LABELS = (
|
||||||
|
("missing", "MISSING"),
|
||||||
|
("extra_phantom", "UNPAIRED"),
|
||||||
|
("extra_unprofiled", "UNPROF"),
|
||||||
|
("hash_mismatch", "HASH"),
|
||||||
|
("required_mismatch", "REQ"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _terminal_divergence(sys_id: str, div: dict) -> list[str]:
|
||||||
|
labels = [f"{label}:{len(div[key])}" for key, label in _DIVERGENCE_LABELS if div.get(key)]
|
||||||
|
lines = [f" {sys_id}: {' '.join(labels)}"]
|
||||||
|
lines.extend(
|
||||||
|
f" + {_where(m)} [{', '.join(m.get('cores', []))}]"
|
||||||
|
for m in div.get("missing", [])
|
||||||
|
)
|
||||||
|
lines.extend(
|
||||||
|
f" ~ {_where(h)} {h['hash_type']}: "
|
||||||
|
f"{h['truth_' + h['hash_type']]} != {h['scraped_' + h['hash_type']]}"
|
||||||
|
for h in div.get("hash_mismatch", [])
|
||||||
|
)
|
||||||
|
lines.extend(
|
||||||
|
f" - {_where(p)} (no profile entry of this system matches it)"
|
||||||
|
for p in div.get("extra_phantom", [])
|
||||||
|
)
|
||||||
|
lines.extend(
|
||||||
|
f" ? {_where(u)} (unprofiled cores)"
|
||||||
|
for u in div.get("extra_unprofiled", [])
|
||||||
|
)
|
||||||
|
lines.extend(
|
||||||
|
f" ! {_where(r)} required: {r['truth_required']} != {r['scraped_required']}"
|
||||||
|
for r in div.get("required_mismatch", [])
|
||||||
|
)
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
def _format_terminal(report: dict) -> str:
|
def _format_terminal(report: dict) -> str:
|
||||||
lines: list[str] = []
|
lines: list[str] = []
|
||||||
platform = report.get("platform", "unknown")
|
platform = report.get("platform", "unknown")
|
||||||
@@ -57,52 +101,14 @@ def _format_terminal(report: dict) -> str:
|
|||||||
f"{s['systems_uncovered']} uncovered"
|
f"{s['systems_uncovered']} uncovered"
|
||||||
)
|
)
|
||||||
|
|
||||||
totals = []
|
totals = [f"{s[key]} {label}" for key, label in _TOTAL_LABELS if s[key]]
|
||||||
if s["total_missing"]:
|
|
||||||
totals.append(f"{s['total_missing']} missing")
|
|
||||||
if s["total_extra_phantom"]:
|
|
||||||
totals.append(f"{s['total_extra_phantom']} unpaired")
|
|
||||||
if s["total_extra_unprofiled"]:
|
|
||||||
totals.append(f"{s['total_extra_unprofiled']} unprofiled")
|
|
||||||
if s["total_hash_mismatch"]:
|
|
||||||
totals.append(f"{s['total_hash_mismatch']} hash")
|
|
||||||
if s["total_required_mismatch"]:
|
|
||||||
totals.append(f"{s['total_required_mismatch']} required")
|
|
||||||
if totals:
|
if totals:
|
||||||
lines.append(f" divergences: {', '.join(totals)}")
|
lines.append(f" divergences: {', '.join(totals)}")
|
||||||
else:
|
else:
|
||||||
lines.append(" no divergences")
|
lines.append(" no divergences")
|
||||||
|
|
||||||
for sys_id, div in sorted(report.get("divergences", {}).items()):
|
for sys_id, div in sorted(report.get("divergences", {}).items()):
|
||||||
labels: list[str] = []
|
lines.extend(_terminal_divergence(sys_id, div))
|
||||||
if div.get("missing"):
|
|
||||||
labels.append(f"MISSING:{len(div['missing'])}")
|
|
||||||
if div.get("extra_phantom"):
|
|
||||||
labels.append(f"UNPAIRED:{len(div['extra_phantom'])}")
|
|
||||||
if div.get("extra_unprofiled"):
|
|
||||||
labels.append(f"UNPROF:{len(div['extra_unprofiled'])}")
|
|
||||||
if div.get("hash_mismatch"):
|
|
||||||
labels.append(f"HASH:{len(div['hash_mismatch'])}")
|
|
||||||
if div.get("required_mismatch"):
|
|
||||||
labels.append(f"REQ:{len(div['required_mismatch'])}")
|
|
||||||
lines.append(f" {sys_id}: {' '.join(labels)}")
|
|
||||||
|
|
||||||
for m in div.get("missing", []):
|
|
||||||
cores = ", ".join(m.get("cores", []))
|
|
||||||
lines.append(f" + {_where(m)} [{cores}]")
|
|
||||||
for h in div.get("hash_mismatch", []):
|
|
||||||
ht = h["hash_type"]
|
|
||||||
lines.append(
|
|
||||||
f" ~ {_where(h)} {ht}: {h[f'truth_{ht}']} != {h[f'scraped_{ht}']}"
|
|
||||||
)
|
|
||||||
for p in div.get("extra_phantom", []):
|
|
||||||
lines.append(f" - {_where(p)} (no profile entry of this system matches it)")
|
|
||||||
for u in div.get("extra_unprofiled", []):
|
|
||||||
lines.append(f" ? {_where(u)} (unprofiled cores)")
|
|
||||||
for r in div.get("required_mismatch", []):
|
|
||||||
lines.append(
|
|
||||||
f" ! {_where(r)} required: {r['truth_required']} != {r['scraped_required']}"
|
|
||||||
)
|
|
||||||
|
|
||||||
uncovered = report.get("uncovered_systems", [])
|
uncovered = report.get("uncovered_systems", [])
|
||||||
if uncovered:
|
if uncovered:
|
||||||
@@ -111,6 +117,39 @@ def _format_terminal(report: dict) -> str:
|
|||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _markdown_divergence(sys_id: str, div: dict) -> list[str]:
|
||||||
|
lines = [f"## {sys_id}", ""]
|
||||||
|
for m in div.get("missing", []):
|
||||||
|
refs = ""
|
||||||
|
if m.get("source_refs"):
|
||||||
|
refs = " " + " ".join(f"`{r}`" for r in m["source_refs"])
|
||||||
|
lines.append(f"- **Add** `{_where(m)}`{refs}")
|
||||||
|
lines.extend(
|
||||||
|
f"- **Fix hash** `{_where(h)}` {h['hash_type']}: "
|
||||||
|
f"`{h['truth_' + h['hash_type']]}` != `{h['scraped_' + h['hash_type']]}`"
|
||||||
|
for h in div.get("hash_mismatch", [])
|
||||||
|
)
|
||||||
|
# Evidence, not a request: an entry leaves a platform's file only on
|
||||||
|
# proof (export_native's removal_candidates). A core can read a
|
||||||
|
# file its profile does not pair with this declaration.
|
||||||
|
lines.extend(
|
||||||
|
f"- **Unpaired** `{_where(p)}`: no profile entry of this system matches it "
|
||||||
|
"by path, name or hash"
|
||||||
|
for p in div.get("extra_phantom", [])
|
||||||
|
)
|
||||||
|
lines.extend(
|
||||||
|
f"- **Unpaired** `{_where(u)}`: some cores of this platform "
|
||||||
|
"have no profile yet"
|
||||||
|
for u in div.get("extra_unprofiled", [])
|
||||||
|
)
|
||||||
|
lines.extend(
|
||||||
|
f"- **Fix required** `{_where(r)}`: truth={r['truth_required']}, scraped={r['scraped_required']}"
|
||||||
|
for r in div.get("required_mismatch", [])
|
||||||
|
)
|
||||||
|
lines.append("")
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
def _format_markdown(report: dict) -> str:
|
def _format_markdown(report: dict) -> str:
|
||||||
lines: list[str] = []
|
lines: list[str] = []
|
||||||
platform = report.get("platform", "unknown")
|
platform = report.get("platform", "unknown")
|
||||||
@@ -134,43 +173,13 @@ def _format_markdown(report: dict) -> str:
|
|||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
for sys_id, div in sorted(report.get("divergences", {}).items()):
|
for sys_id, div in sorted(report.get("divergences", {}).items()):
|
||||||
lines.append(f"## {sys_id}")
|
lines.extend(_markdown_divergence(sys_id, div))
|
||||||
lines.append("")
|
|
||||||
for m in div.get("missing", []):
|
|
||||||
refs = ""
|
|
||||||
if m.get("source_refs"):
|
|
||||||
refs = " " + " ".join(f"`{r}`" for r in m["source_refs"])
|
|
||||||
lines.append(f"- **Add** `{_where(m)}`{refs}")
|
|
||||||
for h in div.get("hash_mismatch", []):
|
|
||||||
ht = h["hash_type"]
|
|
||||||
lines.append(
|
|
||||||
f"- **Fix hash** `{_where(h)}` {ht}: `{h[f'truth_{ht}']}` != `{h[f'scraped_{ht}']}`"
|
|
||||||
)
|
|
||||||
# Evidence, not a request: an entry leaves a platform's file only on
|
|
||||||
# proof (export_native's removal_candidates). A core can read a
|
|
||||||
# file its profile does not pair with this declaration.
|
|
||||||
for p in div.get("extra_phantom", []):
|
|
||||||
lines.append(
|
|
||||||
f"- **Unpaired** `{_where(p)}`: no profile entry of this system matches it "
|
|
||||||
"by path, name or hash"
|
|
||||||
)
|
|
||||||
for u in div.get("extra_unprofiled", []):
|
|
||||||
lines.append(
|
|
||||||
f"- **Unpaired** `{_where(u)}`: some cores of this platform "
|
|
||||||
"have no profile yet"
|
|
||||||
)
|
|
||||||
for r in div.get("required_mismatch", []):
|
|
||||||
lines.append(
|
|
||||||
f"- **Fix required** `{_where(r)}`: truth={r['truth_required']}, scraped={r['scraped_required']}"
|
|
||||||
)
|
|
||||||
lines.append("")
|
|
||||||
|
|
||||||
uncovered = report.get("uncovered_systems", [])
|
uncovered = report.get("uncovered_systems", [])
|
||||||
if uncovered:
|
if uncovered:
|
||||||
lines.append("## Uncovered systems")
|
lines.append("## Uncovered systems")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
for u in uncovered:
|
lines.extend(f"- {u}" for u in uncovered)
|
||||||
lines.append(f"- {u}")
|
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|||||||
+173
-119
@@ -50,7 +50,15 @@ from common import (
|
|||||||
yaml_load,
|
yaml_load,
|
||||||
)
|
)
|
||||||
from exporter import discover_exporters
|
from exporter import discover_exporters
|
||||||
from exporter.baseline import HASH_FIELDS, _hash_values, _single_size, build_native_model
|
from exporter.base_exporter import BaseExporter
|
||||||
|
from exporter.baseline import (
|
||||||
|
HASH_FIELDS,
|
||||||
|
NativeFile,
|
||||||
|
Report,
|
||||||
|
_hash_values,
|
||||||
|
_single_size,
|
||||||
|
build_native_model,
|
||||||
|
)
|
||||||
from exporter.candidates import removal_candidates
|
from exporter.candidates import removal_candidates
|
||||||
from exporter.doubled import doubled_destinations
|
from exporter.doubled import doubled_destinations
|
||||||
from truth import generate_platform_truth
|
from truth import generate_platform_truth
|
||||||
@@ -252,14 +260,15 @@ def _raw_url(url: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def wanted_sources(
|
def wanted_sources(
|
||||||
exporter: object, systems: dict, scraped: dict | None = None
|
exporter: BaseExporter, systems: dict, scraped: dict | None = None
|
||||||
) -> dict[str, str]:
|
) -> dict[str, str]:
|
||||||
"""Cache-relative name -> URL of every file the exporter patches."""
|
"""Cache-relative name -> URL of every file the exporter patches."""
|
||||||
wanted = dict(exporter.native_sources())
|
wanted = dict(exporter.native_sources())
|
||||||
components = getattr(exporter, "components", None)
|
components = getattr(exporter, "components", None)
|
||||||
if callable(components):
|
component_url = getattr(exporter, "component_url", None)
|
||||||
|
if callable(components) and callable(component_url):
|
||||||
for component in components(systems):
|
for component in components(systems):
|
||||||
wanted[f"{component}/component_manifest.json"] = exporter.component_url(
|
wanted[f"{component}/component_manifest.json"] = component_url(
|
||||||
component
|
component
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -343,7 +352,7 @@ def _at_revision(url: str, base: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def collect_originals(
|
def collect_originals(
|
||||||
exporter: object,
|
exporter: BaseExporter,
|
||||||
systems: dict,
|
systems: dict,
|
||||||
upstream_dir: Path,
|
upstream_dir: Path,
|
||||||
allow_fetch: bool,
|
allow_fetch: bool,
|
||||||
@@ -364,8 +373,12 @@ def collect_originals(
|
|||||||
unpack = getattr(exporter, "unpack", None)
|
unpack = getattr(exporter, "unpack", None)
|
||||||
for relative, url in wanted.items():
|
for relative, url in wanted.items():
|
||||||
path = root / relative
|
path = root / relative
|
||||||
archive = callable(unpack) and relative.endswith((".zip", ".tar.gz"))
|
reader: Callable[[bytes], dict[str, str]] | None = (
|
||||||
check = (lambda raw: _read_archive(unpack, raw)) if archive else _read_text
|
unpack if callable(unpack) and relative.endswith((".zip", ".tar.gz")) else None
|
||||||
|
)
|
||||||
|
check: Callable[[bytes], object] = (
|
||||||
|
functools.partial(_read_archive, reader) if reader is not None else _read_text
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
if allow_fetch:
|
if allow_fetch:
|
||||||
payload = fetch(url, path, index, refresh, check)
|
payload = fetch(url, path, index, refresh, check)
|
||||||
@@ -376,8 +389,8 @@ def collect_originals(
|
|||||||
f"{relative}: not in {root}; rerun with --fetch to download it"
|
f"{relative}: not in {root}; rerun with --fetch to download it"
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
if archive:
|
if reader is not None:
|
||||||
originals.update(_read_archive(unpack, payload))
|
originals.update(_read_archive(reader, payload))
|
||||||
keep = getattr(exporter, "keep_archive", None)
|
keep = getattr(exporter, "keep_archive", None)
|
||||||
if callable(keep):
|
if callable(keep):
|
||||||
keep(relative, payload)
|
keep(relative, payload)
|
||||||
@@ -459,7 +472,7 @@ def refresh_cache(
|
|||||||
except StaleTruth as exc:
|
except StaleTruth as exc:
|
||||||
return False, [str(exc)]
|
return False, [str(exc)]
|
||||||
systems, _ = build_native_model(truth or {}, scraped)
|
systems, _ = build_native_model(truth or {}, scraped)
|
||||||
exporter = exporter_class()
|
exporter: BaseExporter = exporter_class()
|
||||||
wanted = wanted_sources(exporter, systems, scraped)
|
wanted = wanted_sources(exporter, systems, scraped)
|
||||||
off_pin = unpinned(wanted, scraped)
|
off_pin = unpinned(wanted, scraped)
|
||||||
if off_pin:
|
if off_pin:
|
||||||
@@ -548,7 +561,7 @@ class LandedChanges:
|
|||||||
|
|
||||||
|
|
||||||
def _change(
|
def _change(
|
||||||
kind: str, entry: object, field_name: str | None, old: object, new: object
|
kind: str, entry: NativeFile, field_name: str | None, old: object, new: object
|
||||||
) -> dict:
|
) -> dict:
|
||||||
return {
|
return {
|
||||||
"kind": kind,
|
"kind": kind,
|
||||||
@@ -561,21 +574,21 @@ def _change(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _platform_value(entry: object, field_name: str) -> str | list[str]:
|
def _platform_value(entry: NativeFile, field_name: str) -> str | list[str]:
|
||||||
values = _hash_values(entry.platform or {}, field_name)
|
values = _hash_values(entry.platform or {}, field_name)
|
||||||
if (entry.platform or {}).get(f"{field_name}_list"):
|
if (entry.platform or {}).get(f"{field_name}_list"):
|
||||||
return values
|
return values
|
||||||
return ",".join(values)
|
return ",".join(values)
|
||||||
|
|
||||||
|
|
||||||
def _written_value(exporter: object, entry: object, field_name: str) -> str | list[str]:
|
def _written_value(exporter: BaseExporter, entry: NativeFile, field_name: str) -> str | list[str]:
|
||||||
"""A hash field as the render writes it: a list where the checker reads
|
"""A hash field as the render writes it: a list where the checker reads
|
||||||
one, so the report never shows several values as one."""
|
one, so the report never shows several values as one."""
|
||||||
listed = exporter.written_list(entry, field_name)
|
listed = exporter.written_list(entry, field_name)
|
||||||
return listed if listed is not None else exporter.written(entry, field_name)
|
return listed if listed is not None else exporter.written(entry, field_name)
|
||||||
|
|
||||||
|
|
||||||
def _added_fields(exporter: object, entry: object) -> dict:
|
def _added_fields(exporter: BaseExporter, entry: NativeFile) -> dict:
|
||||||
"""The fields an addition is written with, as the render chooses them."""
|
"""The fields an addition is written with, as the render chooses them."""
|
||||||
carried = exporter.carries()
|
carried = exporter.carries()
|
||||||
written: dict[str, object] = {
|
written: dict[str, object] = {
|
||||||
@@ -590,7 +603,7 @@ def _added_fields(exporter: object, entry: object) -> dict:
|
|||||||
return written
|
return written
|
||||||
|
|
||||||
|
|
||||||
def landed_changes(exporter: object, systems: dict) -> LandedChanges:
|
def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges:
|
||||||
"""The changes the written file carries, with their values.
|
"""The changes the written file carries, with their values.
|
||||||
|
|
||||||
Only what the format states: a correction to a field the file has no
|
Only what the format states: a correction to a field the file has no
|
||||||
@@ -706,8 +719,6 @@ def export_platform(
|
|||||||
allow_fetch: bool,
|
allow_fetch: bool,
|
||||||
) -> tuple[bool, list[str]]:
|
) -> tuple[bool, list[str]]:
|
||||||
"""Write one platform's corrected file. Returns (ok, messages)."""
|
"""Write one platform's corrected file. Returns (ok, messages)."""
|
||||||
messages: list[str] = []
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
truth, scraped = load_inputs(platform, truth_dir, platforms_dir)
|
truth, scraped = load_inputs(platform, truth_dir, platforms_dir)
|
||||||
except StaleTruth as exc:
|
except StaleTruth as exc:
|
||||||
@@ -724,34 +735,12 @@ def export_platform(
|
|||||||
if not systems:
|
if not systems:
|
||||||
return False, ["nothing to write: neither the platform nor the truth has data"]
|
return False, ["nothing to write: neither the platform nor the truth has data"]
|
||||||
|
|
||||||
exporter = exporter_class()
|
exporter: BaseExporter = exporter_class()
|
||||||
off_pin = unpinned(wanted_sources(exporter, systems, scraped), scraped)
|
produced, issues, stopped = _produce(
|
||||||
if off_pin:
|
exporter, systems, report, scraped, upstream_dir, allow_fetch,
|
||||||
return False, off_pin
|
|
||||||
originals, missing = collect_originals(
|
|
||||||
exporter, systems, upstream_dir, allow_fetch, scraped
|
|
||||||
)
|
)
|
||||||
if missing:
|
if stopped:
|
||||||
return False, [f"the platform's own file is required: {m}" for m in missing]
|
return False, stopped
|
||||||
if exporter.needs_original() and not originals:
|
|
||||||
return False, ["the platform's own file is required and none was read"]
|
|
||||||
|
|
||||||
try:
|
|
||||||
produced = exporter.render(systems, report, originals, scraped)
|
|
||||||
except ValueError as exc:
|
|
||||||
return False, [str(exc)]
|
|
||||||
|
|
||||||
if not produced and not exporter.may_write_nothing():
|
|
||||||
return False, ["the exporter produced no file"]
|
|
||||||
|
|
||||||
issues = exporter.validate(systems, produced)
|
|
||||||
if issues:
|
|
||||||
# Written first, a file its own validator refused replaced the
|
|
||||||
# published export and only the exit code said so.
|
|
||||||
invalid = [f"INVALID: {issue}" for issue in issues[:10]]
|
|
||||||
if len(issues) > 10:
|
|
||||||
invalid.append(f"and {len(issues) - 10} more validation failures")
|
|
||||||
return False, invalid
|
|
||||||
|
|
||||||
platform_dir = output_dir / platform
|
platform_dir = output_dir / platform
|
||||||
_remove_stale(platform_dir, set(produced))
|
_remove_stale(platform_dir, set(produced))
|
||||||
@@ -762,61 +751,15 @@ def export_platform(
|
|||||||
resized, cleared = changes.resized, changes.cleared
|
resized, cleared = changes.resized, changes.cleared
|
||||||
unsized = changes.unsized
|
unsized = changes.unsized
|
||||||
requirements = changes.requirements
|
requirements = changes.requirements
|
||||||
lists = changes.lists
|
|
||||||
|
|
||||||
landed = 0
|
landed, refused, lost = _entry_outcomes(exporter, systems)
|
||||||
refused = 0
|
|
||||||
lost = 0
|
|
||||||
for system in systems.values():
|
|
||||||
for entry in system.files:
|
|
||||||
if not entry.name:
|
|
||||||
continue
|
|
||||||
if exporter.lands(entry):
|
|
||||||
landed += entry.platform is None
|
|
||||||
elif entry.platform is None:
|
|
||||||
refused += 1
|
|
||||||
else:
|
|
||||||
# The platform declares it and the format still cannot state
|
|
||||||
# it, so their own file loses a line. Worth saying out loud.
|
|
||||||
lost += 1
|
|
||||||
|
|
||||||
own_summary = exporter.outcome(systems, produced)
|
own_summary = exporter.outcome(systems, produced)
|
||||||
summary = own_summary
|
summary = own_summary
|
||||||
if summary is None:
|
if summary is None:
|
||||||
# What the written file carries, in the terms the exports page uses.
|
summary = _landed_summary(report, changes, landed, lost)
|
||||||
# What it does not carry is counted on a line of its own below.
|
|
||||||
parts = [f"{report.files_kept} kept"]
|
|
||||||
landed_counts = (
|
|
||||||
(landed, "file", "", "added"),
|
|
||||||
(len(applied), "hash", "", "updated to the emulator source"),
|
|
||||||
(requirements, "required flag", "", "aligned with the code"),
|
|
||||||
(len(filled), "hash", "", "added to an existing entry"),
|
|
||||||
(len(resized), "size", "", "updated to the emulator source"),
|
|
||||||
(len(unsized), "size", "", "removed"),
|
|
||||||
(len(cleared), "hash", "", "removed"),
|
|
||||||
(lost, "entry", "entries", "removed, the format cannot state them"),
|
|
||||||
(lists, "md5 list", "", "written, any listed value passes"),
|
|
||||||
)
|
|
||||||
parts += [
|
|
||||||
f"{_count(number, noun, plural)} {verb}"
|
|
||||||
for number, noun, plural, verb in landed_counts
|
|
||||||
if number
|
|
||||||
]
|
|
||||||
summary = ", ".join(parts)
|
|
||||||
withheld = exporter.withheld()
|
withheld = exporter.withheld()
|
||||||
unwritten = [
|
unwritten = _unwritten(refused, withheld, report)
|
||||||
f"{_count(number, noun, plural)} {what}"
|
|
||||||
for number, noun, plural, what in (
|
|
||||||
(refused, "file", "", "the format or its checker cannot carry"),
|
|
||||||
(len(withheld), "update", "", "withheld"),
|
|
||||||
# A content-scanning core's names are labels: a list checked
|
|
||||||
# by path cannot hold them.
|
|
||||||
(report.labels, "entry", "entries", "found by content"),
|
|
||||||
(len(report.unattributed), "file", "",
|
|
||||||
"no single native system of the platform takes"),
|
|
||||||
)
|
|
||||||
if number
|
|
||||||
]
|
|
||||||
# Reported, never removed: the platform's file keeps every entry.
|
# Reported, never removed: the platform's file keeps every entry.
|
||||||
candidates = removal_candidates(
|
candidates = removal_candidates(
|
||||||
systems, scraped, load_emulator_profiles("emulators"),
|
systems, scraped, load_emulator_profiles("emulators"),
|
||||||
@@ -824,32 +767,7 @@ def export_platform(
|
|||||||
)
|
)
|
||||||
# Reported, never rewritten: both declarations stay as the platform wrote them.
|
# Reported, never rewritten: both declarations stay as the platform wrote them.
|
||||||
doubled = doubled_in(scraped, platforms_dir)
|
doubled = doubled_in(scraped, platforms_dir)
|
||||||
messages.append(summary)
|
messages = _export_messages(summary, unwritten, candidates, doubled, withheld, changes)
|
||||||
if unwritten:
|
|
||||||
messages.append("not in the file: " + ", ".join(unwritten))
|
|
||||||
if candidates:
|
|
||||||
open_question = sum(c["verdict"] == "undetermined" for c in candidates)
|
|
||||||
messages.append(
|
|
||||||
f"{_count(len(candidates), 'entry', 'entries')} no examined core is known to open"
|
|
||||||
+ (f" ({open_question} undetermined)" if open_question else "")
|
|
||||||
+ ", listed in the report"
|
|
||||||
)
|
|
||||||
if doubled:
|
|
||||||
messages.append(
|
|
||||||
f"{_count(len(doubled), 'destination')} declared twice for two files"
|
|
||||||
", listed in the report"
|
|
||||||
)
|
|
||||||
messages.extend(f"withheld: {reason}" for reason in withheld)
|
|
||||||
for heading, labels in (
|
|
||||||
("hash updated", applied),
|
|
||||||
("hash added", filled),
|
|
||||||
("size updated", resized),
|
|
||||||
("size removed", unsized),
|
|
||||||
("hash removed", cleared),
|
|
||||||
):
|
|
||||||
messages.extend(f"{heading}: {label}" for label in labels[:5])
|
|
||||||
if len(labels) > 5:
|
|
||||||
messages.append(f"and {len(labels) - 5} more")
|
|
||||||
|
|
||||||
write_report(output_dir / f"{platform}.json", {
|
write_report(output_dir / f"{platform}.json", {
|
||||||
"platform": platform,
|
"platform": platform,
|
||||||
@@ -879,6 +797,142 @@ def export_platform(
|
|||||||
return True, messages
|
return True, messages
|
||||||
|
|
||||||
|
|
||||||
|
def _produce(
|
||||||
|
exporter: BaseExporter,
|
||||||
|
systems: dict,
|
||||||
|
report: Report,
|
||||||
|
scraped: dict | None,
|
||||||
|
upstream_dir: Path,
|
||||||
|
allow_fetch: bool,
|
||||||
|
) -> tuple[dict, list[str], list[str]]:
|
||||||
|
"""The files the exporter renders, its validator's issues, and why the
|
||||||
|
export stops before writing (empty when it goes on)."""
|
||||||
|
off_pin = unpinned(wanted_sources(exporter, systems, scraped), scraped)
|
||||||
|
if off_pin:
|
||||||
|
return {}, [], off_pin
|
||||||
|
originals, missing = collect_originals(
|
||||||
|
exporter, systems, upstream_dir, allow_fetch, scraped
|
||||||
|
)
|
||||||
|
if missing:
|
||||||
|
return {}, [], [f"the platform's own file is required: {m}" for m in missing]
|
||||||
|
if exporter.needs_original() and not originals:
|
||||||
|
return {}, [], ["the platform's own file is required and none was read"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
produced = exporter.render(systems, report, originals, scraped)
|
||||||
|
except ValueError as exc:
|
||||||
|
return {}, [], [str(exc)]
|
||||||
|
|
||||||
|
if not produced and not exporter.may_write_nothing():
|
||||||
|
return {}, [], ["the exporter produced no file"]
|
||||||
|
|
||||||
|
issues = exporter.validate(systems, produced)
|
||||||
|
if issues:
|
||||||
|
# Written first, a file its own validator refused replaced the
|
||||||
|
# published export and only the exit code said so.
|
||||||
|
invalid = [f"INVALID: {issue}" for issue in issues[:10]]
|
||||||
|
if len(issues) > 10:
|
||||||
|
invalid.append(f"and {len(issues) - 10} more validation failures")
|
||||||
|
return {}, issues, invalid
|
||||||
|
return produced, issues, []
|
||||||
|
|
||||||
|
|
||||||
|
def _entry_outcomes(exporter: BaseExporter, systems: dict) -> tuple[int, int, int]:
|
||||||
|
"""Additions written, additions refused, and platform entries lost."""
|
||||||
|
landed = 0
|
||||||
|
refused = 0
|
||||||
|
lost = 0
|
||||||
|
for system in systems.values():
|
||||||
|
for entry in system.files:
|
||||||
|
if not entry.name:
|
||||||
|
continue
|
||||||
|
if exporter.lands(entry):
|
||||||
|
landed += entry.platform is None
|
||||||
|
elif entry.platform is None:
|
||||||
|
refused += 1
|
||||||
|
else:
|
||||||
|
# The platform declares it and the format still cannot state
|
||||||
|
# it, so their own file loses a line. Worth saying out loud.
|
||||||
|
lost += 1
|
||||||
|
return landed, refused, lost
|
||||||
|
|
||||||
|
|
||||||
|
def _landed_summary(report: Report, changes: LandedChanges, landed: int, lost: int) -> str:
|
||||||
|
# What the written file carries, in the terms the exports page uses.
|
||||||
|
# What it does not carry is counted on a line of its own below.
|
||||||
|
parts = [f"{report.files_kept} kept"]
|
||||||
|
landed_counts = (
|
||||||
|
(landed, "file", "", "added"),
|
||||||
|
(len(changes.applied), "hash", "", "updated to the emulator source"),
|
||||||
|
(changes.requirements, "required flag", "", "aligned with the code"),
|
||||||
|
(len(changes.filled), "hash", "", "added to an existing entry"),
|
||||||
|
(len(changes.resized), "size", "", "updated to the emulator source"),
|
||||||
|
(len(changes.unsized), "size", "", "removed"),
|
||||||
|
(len(changes.cleared), "hash", "", "removed"),
|
||||||
|
(lost, "entry", "entries", "removed, the format cannot state them"),
|
||||||
|
(changes.lists, "md5 list", "", "written, any listed value passes"),
|
||||||
|
)
|
||||||
|
parts += [
|
||||||
|
f"{_count(number, noun, plural)} {verb}"
|
||||||
|
for number, noun, plural, verb in landed_counts
|
||||||
|
if number
|
||||||
|
]
|
||||||
|
return ", ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _unwritten(refused: int, withheld: list[str], report: Report) -> list[str]:
|
||||||
|
return [
|
||||||
|
f"{_count(number, noun, plural)} {what}"
|
||||||
|
for number, noun, plural, what in (
|
||||||
|
(refused, "file", "", "the format or its checker cannot carry"),
|
||||||
|
(len(withheld), "update", "", "withheld"),
|
||||||
|
# A content-scanning core's names are labels: a list checked
|
||||||
|
# by path cannot hold them.
|
||||||
|
(report.labels, "entry", "entries", "found by content"),
|
||||||
|
(len(report.unattributed), "file", "",
|
||||||
|
"no single native system of the platform takes"),
|
||||||
|
)
|
||||||
|
if number
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _export_messages(
|
||||||
|
summary: str,
|
||||||
|
unwritten: list[str],
|
||||||
|
candidates: list[dict],
|
||||||
|
doubled: list[dict],
|
||||||
|
withheld: list[str],
|
||||||
|
changes: LandedChanges,
|
||||||
|
) -> list[str]:
|
||||||
|
messages = [summary]
|
||||||
|
if unwritten:
|
||||||
|
messages.append("not in the file: " + ", ".join(unwritten))
|
||||||
|
if candidates:
|
||||||
|
open_question = sum(c["verdict"] == "undetermined" for c in candidates)
|
||||||
|
messages.append(
|
||||||
|
f"{_count(len(candidates), 'entry', 'entries')} no examined core is known to open"
|
||||||
|
+ (f" ({open_question} undetermined)" if open_question else "")
|
||||||
|
+ ", listed in the report"
|
||||||
|
)
|
||||||
|
if doubled:
|
||||||
|
messages.append(
|
||||||
|
f"{_count(len(doubled), 'destination')} declared twice for two files"
|
||||||
|
", listed in the report"
|
||||||
|
)
|
||||||
|
messages.extend(f"withheld: {reason}" for reason in withheld)
|
||||||
|
for heading, labels in (
|
||||||
|
("hash updated", changes.applied),
|
||||||
|
("hash added", changes.filled),
|
||||||
|
("size updated", changes.resized),
|
||||||
|
("size removed", changes.unsized),
|
||||||
|
("hash removed", changes.cleared),
|
||||||
|
):
|
||||||
|
messages.extend(f"{heading}: {label}" for label in labels[:5])
|
||||||
|
if len(labels) > 5:
|
||||||
|
messages.append(f"and {len(labels) - 5} more")
|
||||||
|
return messages
|
||||||
|
|
||||||
|
|
||||||
def _write_produced(
|
def _write_produced(
|
||||||
root: Path, produced: dict[str, str | bytes], modes: dict[str, int]
|
root: Path, produced: dict[str, str | bytes], modes: dict[str, int]
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -9,11 +9,16 @@ the data block hands the maintainer something that no longer runs.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import Generic, TypeVar, Union
|
||||||
|
|
||||||
from .baseline import NativeFile, NativeSystem, Report
|
from .baseline import NativeFile, NativeSystem, Report
|
||||||
|
|
||||||
|
# What a produced file holds: text for every format, bytes besides for one
|
||||||
|
# that also hands back an archive (MiSTer's bios_db.json.zip).
|
||||||
|
Content = TypeVar("Content", bound=Union[str, bytes])
|
||||||
|
|
||||||
class BaseExporter(ABC):
|
|
||||||
|
class BaseExporter(ABC, Generic[Content]):
|
||||||
"""Base class for writing a platform's own BIOS file, corrected."""
|
"""Base class for writing a platform's own BIOS file, corrected."""
|
||||||
|
|
||||||
# A hash field the checker compares to one value: an addition the
|
# A hash field the checker compares to one value: an addition the
|
||||||
@@ -77,14 +82,14 @@ class BaseExporter(ABC):
|
|||||||
report: Report,
|
report: Report,
|
||||||
originals: dict[str, str],
|
originals: dict[str, str],
|
||||||
scraped: dict | None = None,
|
scraped: dict | None = None,
|
||||||
) -> dict[str, str]:
|
) -> dict[str, Content]:
|
||||||
"""Return {relative output path: file content}."""
|
"""Return {relative output path: file content}."""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def validate(
|
def validate(
|
||||||
self,
|
self,
|
||||||
systems: dict[str, NativeSystem],
|
systems: dict[str, NativeSystem],
|
||||||
produced: dict[str, str],
|
produced: dict[str, Content],
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
"""Check the produced files against what was asked of them."""
|
"""Check the produced files against what was asked of them."""
|
||||||
|
|
||||||
@@ -162,8 +167,7 @@ class BaseExporter(ABC):
|
|||||||
list carries."""
|
list carries."""
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@classmethod
|
def writable(self, fe: NativeFile, require: str = "") -> bool:
|
||||||
def writable(cls, fe: NativeFile, require: str = "") -> bool:
|
|
||||||
"""Whether this format can carry the entry.
|
"""Whether this format can carry the entry.
|
||||||
|
|
||||||
An entry the platform already declares is always carried, hash or
|
An entry the platform already declares is always carried, hash or
|
||||||
@@ -171,7 +175,7 @@ class BaseExporter(ABC):
|
|||||||
hands back a file poorer than the one it corrects. The requirement
|
hands back a file poorer than the one it corrects. The requirement
|
||||||
only gates what we would be adding.
|
only gates what we would be adding.
|
||||||
"""
|
"""
|
||||||
return cls._carried(fe, require, cls.SINGLE_HASH_FIELD)
|
return self._carried(fe, require, self.SINGLE_HASH_FIELD)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _carried(cls, fe: NativeFile, require: str, single: str | None) -> bool:
|
def _carried(cls, fe: NativeFile, require: str, single: str | None) -> bool:
|
||||||
|
|||||||
+168
-136
@@ -121,7 +121,7 @@ def _field_sets(entry: dict | None) -> dict[str, set[str]]:
|
|||||||
return {f: set(_hash_values(entry or {}, f)) for f in HASH_FIELDS}
|
return {f: set(_hash_values(entry or {}, f)) for f in HASH_FIELDS}
|
||||||
|
|
||||||
|
|
||||||
def _single_size(value: object) -> int | None:
|
def _single_size(value: int | str | list[int | str]) -> int | None:
|
||||||
"""One size, or None: a list names several accepted revisions, which a
|
"""One size, or None: a list names several accepted revisions, which a
|
||||||
single size field cannot state (int() on it stopped the whole export)."""
|
single size field cannot state (int() on it stopped the whole export)."""
|
||||||
if isinstance(value, list):
|
if isinstance(value, list):
|
||||||
@@ -499,22 +499,9 @@ def platform_declares(truth_entry: dict, candidates: list[dict]) -> bool:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def build_native_model(
|
def _platform_systems(scraped_systems: dict, report: Report) -> dict[str, NativeSystem]:
|
||||||
truth: dict,
|
"""Pass 1: the platform's own file, grouped as the platform groups it."""
|
||||||
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()
|
|
||||||
systems: dict[str, NativeSystem] = {}
|
systems: dict[str, NativeSystem] = {}
|
||||||
|
|
||||||
scraped_systems = (scraped or {}).get("systems", {})
|
|
||||||
composite_zips = (scraped or {}).get("zip_digest") == "composite"
|
|
||||||
|
|
||||||
# Pass 1: the platform's own file, grouped as the platform groups it.
|
|
||||||
for sys_key, sys_data in scraped_systems.items():
|
for sys_key, sys_data in scraped_systems.items():
|
||||||
for file_entry in sys_data.get("files", []):
|
for file_entry in sys_data.get("files", []):
|
||||||
native_id = _native_id_of(sys_key, sys_data, file_entry)
|
native_id = _native_id_of(sys_key, sys_data, file_entry)
|
||||||
@@ -540,31 +527,83 @@ def build_native_model(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
report.files_kept += 1
|
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.
|
# Which native ids a truth system may contribute to.
|
||||||
norm_to_scraped: dict[str, str] = {
|
norm_to_scraped: dict[str, str] = field(init=False)
|
||||||
_norm_system_id(key): key for key in scraped_systems
|
|
||||||
}
|
|
||||||
# Every system the platform names, files or none: an addition elsewhere
|
# Every system the platform names, files or none: an addition elsewhere
|
||||||
# is filed under our own slug.
|
# is filed under our own slug.
|
||||||
platform_ids = {
|
platform_ids: set[str] = field(init=False)
|
||||||
native_id
|
native_by_norm: dict[str, str] = field(init=False)
|
||||||
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", [])),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
native_by_norm: dict[str, str] = {}
|
|
||||||
for system in systems.values():
|
|
||||||
native_by_norm.setdefault(_norm_system_id(system.native_id), system.native_id)
|
|
||||||
|
|
||||||
def _target_native_ids(truth_sid: str) -> tuple[list[str], bool]:
|
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
|
"""The native ids a truth system spans, and whether the first one
|
||||||
is where an addition belongs without asking which core reads it."""
|
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
|
scraped_key = truth_sid if truth_sid in scraped_systems else None
|
||||||
if scraped_key is None:
|
if scraped_key is None:
|
||||||
scraped_key = norm_to_scraped.get(_norm_system_id(truth_sid))
|
scraped_key = self.norm_to_scraped.get(_norm_system_id(truth_sid))
|
||||||
if scraped_key is not None:
|
if scraped_key is not None:
|
||||||
sys_data = scraped_systems[scraped_key]
|
sys_data = scraped_systems[scraped_key]
|
||||||
ids = {
|
ids = {
|
||||||
@@ -583,28 +622,28 @@ def build_native_model(
|
|||||||
ordered.remove(primary)
|
ordered.remove(primary)
|
||||||
ordered.insert(0, primary)
|
ordered.insert(0, primary)
|
||||||
return ordered, primary in ids or len(ordered) == 1
|
return ordered, primary in ids or len(ordered) == 1
|
||||||
direct = native_by_norm.get(_norm_system_id(truth_sid))
|
direct = self.native_by_norm.get(_norm_system_id(truth_sid))
|
||||||
return ([direct] if direct else [truth_sid]), True
|
return ([direct] if direct else [truth_sid]), True
|
||||||
|
|
||||||
# Pass 2: apply the truth onto that grouping.
|
def _files_of(self, target_ids: list[str]) -> list[NativeFile]:
|
||||||
for truth_sid in sorted(truth.get("systems", {})):
|
return [
|
||||||
truth_sys = truth["systems"][truth_sid]
|
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", [])
|
truth_files = truth_sys.get("files", [])
|
||||||
if not truth_files:
|
if not truth_files:
|
||||||
continue
|
return
|
||||||
|
|
||||||
target_ids, settled_id = _target_native_ids(truth_sid)
|
target_ids, settled_id = self.target_native_ids(truth_sid)
|
||||||
truth_files = [
|
truth_files = [
|
||||||
entry for entry in truth_files
|
entry for entry in truth_files
|
||||||
if (name := str(entry.get("name", "")))
|
if (name := str(entry.get("name", "")))
|
||||||
and not name.startswith("_") and not _is_placeholder(name)
|
and not name.startswith("_") and not _is_placeholder(name)
|
||||||
]
|
]
|
||||||
candidates = [
|
candidates = [c for c in self._files_of(target_ids) if c.truth is None]
|
||||||
candidate
|
|
||||||
for native_id in target_ids
|
|
||||||
for candidate in systems.get(native_id, NativeSystem(native_id)).files
|
|
||||||
if candidate.truth is None
|
|
||||||
]
|
|
||||||
pairs = pair_entries(truth_files, [c.platform or {} for c in candidates])
|
pairs = pair_entries(truth_files, [c.platform or {} for c in candidates])
|
||||||
# The cores that read what the platform files under each native id,
|
# The cores that read what the platform files under each native id,
|
||||||
# from the truth entries its declarations pair with.
|
# from the truth entries its declarations pair with.
|
||||||
@@ -613,109 +652,102 @@ def build_native_model(
|
|||||||
readers.setdefault(candidates[index].native_system, set()).update(
|
readers.setdefault(candidates[index].native_system, set()).update(
|
||||||
truth_files[t_index].get("_cores") or ()
|
truth_files[t_index].get("_cores") or ()
|
||||||
)
|
)
|
||||||
for candidate in (
|
for candidate in (c for c in self._files_of(target_ids) if c.platform is not None):
|
||||||
c
|
|
||||||
for native_id in target_ids
|
|
||||||
for c in systems.get(native_id, NativeSystem(native_id)).files
|
|
||||||
if c.platform is not None
|
|
||||||
):
|
|
||||||
own = str(candidate.name).casefold()
|
own = str(candidate.name).casefold()
|
||||||
candidate.namesakes.extend(
|
candidate.namesakes.extend(
|
||||||
entry for entry in truth_files if own in _names(entry)
|
entry for entry in truth_files if own in _names(entry)
|
||||||
)
|
)
|
||||||
|
|
||||||
for t_index, truth_entry in enumerate(truth_files):
|
for t_index, truth_entry in enumerate(truth_files):
|
||||||
name = str(truth_entry["name"])
|
paired = pairs.get(t_index)
|
||||||
index = pairs.get(t_index)
|
if paired is not None:
|
||||||
matched = candidates[index] if index is not None else None
|
_correct_matched(candidates[paired], truth_entry, self.report)
|
||||||
|
|
||||||
if matched is not None:
|
|
||||||
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}"
|
|
||||||
)
|
|
||||||
continue
|
continue
|
||||||
|
self._add(truth_sid, truth_entry, target_ids, settled_id, readers)
|
||||||
|
|
||||||
if is_label(truth_entry):
|
def _add(
|
||||||
report.labels += 1
|
self,
|
||||||
continue
|
truth_sid: str,
|
||||||
# The emulator installs it: no user is asked to bring it.
|
truth_entry: dict,
|
||||||
if truth_entry.get("bundled"):
|
target_ids: list[str],
|
||||||
continue
|
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
|
# A file another core's entry already claimed is still the
|
||||||
# platform's file, not a new one: scph101.bin, declared by two
|
# platform's file, not a new one: scph101.bin, declared by two
|
||||||
# PSX cores, was written into RetroDECK's manifest a second time.
|
# PSX cores, was written into RetroDECK's manifest a second time.
|
||||||
declared = [
|
declared = [
|
||||||
candidate.platform
|
candidate.platform
|
||||||
for native_id in target_ids
|
for candidate in self._files_of(target_ids)
|
||||||
for candidate in systems.get(native_id, NativeSystem(native_id)).files
|
if candidate.platform is not None
|
||||||
if candidate.platform is not None
|
]
|
||||||
]
|
if platform_declares(truth_entry, declared):
|
||||||
if platform_declares(truth_entry, declared):
|
return
|
||||||
continue
|
|
||||||
|
|
||||||
# The truth knows a file the platform does not declare. Across
|
# The truth knows a file the platform does not declare. Across
|
||||||
# several native ids and no primary, it joins the one whose files
|
# several native ids and no primary, it joins the one whose files
|
||||||
# its cores read: RetroDECK's arcade spans mame and fbneo, and
|
# its cores read: RetroDECK's arcade spans mame and fbneo, and
|
||||||
# MAME device archives were filed as FBNeo BIOS because fbneo
|
# MAME device archives were filed as FBNeo BIOS because fbneo
|
||||||
# sorts first. With no single answer it is not written.
|
# sorts first. With no single answer it is not written.
|
||||||
native_id = target_ids[0]
|
native_id = target_ids[0]
|
||||||
if not settled_id:
|
if not settled_id:
|
||||||
wanted = set(truth_entry.get("_cores") or ())
|
wanted = set(truth_entry.get("_cores") or ())
|
||||||
shared = {nid: len(readers.get(nid, set()) & wanted) for nid in target_ids}
|
shared = {nid: len(readers.get(nid, set()) & wanted) for nid in target_ids}
|
||||||
best = max(shared.values())
|
best = max(shared.values())
|
||||||
winners = [nid for nid, count in shared.items() if count == best]
|
winners = [nid for nid, count in shared.items() if count == best]
|
||||||
if not best or len(winners) > 1:
|
if not best or len(winners) > 1:
|
||||||
report.unattributed.append(f"{truth_sid}/{name}")
|
self.report.unattributed.append(f"{truth_sid}/{name}")
|
||||||
continue
|
return
|
||||||
native_id = winners[0]
|
native_id = winners[0]
|
||||||
system = systems.get(native_id)
|
system = self.systems.get(native_id)
|
||||||
if system is None:
|
if system is None:
|
||||||
system = NativeSystem(native_id=native_id, from_platform=False)
|
system = NativeSystem(native_id=native_id, from_platform=False)
|
||||||
systems[native_id] = system
|
self.systems[native_id] = system
|
||||||
report.systems_added += 1
|
self.report.systems_added += 1
|
||||||
destination = str(
|
destination = str(
|
||||||
truth_entry.get("path") or truth_entry.get("destination") or name
|
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"),
|
||||||
)
|
)
|
||||||
system.files.append(
|
)
|
||||||
NativeFile(
|
self.report.files_added += 1
|
||||||
name=name,
|
|
||||||
destination=destination,
|
|
||||||
native_system=native_id,
|
def build_native_model(
|
||||||
truth=truth_entry,
|
truth: dict,
|
||||||
foreign_system=native_id not in platform_ids,
|
scraped: dict | None,
|
||||||
composite_md5=composite_zips and name.lower().endswith(".zip"),
|
) -> tuple[dict[str, NativeSystem], Report]:
|
||||||
)
|
"""Rebuild the platform's systems, corrected by the truth.
|
||||||
)
|
|
||||||
report.files_added += 1
|
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
|
# 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
|
# code looks for first is named first. Only what we add is ordered: what
|
||||||
|
|||||||
@@ -134,6 +134,35 @@ def md5_list_support(script: str) -> frozenset[str]:
|
|||||||
return frozenset(support)
|
return frozenset(support)
|
||||||
|
|
||||||
|
|
||||||
|
def _md5_patched(item: str, md5: str | list[str]) -> str:
|
||||||
|
"""An item's text with only its md5 value replaced."""
|
||||||
|
return _MD5_VALUE.sub(
|
||||||
|
lambda m: m.group(1) + _md5_literal(
|
||||||
|
md5, spaced=not m.group(2).startswith("[\"")
|
||||||
|
),
|
||||||
|
item,
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _appended_items(
|
||||||
|
added: list[str], last: re.Match[str], joined: str, original: list[str],
|
||||||
|
) -> str:
|
||||||
|
"""The text that follows an entry's last item with the items it gains,
|
||||||
|
in the form that item is written."""
|
||||||
|
# Their spacing before the closing brace: '"x"}' or '"x" }'.
|
||||||
|
tight = not last.group(0).endswith(" }")
|
||||||
|
added = [a[:-2] + "}" if tight and a.endswith(" }") else a for a in added]
|
||||||
|
if len(original) == 1:
|
||||||
|
return ", " + ", ".join(added)
|
||||||
|
line_start = joined.rfind("\n", 0, last.start()) + 1
|
||||||
|
indent = joined[line_start:last.start()]
|
||||||
|
return "," + "".join(
|
||||||
|
f"\n{indent}{a}" + ("," if i < len(added) - 1 else "")
|
||||||
|
for i, a in enumerate(added)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _md5_literal(value: str | list[str], spaced: bool = True) -> str:
|
def _md5_literal(value: str | list[str], spaced: bool = True) -> str:
|
||||||
"""An md5 as the script writes it: a quoted string, or a list of them
|
"""An md5 as the script writes it: a quoted string, or a list of them
|
||||||
with Batocera's spacing inside the brackets (`[ "a", "b" ]`)."""
|
with Batocera's spacing inside the brackets (`[ "a", "b" ]`)."""
|
||||||
@@ -152,7 +181,7 @@ def _note_key(text: str) -> tuple[str, str]:
|
|||||||
return (path.group(1) if path else "", member.group(1) if member else "")
|
return (path.group(1) if path else "", member.group(1) if member else "")
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write Batocera's batocera-systems, corrected."""
|
"""Write Batocera's batocera-systems, corrected."""
|
||||||
|
|
||||||
# checkBios compares one md5 for a plain file. altmd5 is read only for
|
# checkBios compares one md5 for a plain file. altmd5 is read only for
|
||||||
@@ -180,7 +209,7 @@ class Exporter(BaseExporter):
|
|||||||
super().__init__()
|
super().__init__()
|
||||||
# The emulator and core each system entry of the original is gated
|
# The emulator and core each system entry of the original is gated
|
||||||
# on, read by render.
|
# on, read by render.
|
||||||
self._gates: dict[str, tuple[str, str] | None] = {}
|
self._gates: dict[str, tuple[str, str | None] | None] = {}
|
||||||
# The items the pinned checker reads an md5 list for, read by
|
# The items the pinned checker reads an md5 list for, read by
|
||||||
# render from the platform's own file.
|
# render from the platform's own file.
|
||||||
self._md5_lists: frozenset[str] = frozenset()
|
self._md5_lists: frozenset[str] = frozenset()
|
||||||
@@ -338,11 +367,11 @@ class Exporter(BaseExporter):
|
|||||||
for item in (before or {}).get("biosFiles", [])
|
for item in (before or {}).get("biosFiles", [])
|
||||||
if isinstance(item, dict)
|
if isinstance(item, dict)
|
||||||
}
|
}
|
||||||
parts: list[str] = []
|
return [
|
||||||
for fe in files:
|
self._bios_item(fe, runner, originals)
|
||||||
for runner in self._item_runners(fe):
|
for fe in files
|
||||||
parts.append(self._bios_item(fe, runner, originals))
|
for runner in self._item_runners(fe)
|
||||||
return parts
|
]
|
||||||
|
|
||||||
def _item_runners(self, fe: NativeFile) -> list[list[str] | None]:
|
def _item_runners(self, fe: NativeFile) -> list[list[str] | None]:
|
||||||
"""One item per runner an addition names. None keeps the original's."""
|
"""One item per runner an addition names. None keeps the original's."""
|
||||||
@@ -431,7 +460,6 @@ class Exporter(BaseExporter):
|
|||||||
trailing[key] = line[hash_at:].rstrip()
|
trailing[key] = line[hash_at:].rstrip()
|
||||||
return trailing, leading
|
return trailing, leading
|
||||||
|
|
||||||
|
|
||||||
def _entry_block(
|
def _entry_block(
|
||||||
self,
|
self,
|
||||||
system: NativeSystem,
|
system: NativeSystem,
|
||||||
@@ -443,7 +471,9 @@ class Exporter(BaseExporter):
|
|||||||
before = self._parse_entry(original)
|
before = self._parse_entry(original)
|
||||||
own = self._own_entry(system, before)
|
own = self._own_entry(system, before)
|
||||||
items = self._bios_items(files, own)
|
items = self._bios_items(files, own)
|
||||||
indent = _ENTRY_START.match(original[0]).group(1)
|
start = _ENTRY_START.match(original[0])
|
||||||
|
assert start is not None, original[0]
|
||||||
|
indent = start.group(1)
|
||||||
one_line = len(original) == 1 and not trailing and not leading
|
one_line = len(original) == 1 and not trailing and not leading
|
||||||
if one_line:
|
if one_line:
|
||||||
return [self._entry_line(system, files, before, indent)]
|
return [self._entry_line(system, files, before, indent)]
|
||||||
@@ -483,7 +513,7 @@ class Exporter(BaseExporter):
|
|||||||
before = self._parse_entry(original)
|
before = self._parse_entry(original)
|
||||||
own = self._own_entry(system, before)
|
own = self._own_entry(system, before)
|
||||||
wanted: dict[tuple, list[dict]] = {}
|
wanted: dict[tuple, list[dict]] = {}
|
||||||
order: list[tuple[tuple, dict]] = []
|
order: list[tuple[tuple, str]] = []
|
||||||
for text in self._bios_items(files, own):
|
for text in self._bios_items(files, own):
|
||||||
item = ast.literal_eval(text)
|
item = ast.literal_eval(text)
|
||||||
key = tuple(item.get(k) for k in ("file", "zippedFile", "emulator", "core"))
|
key = tuple(item.get(k) for k in ("file", "zippedFile", "emulator", "core"))
|
||||||
@@ -517,14 +547,7 @@ class Exporter(BaseExporter):
|
|||||||
continue
|
continue
|
||||||
if {k for k in {*ours, *theirs} if ours.get(k) != theirs.get(k)} - {"md5"}:
|
if {k for k in {*ours, *theirs} if ours.get(k) != theirs.get(k)} - {"md5"}:
|
||||||
return None
|
return None
|
||||||
patched = _MD5_VALUE.sub(
|
edits.append((match.start(), match.end(), _md5_patched(match.group(0), ours["md5"])))
|
||||||
lambda m: m.group(1) + _md5_literal(
|
|
||||||
ours["md5"], spaced=not m.group(2).startswith("[\"")
|
|
||||||
),
|
|
||||||
match.group(0),
|
|
||||||
count=1,
|
|
||||||
)
|
|
||||||
edits.append((match.start(), match.end(), patched))
|
|
||||||
if last is None:
|
if last is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -535,19 +558,7 @@ class Exporter(BaseExporter):
|
|||||||
if seen[key] > consumed.get(key, 0):
|
if seen[key] > consumed.get(key, 0):
|
||||||
added.append(text)
|
added.append(text)
|
||||||
if added:
|
if added:
|
||||||
# Their spacing before the closing brace: '"x"}' or '"x" }'.
|
edits.append((last.end(), last.end(), _appended_items(added, last, joined, original)))
|
||||||
tight = not last.group(0).endswith(" }")
|
|
||||||
added = [a[:-2] + "}" if tight and a.endswith(" }") else a for a in added]
|
|
||||||
if len(original) == 1:
|
|
||||||
insert = ", " + ", ".join(added)
|
|
||||||
else:
|
|
||||||
line_start = joined.rfind("\n", 0, last.start()) + 1
|
|
||||||
indent = joined[line_start:last.start()]
|
|
||||||
insert = "," + "".join(
|
|
||||||
f"\n{indent}{a}" + ("," if i < len(added) - 1 else "")
|
|
||||||
for i, a in enumerate(added)
|
|
||||||
)
|
|
||||||
edits.append((last.end(), last.end(), insert))
|
|
||||||
|
|
||||||
for start, end, text in sorted(edits, reverse=True):
|
for start, end, text in sorted(edits, reverse=True):
|
||||||
joined = joined[:start] + text + joined[end:]
|
joined = joined[:start] + text + joined[end:]
|
||||||
@@ -638,7 +649,8 @@ class Exporter(BaseExporter):
|
|||||||
spans = self._entry_spans(body)
|
spans = self._entry_spans(body)
|
||||||
for key, (start, end) in spans.items():
|
for key, (start, end) in spans.items():
|
||||||
parsed = self._parse_entry(body[start:end + 1]) or {}
|
parsed = self._parse_entry(body[start:end + 1]) or {}
|
||||||
own = parsed.get(key) if isinstance(parsed.get(key), dict) else {}
|
value = parsed.get(key)
|
||||||
|
own = value if isinstance(value, dict) else {}
|
||||||
emulator, core = own.get("emulator"), own.get("core")
|
emulator, core = own.get("emulator"), own.get("core")
|
||||||
self._gates[key] = (
|
self._gates[key] = (
|
||||||
(emulator, core if isinstance(core, str) else None)
|
(emulator, core if isinstance(core, str) else None)
|
||||||
@@ -716,9 +728,11 @@ class Exporter(BaseExporter):
|
|||||||
issues.append(f"system absent: {system.native_id}")
|
issues.append(f"system absent: {system.native_id}")
|
||||||
continue
|
continue
|
||||||
declared = {bios.get("file", "") for bios in entry.get("biosFiles", [])}
|
declared = {bios.get("file", "") for bios in entry.get("biosFiles", [])}
|
||||||
for fe in files:
|
issues.extend(
|
||||||
if self.declared_path(fe) not in declared:
|
f"absent: {system.native_id}/{fe.name}"
|
||||||
issues.append(f"absent: {system.native_id}/{fe.name}")
|
for fe in files
|
||||||
|
if self.declared_path(fe) not in declared
|
||||||
|
)
|
||||||
|
|
||||||
for native_id, entry in exported.items():
|
for native_id, entry in exported.items():
|
||||||
if not entry.get("biosFiles"):
|
if not entry.get("biosFiles"):
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ SOURCE_URL = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[str]):
|
||||||
"""Serve BizHawk's FirmwareDatabase.cs as BizHawk wrote it."""
|
"""Serve BizHawk's FirmwareDatabase.cs as BizHawk wrote it."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ from common import _norm_system_id, resolve_platform_cores, unresolved_platform_
|
|||||||
from exporter.baseline import HASH_FIELDS, NativeSystem, _hash_values
|
from exporter.baseline import HASH_FIELDS, NativeSystem, _hash_values
|
||||||
from launchers import _names as launcher_names
|
from launchers import _names as launcher_names
|
||||||
|
|
||||||
|
|
||||||
def _tails(path: str) -> list[str]:
|
def _tails(path: str) -> list[str]:
|
||||||
"""Every trailing run of segments of a path, longest first."""
|
"""Every trailing run of segments of a path, longest first."""
|
||||||
parts = [p for p in path.casefold().strip("/").split("/") if p]
|
parts = [p for p in path.casefold().strip("/").split("/") if p]
|
||||||
@@ -431,11 +432,12 @@ class EntryCategories:
|
|||||||
def cited(f: dict) -> dict:
|
def cited(f: dict) -> dict:
|
||||||
return {k: f[k] for k in ("name", "source_ref") if f.get(k)}
|
return {k: f[k] for k in ("name", "source_ref") if f.get(k)}
|
||||||
|
|
||||||
found: dict[int, dict] = {}
|
found: dict[int, dict] = {
|
||||||
for values in declared.values():
|
position: f
|
||||||
for value in values:
|
for values in declared.values()
|
||||||
for position, f in by_hash_index.get(value, ()):
|
for value in values
|
||||||
found[position] = f
|
for position, f in by_hash_index.get(value, ())
|
||||||
|
}
|
||||||
if found:
|
if found:
|
||||||
return [cited(found[p]) for p in sorted(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, ())}
|
named = {position: f for n in names for position, f in by_name_index.get(n, ())}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ SOURCE_URL = (
|
|||||||
_MD5 = re.compile(r"^[0-9a-f]{32}$")
|
_MD5 = re.compile(r"^[0-9a-f]{32}$")
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write EmuDeck's checkBIOS.sh, corrected."""
|
"""Write EmuDeck's checkBIOS.sh, corrected."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -135,7 +135,9 @@ class Exporter(BaseExporter):
|
|||||||
if system.native_id != system_id:
|
if system.native_id != system_id:
|
||||||
continue
|
continue
|
||||||
for fe in system.files:
|
for fe in system.files:
|
||||||
if not cls.writable(fe):
|
# The base writable rule, which EmuDeck keeps: it needs no
|
||||||
|
# render state, so the class answers it.
|
||||||
|
if not cls._carried(fe, "", cls.SINGLE_HASH_FIELD):
|
||||||
continue
|
continue
|
||||||
for value in cls._entry_md5s(fe):
|
for value in cls._entry_md5s(fe):
|
||||||
if _MD5.match(value) and value not in seen:
|
if _MD5.match(value) and value not in seen:
|
||||||
@@ -227,7 +229,5 @@ class Exporter(BaseExporter):
|
|||||||
if not _RE_LOCAL_HASHES.search(body):
|
if not _RE_LOCAL_HASHES.search(body):
|
||||||
# A check with no hash list is a path check, not a hash check.
|
# A check with no hash list is a path check, not a hash check.
|
||||||
continue
|
continue
|
||||||
for md5 in md5s:
|
issues.extend(f"absent from {name}: {md5}" for md5 in md5s if md5 not in body)
|
||||||
if md5 not in body:
|
|
||||||
issues.append(f"absent from {name}: {md5}")
|
|
||||||
return issues
|
return issues
|
||||||
@@ -11,6 +11,7 @@ import io
|
|||||||
import json
|
import json
|
||||||
import zipfile
|
import zipfile
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
from .base_exporter import BaseExporter
|
from .base_exporter import BaseExporter
|
||||||
from .baseline import NativeFile, NativeSystem, Report
|
from .baseline import NativeFile, NativeSystem, Report
|
||||||
@@ -42,7 +43,7 @@ def rebuild_archive(original: bytes, member: str, text: str) -> bytes:
|
|||||||
return buffer.getvalue()
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[Union[str, bytes]]):
|
||||||
"""Write MiSTer's bios_db.json, corrected."""
|
"""Write MiSTer's bios_db.json, corrected."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -99,8 +100,8 @@ class Exporter(BaseExporter):
|
|||||||
"""
|
"""
|
||||||
return fe.record_hash(field_name)
|
return fe.record_hash(field_name)
|
||||||
|
|
||||||
def _by_path(self, systems: dict[str, NativeSystem]) -> dict[str, object]:
|
def _by_path(self, systems: dict[str, NativeSystem]) -> dict[str, NativeFile]:
|
||||||
indexed: dict[str, object] = {}
|
indexed: dict[str, NativeFile] = {}
|
||||||
for system in systems.values():
|
for system in systems.values():
|
||||||
for fe in system.files:
|
for fe in system.files:
|
||||||
if fe.destination:
|
if fe.destination:
|
||||||
@@ -173,7 +174,7 @@ class Exporter(BaseExporter):
|
|||||||
def validate(
|
def validate(
|
||||||
self,
|
self,
|
||||||
systems: dict[str, NativeSystem],
|
systems: dict[str, NativeSystem],
|
||||||
produced: dict[str, str],
|
produced: dict[str, str | bytes],
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
try:
|
try:
|
||||||
database = json.loads(produced[_DB_NAME])
|
database = json.loads(produced[_DB_NAME])
|
||||||
|
|||||||
@@ -42,6 +42,36 @@ _SYSTEM_BLOCK = re.compile(r"<system\b.*?</system>", re.S)
|
|||||||
_BIOS_ELEMENT = re.compile(r"[ \t]*<bios\b.*?/>", re.S)
|
_BIOS_ELEMENT = re.compile(r"[ \t]*<bios\b.*?/>", re.S)
|
||||||
|
|
||||||
|
|
||||||
|
def _bios_line(attrs: dict[str, str]) -> str:
|
||||||
|
rendered = " ".join(f"{k}={quoteattr(v)}" for k, v in attrs.items())
|
||||||
|
return f" <bios {rendered} />"
|
||||||
|
|
||||||
|
|
||||||
|
def _block_body(
|
||||||
|
children: list[dict[str, str] | str],
|
||||||
|
elements: dict[str, tuple[NativeFile, str]],
|
||||||
|
raw: dict[str, str],
|
||||||
|
) -> list[str]:
|
||||||
|
"""One block of theirs, each element corrected where ours differs."""
|
||||||
|
body: list[str] = []
|
||||||
|
for child in children:
|
||||||
|
if isinstance(child, str):
|
||||||
|
body.append(f" {child}")
|
||||||
|
continue
|
||||||
|
path = child.get("path", "")
|
||||||
|
mine = elements.pop(path, None)
|
||||||
|
kept = raw.get(" ".join(path.split()))
|
||||||
|
if kept is not None and (mine is None or _stated(mine[1]) == _stated(kept)):
|
||||||
|
body.append(kept)
|
||||||
|
elif kept is not None and mine is not None and _stated(
|
||||||
|
patched := patch_element(kept, mine[1])
|
||||||
|
) == _stated(mine[1]):
|
||||||
|
body.append(patched)
|
||||||
|
else:
|
||||||
|
body.append(mine[1] if mine else _bios_line(child))
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
def _stated(text: str) -> dict[str, str]:
|
def _stated(text: str) -> dict[str, str]:
|
||||||
"""What an element says, without its layout: attribute order, spacing,
|
"""What an element says, without its layout: attribute order, spacing,
|
||||||
line breaks inside a value and the case of a digest are not content."""
|
line breaks inside a value and the case of a digest are not content."""
|
||||||
@@ -110,7 +140,7 @@ def _original_elements(original: str) -> list[dict[str, str]]:
|
|||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write Recalbox's es_bios.xml, corrected."""
|
"""Write Recalbox's es_bios.xml, corrected."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -288,8 +318,7 @@ class Exporter(BaseExporter):
|
|||||||
for label in sorted(getattr(self, "_held_whole", {}).values())
|
for label in sorted(getattr(self, "_held_whole", {}).values())
|
||||||
]
|
]
|
||||||
|
|
||||||
@classmethod
|
def writable(self, fe: NativeFile, require: str = "") -> bool:
|
||||||
def writable(cls, fe: NativeFile, require: str = "") -> bool:
|
|
||||||
"""es_bios.xsd makes md5 and core required: without them, no element.
|
"""es_bios.xsd makes md5 and core required: without them, no element.
|
||||||
|
|
||||||
An entry Recalbox already ships has both, so this only ever gates
|
An entry Recalbox already ships has both, so this only ever gates
|
||||||
@@ -299,6 +328,50 @@ class Exporter(BaseExporter):
|
|||||||
return False
|
return False
|
||||||
return bool(fe.hashes("md5")) and bool(fe.cores())
|
return bool(fe.hashes("md5")) and bool(fe.cores())
|
||||||
|
|
||||||
|
def _their_blocks(self, original: str) -> list[tuple[str, str, list[dict[str, str] | str]]]:
|
||||||
|
"""Recalbox's blocks: platform, full name, and each bios element or
|
||||||
|
comment they hold."""
|
||||||
|
if not original:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
root = parse_untrusted_xml(original, self.native_filename(), comments=True)
|
||||||
|
except (ParseError, ValueError) as exc:
|
||||||
|
# Rebuilt from our model alone, the export would drop every
|
||||||
|
# system we do not transcribe and the maintainer's comments.
|
||||||
|
raise ValueError(
|
||||||
|
f"Recalbox's {self.native_filename()} does not parse ({exc}); "
|
||||||
|
"fetch it again with --refresh-cache"
|
||||||
|
) from exc
|
||||||
|
if root is None:
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
(s.get("platform", ""), s.get("fullname", ""), [
|
||||||
|
f"<!--{child.text}-->" if child.tag is Comment else dict(child.attrib)
|
||||||
|
for child in s
|
||||||
|
if child.tag is Comment or child.tag == "bios"
|
||||||
|
])
|
||||||
|
for s in root.iter("system")
|
||||||
|
]
|
||||||
|
|
||||||
|
def _our_elements(
|
||||||
|
self, systems: dict[str, NativeSystem],
|
||||||
|
) -> dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]]:
|
||||||
|
ours: dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]] = {}
|
||||||
|
for system in systems.values():
|
||||||
|
# Two additions at one path (two cores, two dumps) are one
|
||||||
|
# element: keyed by path, the second replaced the first and its
|
||||||
|
# md5 left the file while both were counted added.
|
||||||
|
at_path: dict[str, list[NativeFile]] = {}
|
||||||
|
for fe in system.files:
|
||||||
|
if self.writable(fe):
|
||||||
|
at_path.setdefault(self._path(fe), []).append(fe)
|
||||||
|
if at_path:
|
||||||
|
ours[system.native_id] = (system, {
|
||||||
|
path: (group[0], self._bios_element(group[0], system.native_id, tuple(group[1:])))
|
||||||
|
for path, group in at_path.items()
|
||||||
|
})
|
||||||
|
return ours
|
||||||
|
|
||||||
def render(
|
def render(
|
||||||
self,
|
self,
|
||||||
systems: dict[str, NativeSystem],
|
systems: dict[str, NativeSystem],
|
||||||
@@ -316,27 +389,8 @@ class Exporter(BaseExporter):
|
|||||||
# and its system order with it. A platform can hold several blocks
|
# and its system order with it. A platform can hold several blocks
|
||||||
# (Pentagon and Scorpion are both zxspectrum), and an entry the
|
# (Pentagon and Scorpion are both zxspectrum), and an entry the
|
||||||
# maintainer commented out stays commented out.
|
# maintainer commented out stays commented out.
|
||||||
theirs: list[tuple[str, str, list[dict[str, str] | str]]] = []
|
|
||||||
original = originals.get(self.native_filename(), "")
|
original = originals.get(self.native_filename(), "")
|
||||||
if original:
|
theirs = self._their_blocks(original)
|
||||||
try:
|
|
||||||
root = parse_untrusted_xml(original, self.native_filename(), comments=True)
|
|
||||||
except (ParseError, ValueError) as exc:
|
|
||||||
# Rebuilt from our model alone, the export would drop every
|
|
||||||
# system we do not transcribe and the maintainer's comments.
|
|
||||||
raise ValueError(
|
|
||||||
f"Recalbox's {self.native_filename()} does not parse ({exc}); "
|
|
||||||
"fetch it again with --refresh-cache"
|
|
||||||
) from exc
|
|
||||||
if root is not None:
|
|
||||||
theirs = [
|
|
||||||
(s.get("platform", ""), s.get("fullname", ""), [
|
|
||||||
f"<!--{child.text}-->" if child.tag is Comment else dict(child.attrib)
|
|
||||||
for child in s
|
|
||||||
if child.tag is Comment or child.tag == "bios"
|
|
||||||
])
|
|
||||||
for s in root.iter("system")
|
|
||||||
]
|
|
||||||
|
|
||||||
# Elements of theirs written back as they stand, by (platform, path).
|
# Elements of theirs written back as they stand, by (platform, path).
|
||||||
held = {
|
held = {
|
||||||
@@ -353,24 +407,7 @@ class Exporter(BaseExporter):
|
|||||||
and not self.writable(fe)
|
and not self.writable(fe)
|
||||||
and (system.native_id, " ".join(self._path(fe).split())) in held
|
and (system.native_id, " ".join(self._path(fe).split())) in held
|
||||||
}
|
}
|
||||||
ours: dict[str, tuple[NativeSystem, dict[str, tuple[NativeFile, str]]]] = {}
|
ours = self._our_elements(systems)
|
||||||
for system in systems.values():
|
|
||||||
# Two additions at one path (two cores, two dumps) are one
|
|
||||||
# element: keyed by path, the second replaced the first and its
|
|
||||||
# md5 left the file while both were counted added.
|
|
||||||
at_path: dict[str, list[NativeFile]] = {}
|
|
||||||
for fe in system.files:
|
|
||||||
if self.writable(fe):
|
|
||||||
at_path.setdefault(self._path(fe), []).append(fe)
|
|
||||||
if at_path:
|
|
||||||
ours[system.native_id] = (system, {
|
|
||||||
path: (group[0], self._bios_element(group[0], system.native_id, tuple(group[1:])))
|
|
||||||
for path, group in at_path.items()
|
|
||||||
})
|
|
||||||
|
|
||||||
def element(attrs: dict[str, str]) -> str:
|
|
||||||
rendered = " ".join(f"{k}={quoteattr(v)}" for k, v in attrs.items())
|
|
||||||
return f" <bios {rendered} />"
|
|
||||||
|
|
||||||
def emit(platform: str, fullname: str, body: list[str], opening: str = "") -> None:
|
def emit(platform: str, fullname: str, body: list[str], opening: str = "") -> None:
|
||||||
stated = _stated(opening) if opening else {}
|
stated = _stated(opening) if opening else {}
|
||||||
@@ -392,23 +429,7 @@ class Exporter(BaseExporter):
|
|||||||
for index, (platform, fullname, children) in enumerate(theirs):
|
for index, (platform, fullname, children) in enumerate(theirs):
|
||||||
elements = ours.get(platform, (None, {}))[1]
|
elements = ours.get(platform, (None, {}))[1]
|
||||||
raw = written[index] if index < len(written) else {}
|
raw = written[index] if index < len(written) else {}
|
||||||
body: list[str] = []
|
blocks.append((platform, fullname, _block_body(children, elements, raw)))
|
||||||
for child in children:
|
|
||||||
if isinstance(child, str):
|
|
||||||
body.append(f" {child}")
|
|
||||||
continue
|
|
||||||
path = child.get("path", "")
|
|
||||||
mine = elements.pop(path, None)
|
|
||||||
kept = raw.get(" ".join(path.split()))
|
|
||||||
if kept is not None and (mine is None or _stated(mine[1]) == _stated(kept)):
|
|
||||||
body.append(kept)
|
|
||||||
elif kept is not None and mine is not None and _stated(
|
|
||||||
patched := patch_element(kept, mine[1])
|
|
||||||
) == _stated(mine[1]):
|
|
||||||
body.append(patched)
|
|
||||||
else:
|
|
||||||
body.append(mine[1] if mine else element(child))
|
|
||||||
blocks.append((platform, fullname, body))
|
|
||||||
|
|
||||||
# An addition joins the block named like its file, else the first
|
# An addition joins the block named like its file, else the first
|
||||||
# block of its platform.
|
# block of its platform.
|
||||||
@@ -446,18 +467,20 @@ class Exporter(BaseExporter):
|
|||||||
return [f"the XML does not parse: {exc}"]
|
return [f"the XML does not parse: {exc}"]
|
||||||
|
|
||||||
for element in root.iter("bios"):
|
for element in root.iter("bios"):
|
||||||
for attribute in ("path", "md5", "core"):
|
issues.extend(
|
||||||
if not element.get(attribute):
|
f"es_bios.xsd requires {attribute}: "
|
||||||
issues.append(
|
f"{element.get('path', '?')}"
|
||||||
f"es_bios.xsd requires {attribute}: "
|
for attribute in ("path", "md5", "core")
|
||||||
f"{element.get('path', '?')}"
|
if not element.get(attribute)
|
||||||
)
|
)
|
||||||
for element in root.iter("system"):
|
for element in root.iter("system"):
|
||||||
if not list(element):
|
if not list(element):
|
||||||
issues.append(f"empty system: {element.get('platform', '?')}")
|
issues.append(f"empty system: {element.get('platform', '?')}")
|
||||||
for attribute in ("fullname", "platform"):
|
issues.extend(
|
||||||
if not element.get(attribute):
|
f"es_bios.xsd requires {attribute} on system"
|
||||||
issues.append(f"es_bios.xsd requires {attribute} on system")
|
for attribute in ("fullname", "platform")
|
||||||
|
if not element.get(attribute)
|
||||||
|
)
|
||||||
|
|
||||||
exported = {
|
exported = {
|
||||||
element.get("path", "").casefold() for element in root.iter("bios")
|
element.get("path", "").casefold() for element in root.iter("bios")
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ def keep_blank_lines(original: str, produced: str) -> str:
|
|||||||
return _TOP_KEY.sub(separate, produced)
|
return _TOP_KEY.sub(separate, produced)
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write RetroBat's batocera-systems.json, corrected."""
|
"""Write RetroBat's batocera-systems.json, corrected."""
|
||||||
|
|
||||||
# One md5 per entry, compared as Batocera's checkBios does.
|
# One md5 per entry, compared as Batocera's checkBios does.
|
||||||
@@ -152,9 +152,10 @@ class Exporter(BaseExporter):
|
|||||||
if fe.platform is not None and fe.platform.get("required") is False:
|
if fe.platform is not None and fe.platform.get("required") is False:
|
||||||
entry["optional"] = True
|
entry["optional"] = True
|
||||||
ours.setdefault(path, entry)
|
ours.setdefault(path, entry)
|
||||||
bios_files = []
|
bios_files = [
|
||||||
for theirs in (base.get(key) or {}).get("biosFiles", []):
|
ours.pop(theirs.get("file"), theirs)
|
||||||
bios_files.append(ours.pop(theirs.get("file"), theirs))
|
for theirs in (base.get(key) or {}).get("biosFiles", [])
|
||||||
|
]
|
||||||
bios_files.extend(ours.values())
|
bios_files.extend(ours.values())
|
||||||
system_entry: OrderedDict[str, object] = OrderedDict()
|
system_entry: OrderedDict[str, object] = OrderedDict()
|
||||||
system_entry["name"] = self.display_name(system)
|
system_entry["name"] = self.display_name(system)
|
||||||
@@ -181,11 +182,13 @@ class Exporter(BaseExporter):
|
|||||||
issues.append(f"system without a name: {key}")
|
issues.append(f"system without a name: {key}")
|
||||||
if not entry.get("biosFiles"):
|
if not entry.get("biosFiles"):
|
||||||
issues.append(f"empty entry: {key}")
|
issues.append(f"empty entry: {key}")
|
||||||
for bios in entry.get("biosFiles", []):
|
# RetroBat states an unhashed file with an empty md5, so only
|
||||||
# RetroBat states an unhashed file with an empty md5, so only
|
# a missing path makes an entry unusable.
|
||||||
# a missing path makes an entry unusable.
|
issues.extend(
|
||||||
if "md5" not in bios or not bios.get("file"):
|
f"incomplete entry: {key}/{bios.get('file', '?')}"
|
||||||
issues.append(f"incomplete entry: {key}/{bios.get('file', '?')}")
|
for bios in entry.get("biosFiles", [])
|
||||||
|
if "md5" not in bios or not bios.get("file")
|
||||||
|
)
|
||||||
|
|
||||||
for system, files in self.exportable(systems, require="md5"):
|
for system, files in self.exportable(systems, require="md5"):
|
||||||
entry = data.get(system.native_id)
|
entry = data.get(system.native_id)
|
||||||
@@ -193,7 +196,9 @@ class Exporter(BaseExporter):
|
|||||||
issues.append(f"system absent: {system.native_id}")
|
issues.append(f"system absent: {system.native_id}")
|
||||||
continue
|
continue
|
||||||
declared = {bios.get("file") for bios in entry.get("biosFiles", [])}
|
declared = {bios.get("file") for bios in entry.get("biosFiles", [])}
|
||||||
for fe in files:
|
issues.extend(
|
||||||
if self._path(fe) not in declared:
|
f"absent: {system.native_id}/{fe.name}"
|
||||||
issues.append(f"absent: {system.native_id}/{fe.name}")
|
for fe in files
|
||||||
|
if self._path(fe) not in declared
|
||||||
|
)
|
||||||
return issues
|
return issues
|
||||||
@@ -62,7 +62,7 @@ def _matching_keys(
|
|||||||
return named if len(named) == 1 else []
|
return named if len(named) == 1 else []
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write RetroDECK's component manifests, corrected."""
|
"""Write RetroDECK's component manifests, corrected."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -83,8 +83,7 @@ class Exporter(BaseExporter):
|
|||||||
# one from BIOS data alone would throw the component away.
|
# one from BIOS data alone would throw the component away.
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@classmethod
|
def writable(self, fe: NativeFile, require: str = "") -> bool:
|
||||||
def writable(cls, fe: NativeFile, require: str = "") -> bool:
|
|
||||||
"""An addition lands only in a manifest it can be placed in."""
|
"""An addition lands only in a manifest it can be placed in."""
|
||||||
if fe.platform is None and not fe.native("component", ""):
|
if fe.platform is None and not fe.native("component", ""):
|
||||||
return False
|
return False
|
||||||
@@ -229,10 +228,10 @@ class Exporter(BaseExporter):
|
|||||||
# ATARIOSB.ROM for atari5200 and atari800 with different md5 lists,
|
# ATARIOSB.ROM for atari5200 and atari800 with different md5 lists,
|
||||||
# and a name-only key wrote the first of ours over both.
|
# and a name-only key wrote the first of ours over both.
|
||||||
by_key: OrderedDict[tuple[str, str], OrderedDict] = OrderedDict()
|
by_key: OrderedDict[tuple[str, str], OrderedDict] = OrderedDict()
|
||||||
for entry in ours:
|
for own in ours:
|
||||||
key = (str(entry.get("filename", "")), str(entry.get("system", "")))
|
key = (str(own.get("filename", "")), str(own.get("system", "")))
|
||||||
if key[0] and key not in by_key:
|
if key[0] and key not in by_key:
|
||||||
by_key[key] = entry
|
by_key[key] = own
|
||||||
|
|
||||||
merged: list[OrderedDict] = []
|
merged: list[OrderedDict] = []
|
||||||
corrected: set[tuple[str, str]] = set()
|
corrected: set[tuple[str, str]] = set()
|
||||||
@@ -261,31 +260,7 @@ class Exporter(BaseExporter):
|
|||||||
if other_revision or not keys:
|
if other_revision or not keys:
|
||||||
merged.append(OrderedDict(entry))
|
merged.append(OrderedDict(entry))
|
||||||
continue
|
continue
|
||||||
declared = entry.get("system")
|
merged.append(cls._corrected(entry, by_key[keys[0]]))
|
||||||
combined = OrderedDict(entry)
|
|
||||||
# Only what the format says it corrects: the maintainer's
|
|
||||||
# description and search paths are theirs (neogeo.zip lost its
|
|
||||||
# four roms directories to a path that does not exist).
|
|
||||||
combined.update(
|
|
||||||
(field, value) for field, value in by_key[keys[0]].items()
|
|
||||||
if field in cls.carries() and not (field == "system" and declared)
|
|
||||||
)
|
|
||||||
# A hash of theirs that ours no longer carries is one the truth
|
|
||||||
# contradicts: kept, it went on rejecting the dump the emulator
|
|
||||||
# loads while the summary counted it cleared.
|
|
||||||
for field in ("md5", "sha256"):
|
|
||||||
if field in cls.carries() and field not in by_key[keys[0]]:
|
|
||||||
combined.pop(field, None)
|
|
||||||
if _md5_set(entry.get("md5")) == _md5_set(combined.get("md5")):
|
|
||||||
# Their own spelling, and no key where they wrote none: an
|
|
||||||
# equal empty set wrote "md5": null 39 times.
|
|
||||||
if "md5" in entry:
|
|
||||||
combined["md5"] = entry["md5"]
|
|
||||||
else:
|
|
||||||
combined.pop("md5", None)
|
|
||||||
elif isinstance(entry.get("md5"), list) and isinstance(combined.get("md5"), str):
|
|
||||||
combined["md5"] = [combined["md5"]]
|
|
||||||
merged.append(combined)
|
|
||||||
corrected.update(keys)
|
corrected.update(keys)
|
||||||
|
|
||||||
uncorrected = [key for key in by_key if key not in corrected]
|
uncorrected = [key for key in by_key if key not in corrected]
|
||||||
@@ -302,15 +277,47 @@ class Exporter(BaseExporter):
|
|||||||
for e in merged
|
for e in merged
|
||||||
for system in (_systems_of(e) or [""])
|
for system in (_systems_of(e) or [""])
|
||||||
}
|
}
|
||||||
for index, entry in enumerate(additions or []):
|
for index, addition in enumerate(additions or []):
|
||||||
key = (str(entry.get("filename", "")), str(entry.get("system", "")), _paths_key(entry))
|
slot = (
|
||||||
if key[0] and key not in held:
|
str(addition.get("filename", "")), str(addition.get("system", "")),
|
||||||
held.add(key)
|
_paths_key(addition),
|
||||||
merged.append(entry)
|
)
|
||||||
|
if slot[0] and slot not in held:
|
||||||
|
held.add(slot)
|
||||||
|
merged.append(addition)
|
||||||
elif held_back is not None:
|
elif held_back is not None:
|
||||||
held_back.append(index)
|
held_back.append(index)
|
||||||
return merged
|
return merged
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _corrected(cls, entry: dict, own: OrderedDict) -> OrderedDict:
|
||||||
|
"""The platform's entry with the fields ours corrects."""
|
||||||
|
declared = entry.get("system")
|
||||||
|
combined = OrderedDict(entry)
|
||||||
|
# Only what the format says it corrects: the maintainer's
|
||||||
|
# description and search paths are theirs (neogeo.zip lost its
|
||||||
|
# four roms directories to a path that does not exist).
|
||||||
|
combined.update(
|
||||||
|
(field, value) for field, value in own.items()
|
||||||
|
if field in cls.carries() and not (field == "system" and declared)
|
||||||
|
)
|
||||||
|
# A hash of theirs that ours no longer carries is one the truth
|
||||||
|
# contradicts: kept, it went on rejecting the dump the emulator
|
||||||
|
# loads while the summary counted it cleared.
|
||||||
|
for field in ("md5", "sha256"):
|
||||||
|
if field in cls.carries() and field not in own:
|
||||||
|
combined.pop(field, None)
|
||||||
|
if _md5_set(entry.get("md5")) == _md5_set(combined.get("md5")):
|
||||||
|
# Their own spelling, and no key where they wrote none: an
|
||||||
|
# equal empty set wrote "md5": null 39 times.
|
||||||
|
if "md5" in entry:
|
||||||
|
combined["md5"] = entry["md5"]
|
||||||
|
else:
|
||||||
|
combined.pop("md5", None)
|
||||||
|
elif isinstance(entry.get("md5"), list) and isinstance(combined.get("md5"), str):
|
||||||
|
combined["md5"] = [combined["md5"]]
|
||||||
|
return combined
|
||||||
|
|
||||||
def lands(self, fe: NativeFile) -> bool:
|
def lands(self, fe: NativeFile) -> bool:
|
||||||
"""An addition the list already held is not written a second time."""
|
"""An addition the list already held is not written a second time."""
|
||||||
return self.writable(fe) and id(fe) not in getattr(self, "_held_back", set())
|
return self.writable(fe) and id(fe) not in getattr(self, "_held_back", set())
|
||||||
|
|||||||
@@ -53,7 +53,13 @@ _SEPARATOR = re.compile(r"\s*(?:,\s*(?:and\s+)?|and\s+)")
|
|||||||
_EXAMPLES = re.compile(r"\b(?:e\.?g\b|for example|for instance|such as|like)\W*$", re.I)
|
_EXAMPLES = re.compile(r"\b(?:e\.?g\b|for example|for instance|such as|like)\W*$", re.I)
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
def _aliases(fe: NativeFile) -> list[object]:
|
||||||
|
"""The other names a file is declared under."""
|
||||||
|
aliases = fe.native("aliases", []) or []
|
||||||
|
return list(aliases) if isinstance(aliases, (list, tuple)) else []
|
||||||
|
|
||||||
|
|
||||||
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write RetroPie's scriptmodules, corrected."""
|
"""Write RetroPie's scriptmodules, corrected."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -332,108 +338,124 @@ class Exporter(BaseExporter):
|
|||||||
systems_of: dict[str, set[str]] = {}
|
systems_of: dict[str, set[str]] = {}
|
||||||
for system in systems.values():
|
for system in systems.values():
|
||||||
for fe in system.files:
|
for fe in system.files:
|
||||||
for name in [fe.name, *(fe.native("aliases", []) or [])]:
|
for name in [fe.name, *_aliases(fe)]:
|
||||||
systems_of.setdefault(str(name).lower(), set()).add(fe.native_system)
|
systems_of.setdefault(str(name).lower(), set()).add(fe.native_system)
|
||||||
known = set(systems_of)
|
|
||||||
self._skipped: dict[str, list[str]] = {}
|
self._skipped: dict[str, list[str]] = {}
|
||||||
# Rewritten, with a file of a system no clause lists left out.
|
# Rewritten, with a file of a system no clause lists left out.
|
||||||
self._partial: list[str] = []
|
self._partial: list[str] = []
|
||||||
self._named: set[int] = set()
|
self._named: set[int] = set()
|
||||||
produced: dict[str, str] = {}
|
produced: dict[str, str] = {}
|
||||||
|
|
||||||
def skip(reason: str, module: str) -> None:
|
|
||||||
self._skipped.setdefault(reason, []).append(module)
|
|
||||||
|
|
||||||
for relative, (module_id, help_text) in sorted(modules.items()):
|
for relative, (module_id, help_text) in sorted(modules.items()):
|
||||||
build = "libretro" if module_id.startswith("lr-") else "standalone"
|
build = "libretro" if module_id.startswith("lr-") else "standalone"
|
||||||
core = index[build].get(module_id.removeprefix("lr-").replace("-", "_").lower())
|
core = index[build].get(module_id.removeprefix("lr-").replace("-", "_").lower())
|
||||||
files = by_core.get(core or "", [])
|
files = by_core.get(core or "", [])
|
||||||
if not files:
|
if not files:
|
||||||
skip("which no profiled core matches", module_id)
|
self._skip("which no profiled core matches", module_id)
|
||||||
continue
|
continue
|
||||||
|
new_help = self._new_help(module_id, help_text, files, core, systems_of)
|
||||||
listed = self._listed(help_text)
|
if new_help is None:
|
||||||
unknown = sorted(listed - known)
|
|
||||||
if unknown:
|
|
||||||
skip(
|
|
||||||
f"whose help text names a file no profile documents yet ({', '.join(unknown)})",
|
|
||||||
module_id,
|
|
||||||
)
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# A file already listed under one of its other names is not
|
|
||||||
# missing: proposing the primary would name the same bytes twice.
|
|
||||||
# A system RetroPie does not have is no package's: lr-geargrafx
|
|
||||||
# adds pcengine only, not the LaserActive its core also reads.
|
|
||||||
candidates = [
|
|
||||||
fe
|
|
||||||
for fe in files
|
|
||||||
if not fe.foreign_system
|
|
||||||
and self._required_for(fe, core)
|
|
||||||
and not (
|
|
||||||
{fe.name.lower()}
|
|
||||||
| {str(a).lower() for a in (fe.native("aliases", []) or [])}
|
|
||||||
)
|
|
||||||
& listed
|
|
||||||
]
|
|
||||||
filled = {
|
|
||||||
slot
|
|
||||||
for fe in files
|
|
||||||
if ({fe.name.lower()}
|
|
||||||
| {str(a).lower() for a in (fe.native("aliases", []) or [])}) & listed
|
|
||||||
and (slot := self._slot_of(fe)) is not None
|
|
||||||
}
|
|
||||||
proposed = self._one_per_slot(candidates, filled)
|
|
||||||
if not proposed:
|
|
||||||
continue
|
|
||||||
|
|
||||||
# A file joins the list of its own system: the clause whose
|
|
||||||
# names the platform files under that system, and only one.
|
|
||||||
clauses = self._clauses(help_text)
|
|
||||||
homes: dict[int, list[NativeFile]] = {}
|
|
||||||
homeless = False
|
|
||||||
for fe in proposed:
|
|
||||||
owners = [
|
|
||||||
i for i, (_, names, _) in enumerate(clauses)
|
|
||||||
if fe.native_system in set().union(
|
|
||||||
*(systems_of.get(n.lower(), set()) for n in names))
|
|
||||||
]
|
|
||||||
if len(owners) == 1 and clauses[owners[0]][2] is not None:
|
|
||||||
homes.setdefault(owners[0], []).append(fe)
|
|
||||||
else:
|
|
||||||
homeless = True
|
|
||||||
# No enumeration of that system to extend, and a sentence we
|
|
||||||
# would have to write ourselves is a documentation change, not a
|
|
||||||
# correction. With nothing placed the package is left as is.
|
|
||||||
if not homes:
|
|
||||||
skip("whose help text lists no files of that system to add to", module_id)
|
|
||||||
continue
|
|
||||||
|
|
||||||
added = sum(len(self._in_search_order(fes)) for fes in homes.values())
|
|
||||||
if len(listed) + added > self._longest:
|
|
||||||
skip("whose help text would grow longer than any it has today", module_id)
|
|
||||||
continue
|
|
||||||
|
|
||||||
new_help = help_text
|
|
||||||
for i in sorted(homes, reverse=True):
|
|
||||||
start, _, enumeration = clauses[i]
|
|
||||||
missing = self._in_search_order(homes[i])
|
|
||||||
new_help = self._extended(new_help, enumeration, missing)
|
|
||||||
if len(enumeration[2]) + len(missing) > 1:
|
|
||||||
new_help = new_help[:start] + _BIOS_NOUN.sub(
|
|
||||||
r"\1 files", new_help[start:enumeration[0]], count=1
|
|
||||||
) + new_help[enumeration[0]:]
|
|
||||||
self._named.update(id(fe) for fe in homes[i])
|
|
||||||
produced[relative] = originals[relative].replace(
|
produced[relative] = originals[relative].replace(
|
||||||
f'rp_module_help="{help_text}"',
|
f'rp_module_help="{help_text}"',
|
||||||
f'rp_module_help="{new_help}"',
|
f'rp_module_help="{new_help}"',
|
||||||
1,
|
1,
|
||||||
)
|
)
|
||||||
if homeless:
|
|
||||||
self._partial.append(module_id)
|
|
||||||
|
|
||||||
return produced
|
return produced
|
||||||
|
|
||||||
|
def _skip(self, reason: str, module: str) -> None:
|
||||||
|
self._skipped.setdefault(reason, []).append(module)
|
||||||
|
|
||||||
|
def _new_help(
|
||||||
|
self,
|
||||||
|
module_id: str,
|
||||||
|
help_text: str,
|
||||||
|
files: list[NativeFile],
|
||||||
|
core: str | None,
|
||||||
|
systems_of: dict[str, set[str]],
|
||||||
|
) -> str | None:
|
||||||
|
"""The help sentence with the files it lacks, None when left as is."""
|
||||||
|
listed = self._listed(help_text)
|
||||||
|
unknown = sorted(listed - set(systems_of))
|
||||||
|
if unknown:
|
||||||
|
self._skip(
|
||||||
|
f"whose help text names a file no profile documents yet ({', '.join(unknown)})",
|
||||||
|
module_id,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# A file already listed under one of its other names is not
|
||||||
|
# missing: proposing the primary would name the same bytes twice.
|
||||||
|
# A system RetroPie does not have is no package's: lr-geargrafx
|
||||||
|
# adds pcengine only, not the LaserActive its core also reads.
|
||||||
|
candidates = [
|
||||||
|
fe
|
||||||
|
for fe in files
|
||||||
|
if not fe.foreign_system
|
||||||
|
and self._required_for(fe, core)
|
||||||
|
and not (
|
||||||
|
{fe.name.lower()}
|
||||||
|
| {str(a).lower() for a in _aliases(fe)}
|
||||||
|
)
|
||||||
|
& listed
|
||||||
|
]
|
||||||
|
filled = {
|
||||||
|
slot
|
||||||
|
for fe in files
|
||||||
|
if ({fe.name.lower()}
|
||||||
|
| {str(a).lower() for a in _aliases(fe)}) & listed
|
||||||
|
and (slot := self._slot_of(fe)) is not None
|
||||||
|
}
|
||||||
|
proposed = self._one_per_slot(candidates, filled)
|
||||||
|
if not proposed:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# A file joins the list of its own system: the clause whose
|
||||||
|
# names the platform files under that system, and only one.
|
||||||
|
clauses = self._clauses(help_text)
|
||||||
|
homes: dict[int, list[NativeFile]] = {}
|
||||||
|
enumerations: dict[int, tuple[int, int, list[str]]] = {}
|
||||||
|
homeless = False
|
||||||
|
for fe in proposed:
|
||||||
|
owners = [
|
||||||
|
i for i, (_, names, _) in enumerate(clauses)
|
||||||
|
if fe.native_system in set().union(
|
||||||
|
*(systems_of.get(n.lower(), set()) for n in names))
|
||||||
|
]
|
||||||
|
enumeration = clauses[owners[0]][2] if len(owners) == 1 else None
|
||||||
|
if enumeration is not None:
|
||||||
|
homes.setdefault(owners[0], []).append(fe)
|
||||||
|
enumerations[owners[0]] = enumeration
|
||||||
|
else:
|
||||||
|
homeless = True
|
||||||
|
# No enumeration of that system to extend, and a sentence we
|
||||||
|
# would have to write ourselves is a documentation change, not a
|
||||||
|
# correction. With nothing placed the package is left as is.
|
||||||
|
if not homes:
|
||||||
|
self._skip("whose help text lists no files of that system to add to", module_id)
|
||||||
|
return None
|
||||||
|
|
||||||
|
added = sum(len(self._in_search_order(fes)) for fes in homes.values())
|
||||||
|
if len(listed) + added > self._longest:
|
||||||
|
self._skip("whose help text would grow longer than any it has today", module_id)
|
||||||
|
return None
|
||||||
|
|
||||||
|
new_help = help_text
|
||||||
|
for i in sorted(homes, reverse=True):
|
||||||
|
start = clauses[i][0]
|
||||||
|
enumeration = enumerations[i]
|
||||||
|
missing = self._in_search_order(homes[i])
|
||||||
|
new_help = self._extended(new_help, enumeration, missing)
|
||||||
|
if len(enumeration[2]) + len(missing) > 1:
|
||||||
|
new_help = new_help[:start] + _BIOS_NOUN.sub(
|
||||||
|
r"\1 files", new_help[start:enumeration[0]], count=1
|
||||||
|
) + new_help[enumeration[0]:]
|
||||||
|
self._named.update(id(fe) for fe in homes[i])
|
||||||
|
if homeless:
|
||||||
|
self._partial.append(module_id)
|
||||||
|
return new_help
|
||||||
|
|
||||||
def lands(self, fe: NativeFile) -> bool:
|
def lands(self, fe: NativeFile) -> bool:
|
||||||
"""An addition lands only where a help sentence now names it.
|
"""An addition lands only where a help sentence now names it.
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ SOURCE_URL = (
|
|||||||
_FIELDS = (("size", "size"), ("crc", "crc32"), ("md5", "md5"), ("sha1", "sha1"))
|
_FIELDS = (("size", "size"), ("crc", "crc32"), ("md5", "md5"), ("sha1", "sha1"))
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write RomM's known_bios_files.json, corrected."""
|
"""Write RomM's known_bios_files.json, corrected."""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
|
|||||||
@@ -77,7 +77,25 @@ def _sections(original: str) -> list[tuple[str, list[str]]]:
|
|||||||
return sections
|
return sections
|
||||||
|
|
||||||
|
|
||||||
class Exporter(BaseExporter):
|
def _rom_fields(fe: NativeFile, name: str) -> list[str]:
|
||||||
|
"""The fields of a rom line, in the order clrmamepro writes them."""
|
||||||
|
parts = [f"name {name}"]
|
||||||
|
size = fe.size()
|
||||||
|
if size:
|
||||||
|
parts.append(f"size {size}")
|
||||||
|
crc = fe.record_hash("crc32")
|
||||||
|
if crc:
|
||||||
|
parts.append(f"crc {crc.upper()}")
|
||||||
|
md5 = fe.record_hash("md5")
|
||||||
|
if md5:
|
||||||
|
parts.append(f"md5 {md5}")
|
||||||
|
sha1 = fe.record_hash("sha1")
|
||||||
|
if sha1:
|
||||||
|
parts.append(f"sha1 {sha1}")
|
||||||
|
return parts
|
||||||
|
|
||||||
|
|
||||||
|
class Exporter(BaseExporter[str]):
|
||||||
"""Write libretro's System.dat, corrected."""
|
"""Write libretro's System.dat, corrected."""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -96,8 +114,7 @@ class Exporter(BaseExporter):
|
|||||||
def native_sources() -> dict[str, str]:
|
def native_sources() -> dict[str, str]:
|
||||||
return {"System.dat": SOURCE_URL}
|
return {"System.dat": SOURCE_URL}
|
||||||
|
|
||||||
@classmethod
|
def writable(self, fe: NativeFile, require: str = "") -> bool:
|
||||||
def writable(cls, fe: NativeFile, require: str = "") -> bool:
|
|
||||||
"""A clrmamepro rom line is a hash record, and the DAT has no other.
|
"""A clrmamepro rom line is a hash record, and the DAT has no other.
|
||||||
|
|
||||||
The original never states a rom it cannot hash, so neither do we.
|
The original never states a rom it cannot hash, so neither do we.
|
||||||
@@ -184,19 +201,7 @@ class Exporter(BaseExporter):
|
|||||||
if not any(fe.hash(h) for h in ("crc32", "md5", "sha1")):
|
if not any(fe.hash(h) for h in ("crc32", "md5", "sha1")):
|
||||||
continue
|
continue
|
||||||
name = _quote(self._rom_name(fe), quoted)
|
name = _quote(self._rom_name(fe), quoted)
|
||||||
parts = [f"name {name}"]
|
parts = _rom_fields(fe, name)
|
||||||
size = fe.size()
|
|
||||||
if size:
|
|
||||||
parts.append(f"size {size}")
|
|
||||||
crc = fe.record_hash("crc32")
|
|
||||||
if crc:
|
|
||||||
parts.append(f"crc {crc.upper()}")
|
|
||||||
md5 = fe.record_hash("md5")
|
|
||||||
if md5:
|
|
||||||
parts.append(f"md5 {md5}")
|
|
||||||
sha1 = fe.record_hash("sha1")
|
|
||||||
if sha1:
|
|
||||||
parts.append(f"sha1 {sha1}")
|
|
||||||
if name in rendered:
|
if name in rendered:
|
||||||
if fe.platform is None:
|
if fe.platform is None:
|
||||||
self._shadowed.add(id(fe))
|
self._shadowed.add(id(fe))
|
||||||
|
|||||||
+6
-4
@@ -139,10 +139,12 @@ def without_game_data(
|
|||||||
))
|
))
|
||||||
systems[sys_id] = {**system, "files": kept} if len(kept) != len(files) else system
|
systems[sys_id] = {**system, "files": kept} if len(kept) != len(files) else system
|
||||||
|
|
||||||
for key in examined:
|
left_out.extend(
|
||||||
for fe in profiles[key].get("files") or []:
|
LeftOut("core", "", str(fe.get("name") or ""), (key,))
|
||||||
if isinstance(fe, dict) and is_game_data(fe):
|
for key in examined
|
||||||
left_out.append(LeftOut("core", "", str(fe.get("name") or ""), (key,)))
|
for fe in profiles[key].get("files") or []
|
||||||
|
if isinstance(fe, dict) and is_game_data(fe)
|
||||||
|
)
|
||||||
|
|
||||||
stripped = {
|
stripped = {
|
||||||
key: (
|
key: (
|
||||||
|
|||||||
+53
-32
@@ -568,6 +568,16 @@ def launcher_unproven(
|
|||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _place_paths(name: str, directories: list[str] | None) -> tuple[str, ...]:
|
||||||
|
"""The paths a name is opened at: under each directory, or bare when the
|
||||||
|
record anchors it nowhere."""
|
||||||
|
if directories is None:
|
||||||
|
return (name,)
|
||||||
|
return tuple(
|
||||||
|
sanitize_pack_path(f"{d}/{name}" if d else name) for d in directories
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def launcher_places(
|
def launcher_places(
|
||||||
config: dict, profiles: Mapping[str, dict] | None = None
|
config: dict, profiles: Mapping[str, dict] | None = None
|
||||||
) -> list[LauncherPlace]:
|
) -> list[LauncherPlace]:
|
||||||
@@ -583,14 +593,6 @@ def launcher_places(
|
|||||||
if not names or directories == []:
|
if not names or directories == []:
|
||||||
continue
|
continue
|
||||||
anchored = directories is not None
|
anchored = directories is not None
|
||||||
|
|
||||||
def paths_of(name: str) -> tuple[str, ...]:
|
|
||||||
if not anchored:
|
|
||||||
return (name,)
|
|
||||||
return tuple(
|
|
||||||
sanitize_pack_path(f"{d}/{name}" if d else name) for d in directories
|
|
||||||
)
|
|
||||||
|
|
||||||
common = {
|
common = {
|
||||||
"emulator": str(record.get("emulator", "")),
|
"emulator": str(record.get("emulator", "")),
|
||||||
"build": str(record.get("build", "")),
|
"build": str(record.get("build", "")),
|
||||||
@@ -607,8 +609,10 @@ def launcher_places(
|
|||||||
settings = name_settings(record, names)
|
settings = name_settings(record, names)
|
||||||
if kind == "names_searched":
|
if kind == "names_searched":
|
||||||
# Each directory in turn, every name in it.
|
# Each directory in turn, every name in it.
|
||||||
depth = len(directories) if anchored else 1
|
depth = len(directories) if directories is not None else 1
|
||||||
ordered = tuple(paths_of(name)[i] for i in range(depth) for name in names)
|
ordered = tuple(
|
||||||
|
_place_paths(name, directories)[i] for i in range(depth) for name in names
|
||||||
|
)
|
||||||
places.append(LauncherPlace(
|
places.append(LauncherPlace(
|
||||||
paths=ordered, passes_to=str(record.get("passes_to") or ""), **common
|
paths=ordered, passes_to=str(record.get("passes_to") or ""), **common
|
||||||
))
|
))
|
||||||
@@ -616,7 +620,9 @@ def launcher_places(
|
|||||||
# A fixed name is the one file passed, and a core option offers
|
# A fixed name is the one file passed, and a core option offers
|
||||||
# each value as the file the user picks: one place per name.
|
# each value as the file the user picks: one place per name.
|
||||||
places.extend(
|
places.extend(
|
||||||
LauncherPlace(paths=paths_of(name), passes_to=settings[name], **common)
|
LauncherPlace(
|
||||||
|
paths=_place_paths(name, directories), passes_to=settings[name], **common
|
||||||
|
)
|
||||||
for name in names
|
for name in names
|
||||||
)
|
)
|
||||||
return places
|
return places
|
||||||
@@ -852,8 +858,8 @@ def handed_directories(
|
|||||||
if (handle := normalize_handle(token, home)) and handle != directory
|
if (handle := normalize_handle(token, home)) and handle != directory
|
||||||
) | ini_keys(passes_to)
|
) | ini_keys(passes_to)
|
||||||
folder = _folder_in_bios(part, base)
|
folder = _folder_in_bios(part, base)
|
||||||
for emulator in (e.strip() for e in str(record.get("emulator", "")).split(",")):
|
found.extend(
|
||||||
found.append(HandedDirectory(
|
HandedDirectory(
|
||||||
emulator=emulator,
|
emulator=emulator,
|
||||||
folder=folder,
|
folder=folder,
|
||||||
directory=directory,
|
directory=directory,
|
||||||
@@ -868,7 +874,9 @@ def handed_directories(
|
|||||||
holds_declared=bool(folder) and any(
|
holds_declared=bool(folder) and any(
|
||||||
d.startswith(f"{(folder or '').lower()}/") for d in declared
|
d.startswith(f"{(folder or '').lower()}/") for d in declared
|
||||||
),
|
),
|
||||||
))
|
)
|
||||||
|
for emulator in (e.strip() for e in str(record.get("emulator", "")).split(","))
|
||||||
|
)
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
@@ -999,10 +1007,12 @@ def executed_files(config: dict) -> list[ExecutedFile]:
|
|||||||
place = (EMULATORS_TREE, sanitize_pack_path(f"{emulator_folder}/{name}"))
|
place = (EMULATORS_TREE, sanitize_pack_path(f"{emulator_folder}/{name}"))
|
||||||
else:
|
else:
|
||||||
place = None
|
place = None
|
||||||
for emulator in (e.strip() for e in str(record.get("emulator", "")).split(",")):
|
found.extend(
|
||||||
found.append(ExecutedFile(
|
ExecutedFile(
|
||||||
emulator, name.rsplit("/", 1)[-1], place, str(record.get("source_ref", ""))
|
emulator, name.rsplit("/", 1)[-1], place, str(record.get("source_ref", ""))
|
||||||
))
|
)
|
||||||
|
for emulator in (e.strip() for e in str(record.get("emulator", "")).split(","))
|
||||||
|
)
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
@@ -1440,6 +1450,26 @@ class LauncherLayer:
|
|||||||
pool = self.declared_names_folded if place.case_insensitive else self.declared_names
|
pool = self.declared_names_folded if place.case_insensitive else self.declared_names
|
||||||
return bool(place.basenames() & pool)
|
return bool(place.basenames() & pool)
|
||||||
|
|
||||||
|
def _add_unoffered(
|
||||||
|
self,
|
||||||
|
by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]],
|
||||||
|
offered: set[int],
|
||||||
|
resolve_held: Callable[[dict], dict | None],
|
||||||
|
) -> None:
|
||||||
|
"""The entries the report left out, each answering only through a
|
||||||
|
launcher's setting or extended name."""
|
||||||
|
for layout, members in self._unoffered.items():
|
||||||
|
for entry, report in members:
|
||||||
|
if id(entry) in offered:
|
||||||
|
continue
|
||||||
|
if "<" not in str(entry.get("name", "")):
|
||||||
|
report["in_repo"] = resolve_held(report) is not None
|
||||||
|
report["unoffered"] = True
|
||||||
|
if (*layout, str(entry.get("name", "")),
|
||||||
|
str(entry.get("path") or "")) in self._declared_elsewhere:
|
||||||
|
report["declared_elsewhere"] = True
|
||||||
|
by_layout.setdefault(layout, []).append((entry, report))
|
||||||
|
|
||||||
def settle(
|
def settle(
|
||||||
self,
|
self,
|
||||||
candidates: list[tuple[str, bool, dict, dict]],
|
candidates: list[tuple[str, bool, dict, dict]],
|
||||||
@@ -1470,18 +1500,9 @@ class LauncherLayer:
|
|||||||
by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]] = {}
|
by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]] = {}
|
||||||
for emulator, standalone, entry, report in candidates:
|
for emulator, standalone, entry, report in candidates:
|
||||||
by_layout.setdefault((emulator, standalone), []).append((entry, report))
|
by_layout.setdefault((emulator, standalone), []).append((entry, report))
|
||||||
offered = {id(entry) for _e, _s, entry, _r in candidates}
|
self._add_unoffered(
|
||||||
for layout, members in self._unoffered.items():
|
by_layout, {id(entry) for _e, _s, entry, _r in candidates}, resolve_held,
|
||||||
for entry, report in members:
|
)
|
||||||
if id(entry) in offered:
|
|
||||||
continue
|
|
||||||
if "<" not in str(entry.get("name", "")):
|
|
||||||
report["in_repo"] = resolve_held(report) is not None
|
|
||||||
report["unoffered"] = True
|
|
||||||
if (*layout, str(entry.get("name", "")),
|
|
||||||
str(entry.get("path") or "")) in self._declared_elsewhere:
|
|
||||||
report["declared_elsewhere"] = True
|
|
||||||
by_layout.setdefault(layout, []).append((entry, report))
|
|
||||||
placed: set[str] = set()
|
placed: set[str] = set()
|
||||||
for (emulator, standalone), members in sorted(by_layout.items()):
|
for (emulator, standalone), members in sorted(by_layout.items()):
|
||||||
for place in self.places_for(emulator, standalone):
|
for place in self.places_for(emulator, standalone):
|
||||||
@@ -1621,9 +1642,9 @@ class LauncherLayer:
|
|||||||
continue
|
continue
|
||||||
if not report.get("in_repo"):
|
if not report.get("in_repo"):
|
||||||
continue
|
continue
|
||||||
record = resolve_held(report)
|
held = resolve_held(report)
|
||||||
if record is not None:
|
if held is not None:
|
||||||
return report, record
|
return report, held
|
||||||
for candidate, report in matched:
|
for candidate, report in matched:
|
||||||
if key not in candidate.names or not set_by(candidate.entry, place.passes_to):
|
if key not in candidate.names or not set_by(candidate.entry, place.passes_to):
|
||||||
continue
|
continue
|
||||||
|
|||||||
+3
-2
@@ -403,8 +403,9 @@ def resolve_region_drops(
|
|||||||
for destination, name in members
|
for destination, name in members
|
||||||
if destination in rivals
|
if destination in rivals
|
||||||
]
|
]
|
||||||
known = None not in world_ranks
|
ranked = [rank for rank in world_ranks if rank is not None]
|
||||||
best_world = min(world_ranks) if known and world_ranks else None
|
known = len(ranked) == len(world_ranks)
|
||||||
|
best_world = min(ranked) if known and ranked else None
|
||||||
for _r, destination in regional:
|
for _r, destination in regional:
|
||||||
name = next(n for d, n in members if d == destination)
|
name = next(n for d, n in members if d == destination)
|
||||||
ours = lookup_priority(index, destination, name)
|
ours = lookup_priority(index, destination, name)
|
||||||
|
|||||||
+1
-1
@@ -193,7 +193,7 @@ def resolve_slot_drops(
|
|||||||
keep.update(dest for dest, _p in candidates)
|
keep.update(dest for dest, _p in candidates)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
best = min(p for _d, p in candidates)
|
best = min(p for _d, p in candidates if p is not None)
|
||||||
winners = [dest for dest, p in candidates if p == best]
|
winners = [dest for dest, p in candidates if p == best]
|
||||||
if len(winners) != 1:
|
if len(winners) != 1:
|
||||||
undecidable.append(f"{group_id}|{','.join(tier)}" if tier else group_id)
|
undecidable.append(f"{group_id}|{','.join(tier)}" if tier else group_id)
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ def _size_the_code_reads(entry: dict, local: str | None) -> bool:
|
|||||||
except OSError:
|
except OSError:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
# A core that reads ROMs inside an archive proves the archive by its members:
|
# A core that reads ROMs inside an archive proves the archive by its members:
|
||||||
# FBNeo's neocdz.zip is any copy holding neocd.bin and 000-lo.lo by crc.
|
# FBNeo's neocdz.zip is any copy holding neocd.bin and 000-lo.lo by crc.
|
||||||
MEMBERS_HELD = "members_held"
|
MEMBERS_HELD = "members_held"
|
||||||
|
|||||||
+188
-165
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|||||||
import copy
|
import copy
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from common import (
|
from common import (
|
||||||
@@ -30,9 +31,9 @@ from validation import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
_CONFLICTS_SHOWN: set[tuple[str, ...]] = set()
|
_CONFLICTS_SHOWN: set[tuple[str, ...]] = set()
|
||||||
|
|
||||||
|
|
||||||
def _serialize_source_ref(sr: object) -> str:
|
def _serialize_source_ref(sr: object) -> str:
|
||||||
"""Convert a source_ref value to a clean string for serialization."""
|
"""Convert a source_ref value to a clean string for serialization."""
|
||||||
if isinstance(sr, str):
|
if isinstance(sr, str):
|
||||||
@@ -43,6 +44,19 @@ def _serialize_source_ref(sr: object) -> str:
|
|||||||
return str(sr)
|
return str(sr)
|
||||||
|
|
||||||
|
|
||||||
|
def _indexed_record(value: object, index: dict, files_db: dict) -> dict | None:
|
||||||
|
"""The database record a hash index points a single hash value to."""
|
||||||
|
if not (value and isinstance(value, str)):
|
||||||
|
return None
|
||||||
|
ref = index.get(value.lower())
|
||||||
|
if not ref:
|
||||||
|
return None
|
||||||
|
ref_sha1 = ref if isinstance(ref, str) else (ref[0] if ref else None)
|
||||||
|
if not ref_sha1:
|
||||||
|
return None
|
||||||
|
return files_db.get(ref_sha1)
|
||||||
|
|
||||||
|
|
||||||
def _enrich_hashes(entry: dict, db: dict) -> None:
|
def _enrich_hashes(entry: dict, db: dict) -> None:
|
||||||
"""Fill the hashes a profile omits from the record its own hash names.
|
"""Fill the hashes a profile omits from the record its own hash names.
|
||||||
|
|
||||||
@@ -67,30 +81,18 @@ def _enrich_hashes(entry: dict, db: dict) -> None:
|
|||||||
|
|
||||||
# Anchor 2: MD5 (strong)
|
# Anchor 2: MD5 (strong)
|
||||||
if record is None:
|
if record is None:
|
||||||
md5 = entry.get("md5")
|
record = _indexed_record(entry.get("md5"), indexes.get("by_md5", {}), files_db)
|
||||||
if md5 and isinstance(md5, str):
|
|
||||||
by_md5 = indexes.get("by_md5", {})
|
|
||||||
ref = by_md5.get(md5.lower())
|
|
||||||
if ref:
|
|
||||||
ref_sha1 = ref if isinstance(ref, str) else (ref[0] if ref else None)
|
|
||||||
if ref_sha1:
|
|
||||||
record = files_db.get(ref_sha1)
|
|
||||||
|
|
||||||
# Anchor 3: CRC32 (32-bit, collisions theoretically possible).
|
# Anchor 3: CRC32 (32-bit, collisions theoretically possible).
|
||||||
# Require size match when profile has a size to guard against collisions.
|
# Require size match when profile has a size to guard against collisions.
|
||||||
if record is None:
|
if record is None:
|
||||||
crc = entry.get("crc32")
|
candidate = _indexed_record(
|
||||||
if crc and isinstance(crc, str):
|
entry.get("crc32"), indexes.get("by_crc32", {}), files_db,
|
||||||
by_crc32 = indexes.get("by_crc32", {})
|
)
|
||||||
ref = by_crc32.get(crc.lower())
|
if candidate is not None:
|
||||||
if ref:
|
profile_size = entry.get("size")
|
||||||
ref_sha1 = ref if isinstance(ref, str) else (ref[0] if ref else None)
|
if not profile_size or candidate.get("size") == profile_size:
|
||||||
if ref_sha1:
|
record = candidate
|
||||||
candidate = files_db.get(ref_sha1)
|
|
||||||
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:
|
if record is None:
|
||||||
return
|
return
|
||||||
@@ -653,6 +655,160 @@ def _fold_data_directory_readers(
|
|||||||
_fold_into(entry, dict(declaration), emu_name)
|
_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, standalone_set: set[str], 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, standalone_set)
|
||||||
|
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(
|
def generate_platform_truth(
|
||||||
platform_name: str,
|
platform_name: str,
|
||||||
config: dict,
|
config: dict,
|
||||||
@@ -690,62 +846,7 @@ def generate_platform_truth(
|
|||||||
# 1. File-based: if the scraped platform already has this file, use its system
|
# 1. File-based: if the scraped platform already has this file, use its system
|
||||||
# 2. Exact match: profile system ID == platform system ID
|
# 2. Exact match: profile system ID == platform system ID
|
||||||
# 3. Normalized match: strip manufacturer prefix + separators
|
# 3. Normalized match: strip manufacturer prefix + separators
|
||||||
platform_sys_ids = set(config.get("systems", {}).keys())
|
mapping = _SystemMap.of(config, db)
|
||||||
|
|
||||||
# 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]]] = {}
|
|
||||||
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))
|
|
||||||
|
|
||||||
# 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] = {}
|
|
||||||
for psid in config.get("systems", {}):
|
|
||||||
norm_to_platform.setdefault(_norm_system_id(psid), psid)
|
|
||||||
|
|
||||||
def _map_sys_id(profile_sid: str) -> str:
|
|
||||||
"""Map a profile system ID to the platform's system ID."""
|
|
||||||
if profile_sid in platform_sys_ids:
|
|
||||||
return profile_sid
|
|
||||||
return norm_to_platform.get(_norm_system_id(profile_sid), profile_sid)
|
|
||||||
|
|
||||||
def _attribute(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, db))
|
|
||||||
for psid, decl in 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 = _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 []
|
|
||||||
|
|
||||||
systems: dict[str, dict] = {}
|
systems: dict[str, dict] = {}
|
||||||
unattributed: dict[str, int] = {}
|
unattributed: dict[str, int] = {}
|
||||||
@@ -761,48 +862,11 @@ def generate_platform_truth(
|
|||||||
continue
|
continue
|
||||||
cores_profiled.add(emu_name)
|
cores_profiled.add(emu_name)
|
||||||
|
|
||||||
# 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.
|
|
||||||
filtered = _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, standalone_set)
|
|
||||||
for fe in _system_dir_files(view, standalone)
|
|
||||||
if not unread_on(fe, platform_name)
|
|
||||||
])
|
|
||||||
|
|
||||||
on_platform = {
|
on_platform = {
|
||||||
_map_sys_id(sid) for sid in profile.get("systems", [])
|
mapping.map_sys_id(sid) for sid in profile.get("systems", [])
|
||||||
} & platform_sys_ids
|
} & mapping.platform_sys_ids
|
||||||
for fe in filtered:
|
for fe in _platform_entries(emu_name, profile, standalone_set, platform_name):
|
||||||
profile_sid = fe.get("system", "")
|
sys_targets = mapping.targets(fe, profile, on_platform)
|
||||||
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 = _attribute(fe, own, on_platform)
|
|
||||||
if not sys_ids and not profile_sid and not sys_targets \
|
|
||||||
and fe.get("name", "").lower() not in declared_by_name:
|
|
||||||
sys_targets = [_map_sys_id("unknown")]
|
|
||||||
if not sys_targets:
|
if not sys_targets:
|
||||||
unattributed[emu_name] = unattributed.get(emu_name, 0) + 1
|
unattributed[emu_name] = unattributed.get(emu_name, 0) + 1
|
||||||
continue
|
continue
|
||||||
@@ -811,14 +875,7 @@ def generate_platform_truth(
|
|||||||
_merge_file_into_system(
|
_merge_file_into_system(
|
||||||
system, fe if position == 0 else copy.deepcopy(fe), emu_name, db
|
system, fe if position == 0 else copy.deepcopy(fe), emu_name, db
|
||||||
)
|
)
|
||||||
sys_cov = system_cores.setdefault(
|
_cover(system_cores, sys_id, "profiled", emu_name)
|
||||||
sys_id,
|
|
||||||
{
|
|
||||||
"profiled": set(),
|
|
||||||
"unprofiled": set(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
sys_cov["profiled"].add(emu_name)
|
|
||||||
|
|
||||||
# Ensure all systems of resolved cores have entries (even with 0 files).
|
# Ensure all systems of resolved cores have entries (even with 0 files).
|
||||||
# This documents that the system is covered: the core was analyzed and
|
# This documents that the system is covered: the core was analyzed and
|
||||||
@@ -827,28 +884,14 @@ def generate_platform_truth(
|
|||||||
for emu_name in sorted(cores_profiled):
|
for emu_name in sorted(cores_profiled):
|
||||||
profile = profiles[emu_name]
|
profile = profiles[emu_name]
|
||||||
for prof_sid in profile.get("systems", []):
|
for prof_sid in profile.get("systems", []):
|
||||||
sys_id = _map_sys_id(prof_sid)
|
sys_id = mapping.map_sys_id(prof_sid)
|
||||||
systems.setdefault(sys_id, {})
|
systems.setdefault(sys_id, {})
|
||||||
sys_cov = system_cores.setdefault(
|
_cover(system_cores, sys_id, "profiled", emu_name)
|
||||||
sys_id,
|
|
||||||
{
|
|
||||||
"profiled": set(),
|
|
||||||
"unprofiled": set(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
sys_cov["profiled"].add(emu_name)
|
|
||||||
|
|
||||||
# Track unprofiled cores per system based on profile system lists
|
# Track unprofiled cores per system based on profile system lists
|
||||||
for emu_name in cores_unprofiled:
|
for emu_name in cores_unprofiled:
|
||||||
for sys_id in systems:
|
for sys_id in systems:
|
||||||
sys_cov = system_cores.setdefault(
|
_cover(system_cores, sys_id, "unprofiled", emu_name)
|
||||||
sys_id,
|
|
||||||
{
|
|
||||||
"profiled": set(),
|
|
||||||
"unprofiled": set(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
sys_cov["unprofiled"].add(emu_name)
|
|
||||||
|
|
||||||
_fold_data_directory_readers(
|
_fold_data_directory_readers(
|
||||||
systems, profiles, sorted(cores_profiled), standalone_set, platform_name,
|
systems, profiles, sorted(cores_profiled), standalone_set, platform_name,
|
||||||
@@ -868,27 +911,7 @@ def generate_platform_truth(
|
|||||||
if files_list:
|
if files_list:
|
||||||
sys_data["files"] = [fe for fe in files_list if _has_exploitable_data(fe)]
|
sys_data["files"] = [fe for fe in files_list if _has_exploitable_data(fe)]
|
||||||
|
|
||||||
# Convert sets to sorted lists for serialization
|
_serialize_systems(systems, system_cores)
|
||||||
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())),
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"platform": platform_name,
|
"platform": platform_name,
|
||||||
@@ -1007,7 +1030,7 @@ def _diff_system(truth_sys: dict, scraped_sys: dict) -> dict:
|
|||||||
# An archive declared once per ROM it holds (zipped_file) is still one
|
# An archive declared once per ROM it holds (zipped_file) is still one
|
||||||
# file.
|
# file.
|
||||||
seen_extra: set[tuple[str, str]] = set()
|
seen_extra: set[tuple[str, str]] = set()
|
||||||
for s_key, s_entry in unmatched_scraped.items():
|
for s_entry in unmatched_scraped.values():
|
||||||
key = (s_entry["name"].lower(), _path_tail(s_entry.get("destination")))
|
key = (s_entry["name"].lower(), _path_tail(s_entry.get("destination")))
|
||||||
if key in seen_extra:
|
if key in seen_extra:
|
||||||
continue
|
continue
|
||||||
|
|||||||
+316
-221
@@ -10,7 +10,8 @@ from __future__ import annotations
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import zipfile
|
import zipfile
|
||||||
from collections.abc import Callable, Iterator, Mapping, Sequence
|
from collections.abc import Callable, Collection, Iterator, Mapping, Sequence
|
||||||
|
from typing import TYPE_CHECKING, TypedDict
|
||||||
|
|
||||||
from common import (
|
from common import (
|
||||||
adler32_of,
|
adler32_of,
|
||||||
@@ -28,6 +29,9 @@ from hashing import md5_composite, parse_hash_list, parse_md5_list
|
|||||||
from nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file
|
from nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file
|
||||||
from ziptools import check_inside_zip
|
from ziptools import check_inside_zip
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from typing_extensions import Unpack
|
||||||
|
|
||||||
# Validation types that require console-specific cryptographic keys.
|
# Validation types that require console-specific cryptographic keys.
|
||||||
# verify.py cannot reproduce these: size checks still apply if combined.
|
# verify.py cannot reproduce these: size checks still apply if combined.
|
||||||
_CRYPTO_CHECKS = frozenset({"signature", "crypto"})
|
_CRYPTO_CHECKS = frozenset({"signature", "crypto"})
|
||||||
@@ -62,7 +66,7 @@ def _parse_validation(validation: list | dict | None) -> list[str]:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
def _entry_rule(emu_name: str, f: dict, checks: set[str]) -> dict:
|
def _entry_rule(emu_name: str, f: dict, checks: Collection[str]) -> dict:
|
||||||
"""One profile entry's own checks, kept apart from the merged view.
|
"""One profile entry's own checks, kept apart from the merged view.
|
||||||
|
|
||||||
Merged by name, Azahar's crypto check on the 3DS otp.bin judged Cemu's
|
Merged by name, Azahar's crypto check on the 3DS otp.bin judged Cemu's
|
||||||
@@ -101,7 +105,7 @@ def _entry_rule(emu_name: str, f: dict, checks: set[str]) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def warned_checks(f: dict, checks: set[str]) -> set[str]:
|
def warned_checks(f: dict, checks: Collection[str]) -> set[str]:
|
||||||
"""The checks of an entry the code warns about instead of refusing.
|
"""The checks of an entry the code warns about instead of refusing.
|
||||||
|
|
||||||
`on_mismatch: warn` covers every check, while a map names them one by one, as
|
`on_mismatch: warn` covers every check, while a map names them one by one, as
|
||||||
@@ -116,6 +120,21 @@ def warned_checks(f: dict, checks: set[str]) -> set[str]:
|
|||||||
return set()
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
def _rule_size_failure(rule: dict, local_path: str) -> str | None:
|
||||||
|
"""Why one entry's size check rejects a file, or None."""
|
||||||
|
actual_size = os.path.getsize(local_path)
|
||||||
|
if rule["sizes"] and actual_size not in rule["sizes"]:
|
||||||
|
accepted = ",".join(str(s) for s in sorted(rule["sizes"]))
|
||||||
|
return f"size mismatch: got {actual_size}, accepted [{accepted}]"
|
||||||
|
if rule["min_size"] is not None and actual_size < rule["min_size"]:
|
||||||
|
return f"size too small: min {rule['min_size']}, got {actual_size}"
|
||||||
|
if rule["max_size"] is not None and actual_size > rule["max_size"]:
|
||||||
|
return f"size too large: max {rule['max_size']}, got {actual_size}"
|
||||||
|
if rule.get("size_multiple") and actual_size % int(rule["size_multiple"]):
|
||||||
|
return f"size mismatch: got {actual_size}, accepted multiples of {rule['size_multiple']}"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _rule_failure(
|
def _rule_failure(
|
||||||
rule: dict, local_path: str, filename: str, bios_dir: str, hashes: dict,
|
rule: dict, local_path: str, filename: str, bios_dir: str, hashes: dict,
|
||||||
strict: bool = False,
|
strict: bool = False,
|
||||||
@@ -126,16 +145,9 @@ def _rule_failure(
|
|||||||
"""
|
"""
|
||||||
skip = set() if strict else rule["warn"]
|
skip = set() if strict else rule["warn"]
|
||||||
if "size" not in skip:
|
if "size" not in skip:
|
||||||
actual_size = os.path.getsize(local_path)
|
refused = _rule_size_failure(rule, local_path)
|
||||||
if rule["sizes"] and actual_size not in rule["sizes"]:
|
if refused:
|
||||||
accepted = ",".join(str(s) for s in sorted(rule["sizes"]))
|
return refused
|
||||||
return f"size mismatch: got {actual_size}, accepted [{accepted}]"
|
|
||||||
if rule["min_size"] is not None and actual_size < rule["min_size"]:
|
|
||||||
return f"size too small: min {rule['min_size']}, got {actual_size}"
|
|
||||||
if rule["max_size"] is not None and actual_size > rule["max_size"]:
|
|
||||||
return f"size too large: max {rule['max_size']}, got {actual_size}"
|
|
||||||
if rule.get("size_multiple") and actual_size % int(rule["size_multiple"]):
|
|
||||||
return f"size mismatch: got {actual_size}, accepted multiples of {rule['size_multiple']}"
|
|
||||||
for hash_type in ("crc32", "md5", "sha1", "sha256"):
|
for hash_type in ("crc32", "md5", "sha1", "sha256"):
|
||||||
if rule[hash_type] and hash_type not in skip:
|
if rule[hash_type] and hash_type not in skip:
|
||||||
if not hashes:
|
if not hashes:
|
||||||
@@ -229,6 +241,144 @@ def _labels_widened(profile: dict) -> list[dict]:
|
|||||||
return widened
|
return widened
|
||||||
|
|
||||||
|
|
||||||
|
def _new_index_entry() -> dict:
|
||||||
|
return {
|
||||||
|
"checks": set(),
|
||||||
|
"sizes": set(),
|
||||||
|
"min_size": None,
|
||||||
|
"max_size": None,
|
||||||
|
"size_multiples": set(),
|
||||||
|
"crc32": set(),
|
||||||
|
"md5": set(),
|
||||||
|
"sha1": set(),
|
||||||
|
"sha256": set(),
|
||||||
|
"adler32": set(),
|
||||||
|
"adler32_byteswap": False,
|
||||||
|
"crypto_only": set(),
|
||||||
|
"emulators": set(),
|
||||||
|
"per_emulator": {},
|
||||||
|
"rules": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_sizes(item: dict, f: dict) -> None:
|
||||||
|
raw_size = f.get("size")
|
||||||
|
if raw_size is not None:
|
||||||
|
if isinstance(raw_size, list):
|
||||||
|
item["sizes"].update(raw_size)
|
||||||
|
else:
|
||||||
|
item["sizes"].add(raw_size)
|
||||||
|
if f.get("min_size") is not None:
|
||||||
|
cur = item["min_size"]
|
||||||
|
item["min_size"] = (
|
||||||
|
min(cur, f["min_size"]) if cur is not None else f["min_size"]
|
||||||
|
)
|
||||||
|
if f.get("size_multiple"):
|
||||||
|
item["size_multiples"].add(int(f["size_multiple"]))
|
||||||
|
if f.get("max_size") is not None:
|
||||||
|
cur = item["max_size"]
|
||||||
|
item["max_size"] = (
|
||||||
|
max(cur, f["max_size"]) if cur is not None else f["max_size"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _hex_values(value: object) -> list[str]:
|
||||||
|
"""Hash values without their 0x prefix, lowercased."""
|
||||||
|
values = value if isinstance(value, list) else [value] if value else []
|
||||||
|
out = []
|
||||||
|
for item in values:
|
||||||
|
norm = str(item).lower()
|
||||||
|
if norm.startswith("0x"):
|
||||||
|
norm = norm[2:]
|
||||||
|
out.append(norm)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_hashes(item: dict, f: dict, checks: list[str]) -> None:
|
||||||
|
# Hash checks: collect all accepted hashes as sets (multiple valid
|
||||||
|
# versions of the same file, e.g. MT-32 ROM versions)
|
||||||
|
if "crc32" in checks and f.get("crc32"):
|
||||||
|
item["crc32"].update(_hex_values(f["crc32"]))
|
||||||
|
# A hash field may carry several accepted values, as a list or as
|
||||||
|
# the comma-separated string the schema spells out
|
||||||
|
for hash_type in ("md5", "sha1", "sha256"):
|
||||||
|
if hash_type in checks and f.get(hash_type):
|
||||||
|
val = f[hash_type]
|
||||||
|
values = val if isinstance(val, list) else str(val).split(",")
|
||||||
|
item[hash_type].update(
|
||||||
|
str(h).strip().lower() for h in values if str(h).strip()
|
||||||
|
)
|
||||||
|
# Adler32: stored as known_hash_adler32 field (not in validation: list
|
||||||
|
# for Dolphin, but support it in both forms for future profiles)
|
||||||
|
item["adler32"].update(_hex_values(f.get("known_hash_adler32") or f.get("adler32")))
|
||||||
|
if f.get("adler32_byteswap"):
|
||||||
|
item["adler32_byteswap"] = True
|
||||||
|
|
||||||
|
|
||||||
|
def _expected_values(f: dict, checks: list[str]) -> dict:
|
||||||
|
"""The values an entry's checks compare, for ground truth reporting."""
|
||||||
|
expected: dict = {}
|
||||||
|
if "size" in checks:
|
||||||
|
for key in ("size", "min_size", "max_size", "size_multiple"):
|
||||||
|
if f.get(key) is not None:
|
||||||
|
expected[key] = f[key]
|
||||||
|
for hash_type in ("crc32", "md5", "sha1", "sha256"):
|
||||||
|
if hash_type in checks and f.get(hash_type):
|
||||||
|
expected[hash_type] = f[hash_type]
|
||||||
|
adler_val_pe = f.get("known_hash_adler32") or f.get("adler32")
|
||||||
|
if adler_val_pe:
|
||||||
|
expected["adler32"] = adler_val_pe
|
||||||
|
for check in sorted(CONTENT_CHECKS & set(checks)):
|
||||||
|
expected[check] = f.get(check) or {}
|
||||||
|
return expected
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_per_emulator(item: dict, emu_name: str, f: dict, checks: list[str]) -> None:
|
||||||
|
# Per-emulator ground truth detail
|
||||||
|
pe = item["per_emulator"]
|
||||||
|
expected = _expected_values(f, checks)
|
||||||
|
if emu_name in pe:
|
||||||
|
# Merge checks from multiple file entries for same emulator
|
||||||
|
existing = pe[emu_name]
|
||||||
|
merged_checks = sorted(
|
||||||
|
set(existing["checks"]) | set(checks)
|
||||||
|
)
|
||||||
|
existing["checks"] = merged_checks
|
||||||
|
existing["expected"].update(expected)
|
||||||
|
if f.get("source_ref") and not existing["source_ref"]:
|
||||||
|
existing["source_ref"] = f.get("source_ref")
|
||||||
|
else:
|
||||||
|
pe[emu_name] = {
|
||||||
|
"checks": sorted(checks),
|
||||||
|
"source_ref": f.get("source_ref"),
|
||||||
|
"expected": expected,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _index_entry(index: dict[str, dict], emu_name: str, f: dict, checks: list[str]) -> None:
|
||||||
|
"""Merge one checked profile entry into the index."""
|
||||||
|
fname = f.get("name", "")
|
||||||
|
if fname not in index:
|
||||||
|
index[fname] = _new_index_entry()
|
||||||
|
item = index[fname]
|
||||||
|
item["rules"].append(_entry_rule(emu_name, f, checks))
|
||||||
|
item["emulators"].add(emu_name)
|
||||||
|
# A warned check is never a rejection, so it stays out of the
|
||||||
|
# merged rejection rules.
|
||||||
|
warned = warned_checks(f, set(checks))
|
||||||
|
checks = [check for check in checks if check not in warned]
|
||||||
|
if not checks:
|
||||||
|
return
|
||||||
|
item["checks"].update(checks)
|
||||||
|
# Track non-reproducible crypto checks
|
||||||
|
item["crypto_only"].update(c for c in checks if c in _CRYPTO_CHECKS)
|
||||||
|
# Size checks
|
||||||
|
if "size" in checks:
|
||||||
|
_merge_sizes(item, f)
|
||||||
|
_merge_hashes(item, f, checks)
|
||||||
|
_merge_per_emulator(item, emu_name, f, checks)
|
||||||
|
|
||||||
|
|
||||||
def _build_validation_index(profiles: dict) -> dict[str, dict]:
|
def _build_validation_index(profiles: dict) -> dict[str, dict]:
|
||||||
"""Build per-filename validation rules from emulator profiles.
|
"""Build per-filename validation rules from emulator profiles.
|
||||||
|
|
||||||
@@ -264,116 +414,7 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]:
|
|||||||
unchecked.add(slot)
|
unchecked.add(slot)
|
||||||
continue
|
continue
|
||||||
checked.add(slot)
|
checked.add(slot)
|
||||||
if fname not in index:
|
_index_entry(index, emu_name, f, checks)
|
||||||
index[fname] = {
|
|
||||||
"checks": set(),
|
|
||||||
"sizes": set(),
|
|
||||||
"min_size": None,
|
|
||||||
"max_size": None,
|
|
||||||
"size_multiples": set(),
|
|
||||||
"crc32": set(),
|
|
||||||
"md5": set(),
|
|
||||||
"sha1": set(),
|
|
||||||
"sha256": set(),
|
|
||||||
"adler32": set(),
|
|
||||||
"adler32_byteswap": False,
|
|
||||||
"crypto_only": set(),
|
|
||||||
"emulators": set(),
|
|
||||||
"per_emulator": {},
|
|
||||||
"rules": [],
|
|
||||||
}
|
|
||||||
index[fname]["rules"].append(_entry_rule(emu_name, f, checks))
|
|
||||||
index[fname]["emulators"].add(emu_name)
|
|
||||||
# A warned check is never a rejection, so it stays out of the
|
|
||||||
# merged rejection rules.
|
|
||||||
warned = warned_checks(f, set(checks))
|
|
||||||
checks = [check for check in checks if check not in warned]
|
|
||||||
if not checks:
|
|
||||||
continue
|
|
||||||
index[fname]["checks"].update(checks)
|
|
||||||
# Track non-reproducible crypto checks
|
|
||||||
index[fname]["crypto_only"].update(c for c in checks if c in _CRYPTO_CHECKS)
|
|
||||||
# Size checks
|
|
||||||
if "size" in checks:
|
|
||||||
raw_size = f.get("size")
|
|
||||||
if raw_size is not None:
|
|
||||||
if isinstance(raw_size, list):
|
|
||||||
index[fname]["sizes"].update(raw_size)
|
|
||||||
else:
|
|
||||||
index[fname]["sizes"].add(raw_size)
|
|
||||||
if f.get("min_size") is not None:
|
|
||||||
cur = index[fname]["min_size"]
|
|
||||||
index[fname]["min_size"] = (
|
|
||||||
min(cur, f["min_size"]) if cur is not None else f["min_size"]
|
|
||||||
)
|
|
||||||
if f.get("size_multiple"):
|
|
||||||
index[fname]["size_multiples"].add(int(f["size_multiple"]))
|
|
||||||
if f.get("max_size") is not None:
|
|
||||||
cur = index[fname]["max_size"]
|
|
||||||
index[fname]["max_size"] = (
|
|
||||||
max(cur, f["max_size"]) if cur is not None else f["max_size"]
|
|
||||||
)
|
|
||||||
# Hash checks: collect all accepted hashes as sets (multiple valid
|
|
||||||
# versions of the same file, e.g. MT-32 ROM versions)
|
|
||||||
if "crc32" in checks and f.get("crc32"):
|
|
||||||
crc_val = f["crc32"]
|
|
||||||
crc_list = crc_val if isinstance(crc_val, list) else [crc_val]
|
|
||||||
for cv in crc_list:
|
|
||||||
norm = str(cv).lower()
|
|
||||||
if norm.startswith("0x"):
|
|
||||||
norm = norm[2:]
|
|
||||||
index[fname]["crc32"].add(norm)
|
|
||||||
# A hash field may carry several accepted values, as a list or as
|
|
||||||
# the comma-separated string the schema spells out
|
|
||||||
for hash_type in ("md5", "sha1", "sha256"):
|
|
||||||
if hash_type in checks and f.get(hash_type):
|
|
||||||
val = f[hash_type]
|
|
||||||
values = val if isinstance(val, list) else str(val).split(",")
|
|
||||||
for h in values:
|
|
||||||
if str(h).strip():
|
|
||||||
index[fname][hash_type].add(str(h).strip().lower())
|
|
||||||
# Adler32: stored as known_hash_adler32 field (not in validation: list
|
|
||||||
# for Dolphin, but support it in both forms for future profiles)
|
|
||||||
adler_val = f.get("known_hash_adler32") or f.get("adler32")
|
|
||||||
for value in adler_val if isinstance(adler_val, list) else [adler_val] if adler_val else []:
|
|
||||||
norm = str(value).lower()
|
|
||||||
if norm.startswith("0x"):
|
|
||||||
norm = norm[2:]
|
|
||||||
index[fname]["adler32"].add(norm)
|
|
||||||
if f.get("adler32_byteswap"):
|
|
||||||
index[fname]["adler32_byteswap"] = True
|
|
||||||
# Per-emulator ground truth detail
|
|
||||||
expected: dict = {}
|
|
||||||
if "size" in checks:
|
|
||||||
for key in ("size", "min_size", "max_size", "size_multiple"):
|
|
||||||
if f.get(key) is not None:
|
|
||||||
expected[key] = f[key]
|
|
||||||
for hash_type in ("crc32", "md5", "sha1", "sha256"):
|
|
||||||
if hash_type in checks and f.get(hash_type):
|
|
||||||
expected[hash_type] = f[hash_type]
|
|
||||||
adler_val_pe = f.get("known_hash_adler32") or f.get("adler32")
|
|
||||||
if adler_val_pe:
|
|
||||||
expected["adler32"] = adler_val_pe
|
|
||||||
for check in sorted(CONTENT_CHECKS & set(checks)):
|
|
||||||
expected[check] = f.get(check) or {}
|
|
||||||
pe_entry = {
|
|
||||||
"checks": sorted(checks),
|
|
||||||
"source_ref": f.get("source_ref"),
|
|
||||||
"expected": expected,
|
|
||||||
}
|
|
||||||
pe = index[fname]["per_emulator"]
|
|
||||||
if emu_name in pe:
|
|
||||||
# Merge checks from multiple file entries for same emulator
|
|
||||||
existing = pe[emu_name]
|
|
||||||
merged_checks = sorted(
|
|
||||||
set(existing["checks"]) | set(pe_entry["checks"])
|
|
||||||
)
|
|
||||||
existing["checks"] = merged_checks
|
|
||||||
existing["expected"].update(pe_entry["expected"])
|
|
||||||
if pe_entry["source_ref"] and not existing["source_ref"]:
|
|
||||||
existing["source_ref"] = pe_entry["source_ref"]
|
|
||||||
else:
|
|
||||||
pe[emu_name] = pe_entry
|
|
||||||
for fname, emu_name, _path in sorted(checked & unchecked):
|
for fname, emu_name, _path in sorted(checked & unchecked):
|
||||||
index[fname]["rules"].append(_entry_rule(emu_name, {}, set()))
|
index[fname]["rules"].append(_entry_rule(emu_name, {}, set()))
|
||||||
# Convert sets to sorted tuples/lists for determinism
|
# Convert sets to sorted tuples/lists for determinism
|
||||||
@@ -418,9 +459,11 @@ def _emulators_for_check(
|
|||||||
if check_type in emu_checks:
|
if check_type in emu_checks:
|
||||||
result.append(emu)
|
result.append(emu)
|
||||||
# adler32 is stored as known_hash, not always in validation list
|
# adler32 is stored as known_hash, not always in validation list
|
||||||
if check_type == "adler32" and detail.get("expected", {}).get("adler32"):
|
if (
|
||||||
if emu not in result:
|
check_type == "adler32" and detail.get("expected", {}).get("adler32")
|
||||||
result.append(emu)
|
and emu not in result
|
||||||
|
):
|
||||||
|
result.append(emu)
|
||||||
return sorted(result)
|
return sorted(result)
|
||||||
|
|
||||||
|
|
||||||
@@ -433,8 +476,8 @@ def _merged_reason(reasons: list[str]) -> str:
|
|||||||
Raze lists three BLOOD.RFF sizes and the message named the first one
|
Raze lists three BLOOD.RFF sizes and the message named the first one
|
||||||
alone. Reasons of one kind are merged into a single accepted list.
|
alone. Reasons of one kind are merged into a single accepted list.
|
||||||
"""
|
"""
|
||||||
parsed = [_REASON.match(reason) for reason in reasons]
|
parsed = [m for m in (_REASON.match(reason) for reason in reasons) if m]
|
||||||
if all(parsed) and len({(m.group(1), m.group(2)) for m in parsed}) == 1:
|
if len(parsed) == len(reasons) and len({(m.group(1), m.group(2)) for m in parsed}) == 1:
|
||||||
accepted = sorted({v for m in parsed for v in m.group(3).split(",") if v},
|
accepted = sorted({v for m in parsed for v in m.group(3).split(",") if v},
|
||||||
key=lambda v: (len(v), v))
|
key=lambda v: (len(v), v))
|
||||||
return f"{parsed[0].group(1)}: got {parsed[0].group(2)}, accepted [{','.join(accepted)}]"
|
return f"{parsed[0].group(1)}: got {parsed[0].group(2)}, accepted [{','.join(accepted)}]"
|
||||||
@@ -469,43 +512,17 @@ def check_file_validation(
|
|||||||
if not entry:
|
if not entry:
|
||||||
return None
|
return None
|
||||||
if emulators is not None:
|
if emulators is not None:
|
||||||
hashes: dict = {}
|
return _per_emulator_failure(
|
||||||
failures: dict[str, str] = {}
|
entry, local_path, filename, bios_dir, emulators, strict,
|
||||||
for emu in sorted(emulators):
|
)
|
||||||
rules = [r for r in entry.get("rules", []) if r["emulator"] == emu]
|
|
||||||
if not rules:
|
|
||||||
continue
|
|
||||||
reasons = [
|
|
||||||
_rule_failure(rule, local_path, filename, bios_dir, hashes, strict)
|
|
||||||
for rule in rules
|
|
||||||
]
|
|
||||||
if all(reasons):
|
|
||||||
failures[emu] = _merged_reason(reasons)
|
|
||||||
if not failures:
|
|
||||||
return None
|
|
||||||
first = sorted(failures)[0]
|
|
||||||
return failures[first], sorted(failures)
|
|
||||||
checks = entry["checks"]
|
checks = entry["checks"]
|
||||||
pe = entry.get("per_emulator", {})
|
pe = entry.get("per_emulator", {})
|
||||||
|
|
||||||
# Size checks: sizes is a set of accepted values
|
# Size checks: sizes is a set of accepted values
|
||||||
if "size" in checks:
|
if "size" in checks:
|
||||||
actual_size = os.path.getsize(local_path)
|
refused = _merged_size_failure(entry, local_path, pe)
|
||||||
if entry["sizes"] and actual_size not in entry["sizes"]:
|
if refused:
|
||||||
expected = ",".join(str(s) for s in sorted(entry["sizes"]))
|
return refused
|
||||||
emus = _emulators_for_check("size", pe)
|
|
||||||
return f"size mismatch: got {actual_size}, accepted [{expected}]", emus
|
|
||||||
if entry["min_size"] is not None and actual_size < entry["min_size"]:
|
|
||||||
emus = _emulators_for_check("size", pe)
|
|
||||||
return f"size too small: min {entry['min_size']}, got {actual_size}", emus
|
|
||||||
if entry["max_size"] is not None and actual_size > entry["max_size"]:
|
|
||||||
emus = _emulators_for_check("size", pe)
|
|
||||||
return f"size too large: max {entry['max_size']}, got {actual_size}", emus
|
|
||||||
multiples = entry.get("size_multiples") or set()
|
|
||||||
if multiples and all(actual_size % m for m in multiples):
|
|
||||||
emus = _emulators_for_check("size", pe)
|
|
||||||
accepted = ",".join(str(m) for m in sorted(multiples))
|
|
||||||
return f"size mismatch: got {actual_size}, accepted multiples of [{accepted}]", emus
|
|
||||||
|
|
||||||
# A content test passes when one of the entries declaring it accepts
|
# A content test passes when one of the entries declaring it accepts
|
||||||
# the file, each read as its own code reads it.
|
# the file, each read as its own code reads it.
|
||||||
@@ -516,34 +533,9 @@ def check_file_validation(
|
|||||||
):
|
):
|
||||||
return _CONTENT_REASONS[check], _emulators_for_check(check, pe)
|
return _CONTENT_REASONS[check], _emulators_for_check(check, pe)
|
||||||
|
|
||||||
# Hash checks: compute once, reuse for all hash types.
|
refused = _merged_hash_failure(entry, local_path, checks, pe)
|
||||||
# Each hash field is a set of accepted values (multiple valid ROM versions).
|
if refused:
|
||||||
need_hashes = any(
|
return refused
|
||||||
h in checks and entry.get(h) for h in ("crc32", "md5", "sha1", "sha256")
|
|
||||||
) or entry.get("adler32")
|
|
||||||
if need_hashes:
|
|
||||||
hashes = compute_hashes(local_path)
|
|
||||||
for hash_type in ("crc32", "md5", "sha1", "sha256"):
|
|
||||||
if hash_type in checks and entry[hash_type]:
|
|
||||||
if hashes[hash_type].lower() not in entry[hash_type]:
|
|
||||||
expected = ",".join(sorted(entry[hash_type]))
|
|
||||||
emus = _emulators_for_check(hash_type, pe)
|
|
||||||
return (
|
|
||||||
f"{hash_type} mismatch: got {hashes[hash_type]}, "
|
|
||||||
f"accepted [{expected}]",
|
|
||||||
emus,
|
|
||||||
)
|
|
||||||
if entry["adler32"]:
|
|
||||||
actual_adler = hashes["adler32"].lower()
|
|
||||||
if entry.get("adler32_byteswap"):
|
|
||||||
actual_adler = _adler32_byteswapped(local_path)
|
|
||||||
if actual_adler not in entry["adler32"]:
|
|
||||||
expected = ",".join(sorted(entry["adler32"]))
|
|
||||||
emus = _emulators_for_check("adler32", pe)
|
|
||||||
return (
|
|
||||||
f"adler32 mismatch: got 0x{actual_adler}, accepted [{expected}]",
|
|
||||||
emus,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Signature/crypto checks (3DS RSA, AES)
|
# Signature/crypto checks (3DS RSA, AES)
|
||||||
if entry["crypto_only"]:
|
if entry["crypto_only"]:
|
||||||
@@ -557,6 +549,89 @@ def check_file_validation(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _per_emulator_failure(
|
||||||
|
entry: dict, local_path: str, filename: str, bios_dir: str,
|
||||||
|
emulators: set[str], strict: bool,
|
||||||
|
) -> tuple[str, list[str]] | None:
|
||||||
|
"""Each core judges the file by its own entries for the name."""
|
||||||
|
hashes: dict = {}
|
||||||
|
failures: dict[str, str] = {}
|
||||||
|
for emu in sorted(emulators):
|
||||||
|
rules = [r for r in entry.get("rules", []) if r["emulator"] == emu]
|
||||||
|
if not rules:
|
||||||
|
continue
|
||||||
|
reasons = [
|
||||||
|
_rule_failure(rule, local_path, filename, bios_dir, hashes, strict)
|
||||||
|
for rule in rules
|
||||||
|
]
|
||||||
|
refused = [reason for reason in reasons if reason]
|
||||||
|
if len(refused) == len(reasons):
|
||||||
|
failures[emu] = _merged_reason(refused)
|
||||||
|
if not failures:
|
||||||
|
return None
|
||||||
|
first = sorted(failures)[0]
|
||||||
|
return failures[first], sorted(failures)
|
||||||
|
|
||||||
|
|
||||||
|
def _merged_size_failure(
|
||||||
|
entry: dict, local_path: str, pe: dict[str, dict],
|
||||||
|
) -> tuple[str, list[str]] | None:
|
||||||
|
actual_size = os.path.getsize(local_path)
|
||||||
|
if entry["sizes"] and actual_size not in entry["sizes"]:
|
||||||
|
expected = ",".join(str(s) for s in sorted(entry["sizes"]))
|
||||||
|
emus = _emulators_for_check("size", pe)
|
||||||
|
return f"size mismatch: got {actual_size}, accepted [{expected}]", emus
|
||||||
|
if entry["min_size"] is not None and actual_size < entry["min_size"]:
|
||||||
|
emus = _emulators_for_check("size", pe)
|
||||||
|
return f"size too small: min {entry['min_size']}, got {actual_size}", emus
|
||||||
|
if entry["max_size"] is not None and actual_size > entry["max_size"]:
|
||||||
|
emus = _emulators_for_check("size", pe)
|
||||||
|
return f"size too large: max {entry['max_size']}, got {actual_size}", emus
|
||||||
|
multiples = entry.get("size_multiples") or set()
|
||||||
|
if multiples and all(actual_size % m for m in multiples):
|
||||||
|
emus = _emulators_for_check("size", pe)
|
||||||
|
accepted = ",".join(str(m) for m in sorted(multiples))
|
||||||
|
return f"size mismatch: got {actual_size}, accepted multiples of [{accepted}]", emus
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _merged_hash_failure(
|
||||||
|
entry: dict, local_path: str, checks: list[str], pe: dict[str, dict],
|
||||||
|
) -> tuple[str, list[str]] | None:
|
||||||
|
# Hash checks: compute once, reuse for all hash types.
|
||||||
|
# Each hash field is a set of accepted values (multiple valid ROM versions).
|
||||||
|
need_hashes = any(
|
||||||
|
h in checks and entry.get(h) for h in ("crc32", "md5", "sha1", "sha256")
|
||||||
|
) or entry.get("adler32")
|
||||||
|
if not need_hashes:
|
||||||
|
return None
|
||||||
|
hashes = compute_hashes(local_path)
|
||||||
|
for hash_type in ("crc32", "md5", "sha1", "sha256"):
|
||||||
|
if (
|
||||||
|
hash_type in checks and entry[hash_type]
|
||||||
|
and hashes[hash_type].lower() not in entry[hash_type]
|
||||||
|
):
|
||||||
|
expected = ",".join(sorted(entry[hash_type]))
|
||||||
|
emus = _emulators_for_check(hash_type, pe)
|
||||||
|
return (
|
||||||
|
f"{hash_type} mismatch: got {hashes[hash_type]}, "
|
||||||
|
f"accepted [{expected}]",
|
||||||
|
emus,
|
||||||
|
)
|
||||||
|
if entry["adler32"]:
|
||||||
|
actual_adler = hashes["adler32"].lower()
|
||||||
|
if entry.get("adler32_byteswap"):
|
||||||
|
actual_adler = _adler32_byteswapped(local_path)
|
||||||
|
if actual_adler not in entry["adler32"]:
|
||||||
|
expected = ",".join(sorted(entry["adler32"]))
|
||||||
|
emus = _emulators_for_check("adler32", pe)
|
||||||
|
return (
|
||||||
|
f"adler32 mismatch: got 0x{actual_adler}, accepted [{expected}]",
|
||||||
|
emus,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def read_from_system_dir(file_entry: dict, standalone: bool = False) -> bool:
|
def read_from_system_dir(file_entry: dict, standalone: bool = False) -> bool:
|
||||||
"""Whether the emulator reads this entry from the system directory.
|
"""Whether the emulator reads this entry from the system directory.
|
||||||
|
|
||||||
@@ -784,6 +859,37 @@ def deliverable(entries: list[dict], standalone: bool, platform: str = "") -> li
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _platform_accepted(file_entry: dict, platform_digest: str) -> set[str]:
|
||||||
|
"""The values of the digest the frontend compares that the entry declares."""
|
||||||
|
declared = file_entry.get(platform_digest) or ""
|
||||||
|
if platform_digest == "md5":
|
||||||
|
return set(parse_md5_list(declared))
|
||||||
|
if isinstance(declared, str) and declared:
|
||||||
|
return {declared.lower()}
|
||||||
|
if isinstance(declared, list):
|
||||||
|
return {str(value).lower() for value in declared}
|
||||||
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
def _variant_candidates(expected: dict, indexes: dict, fname: str) -> Iterator[str]:
|
||||||
|
"""The sha1 of each held file that may stand for a name, best evidence first."""
|
||||||
|
# Sorted: the index holds sets, whose order follows the per-process
|
||||||
|
# string hash, and the first passing candidate is the one shipped.
|
||||||
|
for hash_type, index_key in (
|
||||||
|
("sha1", None), ("md5", "by_md5"), ("crc32", "by_crc32"), ("sha256", "by_sha256"),
|
||||||
|
):
|
||||||
|
for value in sorted(expected.get(hash_type) or []):
|
||||||
|
if index_key is None:
|
||||||
|
yield value
|
||||||
|
continue
|
||||||
|
found = indexes.get(index_key, {}).get(value)
|
||||||
|
if isinstance(found, str):
|
||||||
|
yield found
|
||||||
|
elif isinstance(found, list):
|
||||||
|
yield from found
|
||||||
|
yield from indexes.get("by_name", {}).get(fname, [])
|
||||||
|
|
||||||
|
|
||||||
def find_validated_variant(
|
def find_validated_variant(
|
||||||
file_entry: dict,
|
file_entry: dict,
|
||||||
db: dict,
|
db: dict,
|
||||||
@@ -811,38 +917,14 @@ def find_validated_variant(
|
|||||||
if platform_digest:
|
if platform_digest:
|
||||||
if file_entry.get("zipped_file"):
|
if file_entry.get("zipped_file"):
|
||||||
return None
|
return None
|
||||||
declared = file_entry.get(platform_digest) or ""
|
accepted = _platform_accepted(file_entry, platform_digest)
|
||||||
if platform_digest == "md5":
|
|
||||||
accepted = set(parse_md5_list(declared))
|
|
||||||
elif isinstance(declared, str) and declared:
|
|
||||||
accepted = {declared.lower()}
|
|
||||||
elif isinstance(declared, list):
|
|
||||||
accepted = {str(value).lower() for value in declared}
|
|
||||||
|
|
||||||
files_db = db.get("files", {})
|
files_db = db.get("files", {})
|
||||||
indexes = db.get("indexes", {})
|
indexes = db.get("indexes", {})
|
||||||
current_real = os.path.realpath(current_path)
|
current_real = os.path.realpath(current_path)
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
|
|
||||||
def candidates() -> Iterator[str]:
|
for sha1 in _variant_candidates(validation_index[fname], indexes, fname):
|
||||||
# Sorted: the index holds sets, whose order follows the per-process
|
|
||||||
# string hash, and the first passing candidate is the one shipped.
|
|
||||||
expected = validation_index[fname]
|
|
||||||
for hash_type, index_key in (
|
|
||||||
("sha1", None), ("md5", "by_md5"), ("crc32", "by_crc32"), ("sha256", "by_sha256"),
|
|
||||||
):
|
|
||||||
for value in sorted(expected.get(hash_type) or []):
|
|
||||||
if index_key is None:
|
|
||||||
yield value
|
|
||||||
continue
|
|
||||||
found = indexes.get(index_key, {}).get(value)
|
|
||||||
if isinstance(found, str):
|
|
||||||
yield found
|
|
||||||
elif isinstance(found, list):
|
|
||||||
yield from found
|
|
||||||
yield from indexes.get("by_name", {}).get(fname, [])
|
|
||||||
|
|
||||||
for sha1 in candidates():
|
|
||||||
entry = files_db.get(sha1) or {}
|
entry = files_db.get(sha1) or {}
|
||||||
path = entry.get("path", "")
|
path = entry.get("path", "")
|
||||||
if not path or not os.path.exists(path):
|
if not path or not os.path.exists(path):
|
||||||
@@ -900,7 +982,7 @@ def agnostic_substitute(
|
|||||||
|
|
||||||
|
|
||||||
def frontend_digest_matches(
|
def frontend_digest_matches(
|
||||||
file_entry: dict, local_path: str, algorithm: str, rule: str = ""
|
file_entry: dict, local_path: str | None, algorithm: str, rule: str = ""
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""Whether the frontend's own digest accepts the file.
|
"""Whether the frontend's own digest accepts the file.
|
||||||
|
|
||||||
@@ -947,9 +1029,9 @@ def digest_verdict(
|
|||||||
# RomM reads an absent size as 0: such an entry never verifies.
|
# RomM reads an absent size as 0: such an entry never verifies.
|
||||||
if size != int(file_entry.get("size") or 0):
|
if size != int(file_entry.get("size") or 0):
|
||||||
return False
|
return False
|
||||||
actual = hashes()
|
digests = hashes()
|
||||||
return any(
|
return any(
|
||||||
actual[field].lower() == str(file_entry[field]).strip().lower()
|
digests[field].lower() == str(file_entry[field]).strip().lower()
|
||||||
for field in ("md5", "sha1", "crc32")
|
for field in ("md5", "sha1", "crc32")
|
||||||
if file_entry.get(field)
|
if file_entry.get(field)
|
||||||
)
|
)
|
||||||
@@ -970,7 +1052,9 @@ def digest_verdict(
|
|||||||
if not composite_only and actual in declared:
|
if not composite_only and actual in declared:
|
||||||
return True
|
return True
|
||||||
member_digest = composite()
|
member_digest = composite()
|
||||||
return bool(member_digest) and member_digest.lower() in declared
|
if not member_digest:
|
||||||
|
return False
|
||||||
|
return member_digest.lower() in declared
|
||||||
|
|
||||||
|
|
||||||
def inner_rom_check(file_entry: dict, local_path: str) -> str:
|
def inner_rom_check(file_entry: dict, local_path: str) -> str:
|
||||||
@@ -1060,6 +1144,12 @@ def _owners_of(destination: str, name: str, owners: dict) -> set[str]:
|
|||||||
return {emu for tail, emu in matching if len(tail) == longest}
|
return {emu for tail, emu in matching if len(tail) == longest}
|
||||||
|
|
||||||
|
|
||||||
|
class Judges(TypedDict, total=False):
|
||||||
|
"""The cores that judge a file in validated_choice, each by its own entries."""
|
||||||
|
|
||||||
|
emulators: set[str] | None
|
||||||
|
|
||||||
|
|
||||||
def validated_choice(
|
def validated_choice(
|
||||||
file_entry: dict,
|
file_entry: dict,
|
||||||
local_path: str | None,
|
local_path: str | None,
|
||||||
@@ -1069,7 +1159,7 @@ def validated_choice(
|
|||||||
platform_digest: str | None,
|
platform_digest: str | None,
|
||||||
destination: str = "",
|
destination: str = "",
|
||||||
owners: dict | None = None,
|
owners: dict | None = None,
|
||||||
emulators: set[str] | None = None,
|
**judging: Unpack[Judges],
|
||||||
) -> tuple[str | None, str | None]:
|
) -> tuple[str | None, str | None]:
|
||||||
"""The file a platform destination ships, and the disagreement if any.
|
"""The file a platform destination ships, and the disagreement if any.
|
||||||
|
|
||||||
@@ -1079,6 +1169,10 @@ def validated_choice(
|
|||||||
another emulator declares more precisely is that emulator's: ZEsarUX's
|
another emulator declares more precisely is that emulator's: ZEsarUX's
|
||||||
48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom.
|
48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom.
|
||||||
"""
|
"""
|
||||||
|
unknown = sorted(set(judging) - set(Judges.__annotations__))
|
||||||
|
if unknown:
|
||||||
|
raise TypeError(f"validated_choice() got an unexpected keyword argument '{unknown[0]}'")
|
||||||
|
emulators = judging.get("emulators")
|
||||||
if not local_path or not validation_index:
|
if not local_path or not validation_index:
|
||||||
return local_path, None
|
return local_path, None
|
||||||
name = file_entry.get("name", "")
|
name = file_entry.get("name", "")
|
||||||
@@ -1093,6 +1187,7 @@ def validated_choice(
|
|||||||
# The cores that read this destination judge it, each by its own
|
# The cores that read this destination judge it, each by its own
|
||||||
# entries.
|
# entries.
|
||||||
judges = owning & set(rules["emulators"])
|
judges = owning & set(rules["emulators"])
|
||||||
|
|
||||||
def check(path: str, strict: bool) -> tuple[str, list[str]] | None:
|
def check(path: str, strict: bool) -> tuple[str, list[str]] | None:
|
||||||
return check_file_validation(path, name, validation_index, bios_dir, judges, strict)
|
return check_file_validation(path, name, validation_index, bios_dir, judges, strict)
|
||||||
|
|
||||||
@@ -1151,8 +1246,8 @@ def slot_index(files: list) -> dict[tuple[str, str], list[dict]]:
|
|||||||
matches them: one pass, then one lookup per extra."""
|
matches them: one pass, then one lookup per extra."""
|
||||||
index: dict[tuple[str, str], list[dict]] = {}
|
index: dict[tuple[str, str], list[dict]] = {}
|
||||||
for entry in files or []:
|
for entry in files or []:
|
||||||
if isinstance(entry, dict):
|
if isinstance(entry, dict) and isinstance(entry.get("name"), str):
|
||||||
name = entry.get("name")
|
name = entry["name"]
|
||||||
index.setdefault((name, entry.get("path") or name), []).append(entry)
|
index.setdefault((name, entry.get("path") or name), []).append(entry)
|
||||||
return index
|
return index
|
||||||
|
|
||||||
|
|||||||
+1745
-1314
File diff suppressed because it is too large.
Load diff
@@ -145,7 +145,7 @@ class RetroDeckWritesWhatItCounts(unittest.TestCase):
|
|||||||
written = json.loads(produced["duckstation/component_manifest.json"])
|
written = json.loads(produced["duckstation/component_manifest.json"])
|
||||||
names = [e["filename"] for e in written["duckstation"]["bios"]]
|
names = [e["filename"] for e in written["duckstation"]["bios"]]
|
||||||
self.assertIn("b.bin", names)
|
self.assertIn("b.bin", names)
|
||||||
self.assertFalse(RetroDeck.writable(spread.files[2]))
|
self.assertFalse(RetroDeck().writable(spread.files[2]))
|
||||||
|
|
||||||
|
|
||||||
class HashesTheFormatCannotHold(unittest.TestCase):
|
class HashesTheFormatCannotHold(unittest.TestCase):
|
||||||
@@ -434,8 +434,8 @@ class OneMd5FormatsAddWhole(unittest.TestCase):
|
|||||||
|
|
||||||
several = NativeFile("boot.bin", "boot.bin", "dc", truth={"md5": [A, B, C]})
|
several = NativeFile("boot.bin", "boot.bin", "dc", truth={"md5": [A, B, C]})
|
||||||
single = NativeFile("boot2.bin", "boot2.bin", "dc", truth={"md5": A})
|
single = NativeFile("boot2.bin", "boot2.bin", "dc", truth={"md5": A})
|
||||||
self.assertFalse(RetroBat.writable(several))
|
self.assertFalse(RetroBat().writable(several))
|
||||||
self.assertTrue(RetroBat.writable(single))
|
self.assertTrue(RetroBat().writable(single))
|
||||||
|
|
||||||
|
|
||||||
class BizHawkKeepsItsOwnHashes(unittest.TestCase):
|
class BizHawkKeepsItsOwnHashes(unittest.TestCase):
|
||||||
|
|||||||
+20
-2
@@ -558,7 +558,7 @@ class Reconciliation(unittest.TestCase):
|
|||||||
}
|
}
|
||||||
systems, _ = build_native_model({"systems": {}}, scraped)
|
systems, _ = build_native_model({"systems": {}}, scraped)
|
||||||
entry = systems["nds"].files[0]
|
entry = systems["nds"].files[0]
|
||||||
self.assertTrue(BaseExporter.writable(entry, require="md5"))
|
self.assertTrue(_BaseRule().writable(entry, require="md5"))
|
||||||
|
|
||||||
def test_no_format_drops_what_the_platform_already_declares(self):
|
def test_no_format_drops_what_the_platform_already_declares(self):
|
||||||
"""An export poorer than the file it corrects is not usable."""
|
"""An export poorer than the file it corrects is not usable."""
|
||||||
@@ -579,7 +579,25 @@ class Reconciliation(unittest.TestCase):
|
|||||||
}
|
}
|
||||||
systems, _ = build_native_model(truth, None)
|
systems, _ = build_native_model(truth, None)
|
||||||
entry = systems["nintendo-ds"].files[0]
|
entry = systems["nintendo-ds"].files[0]
|
||||||
self.assertFalse(BaseExporter.writable(entry, require="md5"))
|
self.assertFalse(_BaseRule().writable(entry, require="md5"))
|
||||||
|
|
||||||
|
|
||||||
|
class _BaseRule(BaseExporter):
|
||||||
|
"""A concrete exporter that keeps every rule of the base class."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def platform_name() -> str:
|
||||||
|
return "base"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def native_filename() -> str:
|
||||||
|
return "base"
|
||||||
|
|
||||||
|
def render(self, systems, report, originals, scraped=None):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def validate(self, systems, produced):
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
class ExporterRegistry(unittest.TestCase):
|
class ExporterRegistry(unittest.TestCase):
|
||||||
|
|||||||
Reference in new issue
Block a user