refactor: split common.py into three packages

core: cli (run_cli, input errors, name hints), github (token), paths.
model: sources, database, composition, registry, platforms,
declarations, targets, systems, profiles, cliargs. resolve: content,
ownership, datadirs, archives, localfile, directories, layout,
contentlayout, standalone, grouping, cores.

Definitions move verbatim; common.py and its re-exports are gone and
every importer, patch target and code-in-string names the new home. A
test that stubbed common.load_platform_config stubs each module that
reads the loader by its own name.
This commit is contained in:
Abdessamad Derraz committed 2026-11-18 11:09:13 +01:00
1 parent c784aef883
commit 83cfa6fd0f
281 files changed
+7036 -6794

No files matched your search

+196
View File
@@ -0,0 +1,196 @@
"""Archive members an emulator reads, and the copies of an archive that hold them."""
from __future__ import annotations
import sys
from collections import Counter
from collections.abc import Callable
from core.ziptools import zip_member_crcs, zip_member_names
# id(files) -> (files, len(files), {archive: entries with a crc32}). Callers
# ask once per entry of the same profile: scanning the list each time walked
# 38 million entries in one verify --all over mame.yml. The list is held so
# its id is not reused, a list that changed length is indexed again, and the
# members are read from the entries at each call. Short lists are scanned
# directly: a fresh default [] per call would only fill the cache.
_ARCHIVE_INDEX_MIN = 64
_archive_index: dict[int, tuple[list[dict], int, dict[str | None, list[dict]]]] = {}
def _member(f: dict) -> dict:
member = {"crc32": str(f["crc32"]).lower(), "required": bool(f.get("required", True))}
if f.get("group"):
# One of the members sharing it is enough (alternatives.py).
member["group"] = f["group"]
return member
def _required_met(members: list[dict], held: Callable[[dict], bool]) -> tuple[int, bool]:
"""How many requirements an archive meets, and whether it meets all.
A required member is one requirement, and so is a required set of
alternatives, met when one of its members is held: Odin reads the
first of three Hikaru boot ROMs it finds in hikaru.zip.
"""
from model.alternatives import groups_of
met = 0
complete = True
sets: dict[str, bool] = {}
for m in members:
if not m["required"]:
continue
names = groups_of(m)
if names:
for name in names:
sets[name] = sets.get(name, False) or held(m)
continue
if held(m):
met += 1
else:
complete = False
met += sum(sets.values())
return met, complete and all(sets.values())
def archive_members(archive: str, files: list[dict]) -> list[dict]:
"""The members a profile reads inside *archive*, with what it requires."""
if len(files) < _ARCHIVE_INDEX_MIN:
return [_member(f) for f in files if f.get("archive") == archive and f.get("crc32")]
cached = _archive_index.get(id(files))
if cached is None or cached[0] is not files or cached[1] != len(files):
index: dict[str | None, list[dict]] = {}
for f in files:
if f.get("crc32"):
index.setdefault(f.get("archive"), []).append(f)
cached = _archive_index[id(files)] = (files, len(files), index)
return [_member(f) for f in cached[2].get(archive, ())]
def archive_entry(archive: str, files: list[dict]) -> dict:
"""The entry a profile's archive resolves through.
Its own declaration when it has one (it carries the container's hashes),
and the members it reads inside, so a copy of the name that lacks a ROM
the core requires is not taken for the archive.
"""
own = next(
(f for f in files if f.get("name") == archive and not f.get("archive")),
{"name": archive},
)
members = archive_members(archive, files)
return {**own, "members": members} if members else own
def archive_is_optional(entry: dict, archive: str, files: list[dict]) -> bool:
"""Optional as a whole: its own entry and every member it carries.
A --required-only pack leaves it out, and the report of that pack too.
geolith's _Required pack held neocd.zip and irrmaze.zip all the same.
"""
return entry.get("required") is False and all(
member.get("required") is False
for member in files
if member.get("archive") == archive
)
def holds_required_members(path: str, members: list[dict]) -> bool:
"""Whether an archive holds every member a profile requires inside it."""
crcs = zip_member_crcs(path)
names = zip_member_names(path)
return _required_met(members, lambda m: _member_held(m, crcs, names))[1]
def contents_members(file_entry: dict) -> list[dict]:
"""The members an archive entry's ``contents:`` lists, as ranking keys.
A member is its crc32 where the profile declares one, its name where the
code opens it by name alone: Flycast reads epr-21329.ic27 in
hod2bios.zip by filename, and a copy without it has no Japan BIOS.
A crc32 two members share also keeps the name: fpr23905.ic36 and
fpr23905c.ic36 both have crc32 ffffffff in segadimm.zip, so the crc
alone cannot tell a copy holding one from a copy holding both.
"""
listed = [m for m in file_entry.get("contents") or [] if m.get("crc32") or m.get("name")]
seen = Counter(str(m["crc32"]).lower() for m in listed if m.get("crc32"))
members = []
for m in listed:
if not m.get("crc32"):
members.append({"name": str(m["name"]), "required": True})
continue
crc = str(m["crc32"]).lower()
member = {"crc32": crc, "required": True}
if seen[crc] > 1 and m.get("name"):
member["name"] = str(m["name"])
members.append(member)
return members
def _member_held(member: dict, crcs: frozenset[str], names: frozenset[str]) -> bool:
named = member.get("name", "").rsplit("/", 1)[-1].casefold() in names
if member.get("crc32"):
return member["crc32"] in crcs and ("name" not in member or named)
return named
def _holding_members(paths: list[str], members: list[dict]) -> list[str]:
"""The same-named archives holding the most required members, then the most members.
FBNeo reads neocd.bin and 000-lo.lo inside neocdz.zip. The primary copy,
a set without 000-lo.lo, won on the name while a variant held both.
"""
def held(path: str) -> tuple[int, int]:
crcs = zip_member_crcs(path)
names = zip_member_names(path)
found = {id(m) for m in members if _member_held(m, crcs, names)}
return _required_met(members, lambda m: id(m) in found)[0], len(found)
scores = {path: held(path) for path in paths}
best = max(scores.values(), default=(0, 0))
if best == (0, 0):
# Not one declared member in any copy: the name is all that matches,
# and galgames.zip holding only an assembler listing is not the set.
return []
return [path for path in paths if scores[path] == best]
def _covering_archives(paths: list[str]) -> list[str]:
"""Same-named archives, those holding every ROM each other copy holds.
Without a declared layout, a primary that is a superset of the other
primaries misses nothing any of them holds. Two copies that each hold a
ROM the other lacks are different revisions, and nothing here can
choose: the order is kept. Index order alone used to decide, and
deleting an unrelated duplicate flipped which copy a core received.
"""
# A variant is served only when no primary is, so the primaries are
# the copies this choice is between. A copy in an emulator's own tree
# (bios/Other/<emulator>/) is that emulator's file, not a revision of
# the set: an entry no profile owns is not decided by it.
pool = [
path for path in paths
if "/.variants/" not in path and not path.startswith("bios/Other/")
] or [path for path in paths if "/.variants/" not in path] or paths
crcs = {path: zip_member_crcs(path) for path in pool}
covering = [
path for path in pool
if crcs[path] and all(crcs[other] <= crcs[path] for other in pool)
]
return covering + [path for path in paths if path not in covering]
_unreadable_archives: set[str] = set()
def _warn_unreadable_archive(path: str, exc: Exception) -> None:
"""Say once that an archive on disk cannot be read.
Skipped in silence, a truncated ZIP came out as not_found or
hash_mismatch, which reads as a missing dump instead of a broken one.
"""
if path not in _unreadable_archives:
_unreadable_archives.add(path)
print(f"warning: unreadable archive {path}: {exc}", file=sys.stderr)
+2 -1
View File
@@ -16,7 +16,8 @@ from dataclasses import dataclass, field
from pathlib import Path
from common import _norm_system_id, resolve_platform_cores, unresolved_platform_cores
from model.systems import _norm_system_id
from resolve.cores import resolve_platform_cores, unresolved_platform_cores
from resolve.reconcile import HASH_FIELDS, NativeSystem, _hash_values
from resolve.launchers import _names as launcher_names
+306
View File
@@ -0,0 +1,306 @@
"""The content tests a code runs on a candidate: size, Adler-32, ROMDIR, masked SHA-1, hashes."""
from __future__ import annotations
import functools
import hashlib
import json
import os
from collections.abc import Collection
from typing import TYPE_CHECKING, TypedDict
from core.hashing import compute_hashes
from core.ziptools import check_inside_zip
from model.profiles import CONTENT_CHECKS
if TYPE_CHECKING:
from typing_extensions import Unpack
def name_match_size_ok(file_entry: dict, candidate_size: int | None) -> bool:
"""Whether a candidate found by name may be the file the entry describes.
Generic filenames collide across systems: rom1.bin is a Sony PlayStation 2
firmware and a Roland SC-55mk2 program ROM. A name carries no evidence on
its own, so a size the emulator verifies settles it. A size declared
without ``validation: [size]`` is informative and rejects nothing.
"""
validation = file_entry.get("validation")
if isinstance(validation, dict):
validation = validation.get("core", [])
if "size" not in (validation or []) or candidate_size is None:
return True
return size_fits(file_entry, candidate_size)
def adler32_of(path: str, byteswap: bool = False) -> str:
"""The Adler-32 of a file, over its 16-bit words swapped when asked.
Dolphin swaps every 16-bit word of its DSP ROMs before hashing them
(Common::swap16 in DSPLLE.cpp:LoadDSPRom).
"""
import struct
import zlib
with open(path, "rb") as f:
data = f.read()
if byteswap:
if len(data) % 2:
data += b"\x00"
count = len(data) // 2
data = struct.pack(f">{count}H", *struct.unpack(f"<{count}H", data))
return format(zlib.adler32(data) & 0xFFFFFFFF, "08x")
def _adler32_value(value: object) -> str:
return str(value).lower().removeprefix("0x")
def _held_adler32(name: str, db: dict, byteswap: bool) -> set[str]:
"""The Adler-32 of every copy of a name the collection holds."""
files_db = db.get("files", {})
held: set[str] = set()
for sha1 in db.get("indexes", {}).get("by_name", {}).get(name, []):
path = files_db.get(sha1, {}).get("path", "")
try:
held.add(adler32_of(path, byteswap))
except OSError:
continue
return held
def held_adler32_pair(file_entry: dict, db: dict) -> str | None:
"""The entry's own value in the first pair its code accepts that is held.
Dolphin hashes dsp_rom.bin and dsp_coef.bin together and warns on any
combination outside its table: two files each accepted alone can still
be a pair it refuses. ``adler32_pairs`` lists the accepted pairs, the
entry's own value first, in the code's table order. Both members walk
the same pairs over the same collection, so they settle on one pair.
None when the entry declares no pair or none is held whole.
"""
pairs = file_entry.get("adler32_pairs")
partner = file_entry.get("adler32_pairs_with")
if not pairs or not partner:
return None
byteswap = bool(file_entry.get("adler32_byteswap"))
own = _held_adler32(file_entry.get("name", ""), db, byteswap)
other = _held_adler32(partner, db, byteswap)
for mine, theirs in pairs:
if _adler32_value(mine) in own and _adler32_value(theirs) in other:
return _adler32_value(mine)
return None
def adler32_fits(file_entry: dict, path: str, db: dict | None = None) -> bool:
"""Whether a candidate carries an Adler-32 the entry's code accepts.
Dolphin hashes its DSP ROMs and warns on every pair it does not take
as current: the v0.3.1 free dsp_rom.bin is answered by its path, and
shipped beside the official dsp_coef.bin it is a pair Dolphin rejects.
A value declared without ``validation: [adler32]`` rejects nothing.
With the collection at hand, a candidate outside the held pair the
code accepts (``held_adler32_pair``) is refused too.
"""
validation = file_entry.get("validation")
if isinstance(validation, dict):
validation = validation.get("core", [])
declared = file_entry.get("known_hash_adler32")
if "adler32" not in (validation or []) or not declared:
return True
values = declared if isinstance(declared, list) else [declared]
accepted = {_adler32_value(v) for v in values}
try:
actual = adler32_of(path, bool(file_entry.get("adler32_byteswap")))
except OSError:
return False
if actual not in accepted:
return False
chosen = held_adler32_pair(file_entry, db) if db is not None else None
return chosen is None or actual == chosen
def _core_checks(file_entry: dict) -> list:
validation = file_entry.get("validation")
if isinstance(validation, dict):
validation = validation.get("core", [])
return list(validation or [])
def declared_content_checks(file_entry: dict) -> set[str]:
"""The content tests the entry's code runs on a candidate."""
return set(CONTENT_CHECKS.intersection(_core_checks(file_entry)))
@functools.lru_cache(maxsize=4096)
def _romdir_verdict(path: str, size: int, mtime_ns: int, spec: str) -> bool:
from core.romdir import romdir_accepts
with open(path, "rb") as f:
data = f.read()
return romdir_accepts(data, json.loads(spec))
@functools.lru_cache(maxsize=4096)
def _masked_sha1_verdict(path: str, size: int, mtime_ns: int, spec: str) -> bool:
"""Amiberry's flash image identification (getromdatabydata, rommgr.cpp).
A CyberStorm or Blizzard PPC image carries its board configuration in
bytes 0x10-0x2f, so the table SHA-1 is taken with those bytes cleared,
over the first 0x1c000 bytes, and for a 512 KB file also over the
first 0x50000. ``reads`` lists the file sizes the code tries the
transform on and the lengths it hashes for each.
"""
rules = json.loads(spec)
reads = {int(r["size"]): [int(n) for n in r["lengths"]] for r in rules.get("reads", [])}
if size not in reads:
return False
with open(path, "rb") as f:
data = bytearray(f.read())
start, end = (int(v) for v in rules.get("zeroed", [0, 0]))
data[start:end] = bytes(max(0, min(end, len(data)) - start))
wanted = str(rules.get("sha1", "")).lower()
return any(hashlib.sha1(data[:length]).hexdigest() == wanted for length in reads[size])
def content_fits(file_entry: dict, path: str) -> bool:
"""Whether a candidate passes the content tests its entry declares.
The PCSX2 family lists any file of its BIOS folder whose ROM directory
holds RESET and ROMVER (LoadBiosVersion, pcsx2/ps2/BiosTools.cpp), with
no name and, in most forks, no size: ``validation: [romdir]`` and the
``romdir:`` spec of how that fork reads the table (romdir.py). Amiberry
names a flash image by the SHA-1 of its bytes with the configuration
cleared (``masked_sha1``). A file that cannot be read fails. An entry
declaring no content test accepts every candidate.
"""
checks = declared_content_checks(file_entry)
if not checks:
return True
try:
stat = os.stat(path)
except OSError:
return False
verdicts = {"romdir": _romdir_verdict, "masked_sha1": _masked_sha1_verdict}
for check in sorted(checks):
spec = json.dumps(file_entry.get(check) or {}, sort_keys=True)
try:
if not verdicts[check](path, stat.st_size, stat.st_mtime_ns, spec):
return False
except OSError:
return False
return True
def shape_fits(file_entry: dict, path: str, size: int | None = None) -> bool:
"""Size and content together: what a scan by shape checks per candidate."""
if size is None:
try:
size = os.path.getsize(path)
except OSError:
return False
return size_fits(file_entry, size) and content_fits(file_entry, path)
def declares_shape(file_entry: dict) -> bool:
"""Whether the entry says anything that tells one candidate from another."""
return bool(
file_entry.get("size") or file_entry.get("min_size")
or file_entry.get("max_size") or file_entry.get("size_multiple")
or declared_content_checks(file_entry)
)
def size_fits(file_entry: dict, candidate_size: int) -> bool:
"""Whether a size is one the entry declares.
``size`` is an exact size or the list of sizes the code accepts, and it
outranks a ``min_size``/``max_size`` range. ``size_multiple`` is a
granule the size must be a whole number of, as xemu maps any flash
image whose size is a positive multiple of 64 KiB (hw/xbox/xbox.c).
Nothing declared fits all.
"""
declared = file_entry.get("size")
if declared is not None:
allowed = declared if isinstance(declared, list) else [declared]
return candidate_size in allowed
low = file_entry.get("min_size")
high = file_entry.get("max_size")
if low is not None and candidate_size < low:
return False
if high is not None and candidate_size > high:
return False
multiple = file_entry.get("size_multiple")
return not (multiple and candidate_size % int(multiple))
class DeclaredHashes(TypedDict):
"""What an entry declares about its content, as declared_hash_verdict reads it."""
has_strong_hash: bool
sha1_candidates: Collection[str]
sha256_candidates: Collection[str]
md5_list: list[str]
crc_candidates: Collection[str]
zipped_file: str | None
declared_size: int | list[int] | None
def declared_hash_verdict(
candidate: str,
*,
file_entry: dict | None = None,
db: dict | None = None,
**declared: Unpack[DeclaredHashes],
) -> str:
"""Judge a candidate found by name against everything the entry declares.
A file reached through a directory walk was matched on its filename,
which is the weakest evidence there is. Whatever the entry declares
about its content is checked here before the walk may return it,
including the size and Adler-32 the name steps over bios/ apply.
"""
sha1_candidates = declared["sha1_candidates"]
sha256_candidates = declared["sha256_candidates"]
md5_list = declared["md5_list"]
crc_candidates = declared["crc_candidates"]
zipped_file = declared["zipped_file"]
declared_size = declared["declared_size"]
if not declared["has_strong_hash"]:
if file_entry is not None and not (
name_match_size_ok(file_entry, os.path.getsize(candidate))
and adler32_fits(file_entry, candidate, db)
and content_fits(file_entry, candidate)
):
return "hash_mismatch"
return "data_dir"
algorithms: set[str] = set()
if sha1_candidates:
algorithms.add("sha1")
if sha256_candidates:
algorithms.add("sha256")
if md5_list and not zipped_file:
algorithms.add("md5")
if crc_candidates:
algorithms.add("crc32")
actual = compute_hashes(candidate, frozenset(algorithms)) if algorithms else {}
if sha1_candidates and actual.get("sha1", "").lower() not in sha1_candidates:
return "hash_mismatch"
if sha256_candidates and actual.get("sha256", "").lower() not in sha256_candidates:
return "hash_mismatch"
if md5_list and not zipped_file and not any(
actual.get("md5", "").lower().startswith(expected) for expected in md5_list
):
return "hash_mismatch"
if crc_candidates and actual.get("crc32", "").lower() not in crc_candidates:
return "hash_mismatch"
if crc_candidates and declared_size is not None:
allowed_sizes = declared_size if isinstance(declared_size, list) else [declared_size]
if os.path.getsize(candidate) not in allowed_sizes:
return "hash_mismatch"
if zipped_file and md5_list and not any(
check_inside_zip(candidate, zipped_file, expected) == "ok"
for expected in md5_list
):
return "hash_mismatch"
return "data_dir_hash_exact"
+432
View File
@@ -0,0 +1,432 @@
"""Files a core reads beside the content: rom folders, boards and MAME search sets."""
from __future__ import annotations
import functools
import json
from collections.abc import Callable, Iterable
from model.targets import list_available_targets
from resolve.layout import (
CONTENT_FOLDER_PREFIX,
CONTENT_SCOPE_TAG,
CONTENT_SYSTEM_TAG,
CONTENT_TAG_PREFIXES,
OUTSIDE_BIOS_FOLDER,
ROMS_ROOT,
ROM_SEARCH_PREFIX,
_placed_entry,
outer_layout,
standalone_layout_path,
)
from core.paths import REPO_ROOT
LIBRETRO_RUNNERS = frozenset({"libretro", "retroarch", "retroarch32", "retrorun"})
def _core_key(name: str) -> str:
"""A core name as two platforms spell it alike: mame2003-plus, mame2003_plus."""
return str(name).lower().replace("-", "_")
# Set on a platform config built for one board (generate_pack, verify
# --target): a core a roms folder offers on other boards only is not placed
# there.
TARGET_KEY = "_target"
def _branch_holds(branch: str, board: str) -> bool:
"""Whether one `VARIABLE PATTERN` branch of a device case admits a board.
ROCKNIX files a board under the DEVICE value its target scraper reads,
lowercased. A branch on any other variable (PREFER_GLES) is no board
condition, and admits every board.
"""
variable, _, pattern = branch.strip().partition(" ")
if variable != "DEVICE" or not pattern.strip():
return True
import fnmatch
return any(
fnmatch.fnmatchcase(board.upper(), p.strip().upper()) for p in pattern.split("|")
)
def when_admits(when: str, board: str) -> bool:
"""Whether an offer's `when` holds on a board: alternatives joined by
"; ", each the branches it is nested under joined by ", "."""
return any(
all(_branch_holds(branch, board) for branch in alternative.split(", "))
for alternative in when.split("; ")
)
def offer_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]:
"""The boards on which each roms folder offers each core, by
(core key, folder), None where every board does.
ROCKNIX writes a core under a `case "${DEVICE}"` branch for the devices
it builds (`when`), and a default for a named device in board_defaults
(DEVICE=RK3326). Boards are the platform's targets, aliases included.
"""
platform = str(config.get("_key") or "")
targets = list_available_targets(
platform, str(REPO_ROOT / "platforms")
) if platform else []
names = {t["name"]: [t["name"], *t.get("aliases", [])] for t in targets}
def admitted(test: Callable[[str], bool]) -> set[str]:
return {n for board, spelled in names.items() if test(board) for n in spelled}
every = admitted(lambda _board: True)
found: dict[tuple[str, str], set[str]] = {}
for row in config.get("_rom_folders") or []:
folder = str(row.get("folder") or "")
offers = row.get("offers") or []
offered = {(o.get("emulator"), _core_key(o.get("core") or "")) for o in offers}
choices: list[tuple[dict, set[str]]] = []
if row.get("core") and (row.get("emulator"), _core_key(row["core"])) not in offered:
choices.append((row, every))
for key, spec in (row.get("board_defaults") or {}).items():
branch = str(key).replace("=", " ", 1)
choices.append((spec, admitted(functools.partial(_branch_holds, branch))))
for offer in offers:
when = str(offer.get("when") or "")
choices.append((offer, admitted(functools.partial(when_admits, when))
if when else every))
for choice, boards in choices:
if choice.get("core") and choice.get("emulator") in LIBRETRO_RUNNERS:
found.setdefault((_core_key(choice["core"]), folder), set()).update(boards)
return {
pair: None if not names or boards >= every else frozenset(boards)
for pair, boards in found.items()
}
def content_folder_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]:
"""Each (core key, roms folder) a platform launches a libretro core for,
with the boards it does so on, None for every board."""
pairs: set[tuple[str, str]] = set()
for core, systems in (config.get("libretro_systems") or {}).items():
pairs |= {(_core_key(core), str(s)) for s in systems or []}
for system in (config.get("systems") or {}).values():
if isinstance(system, dict) and system.get("native_id"):
pairs |= {(_core_key(c), str(system["native_id"])) for c in system.get("cores") or []}
for record in config.get("launchers") or []:
if record.get("kind") == "package" and record.get("build") == "libretro":
package = str(record.get("emulator", ""))
if package.startswith("lr-mess"):
# Built with SUBTARGET=mess (lr-mess2016.sh:31): the MESS
# drivers alone, none of the arcade sets of the core it
# shares a repository with.
continue
core = _core_key(package.removeprefix("lr-"))
pairs |= {(core, str(s)) for s in record.get("systems") or []}
# Pairs from the platform's own lists hold on every board, an offer on
# the boards its frontend writes it for.
return {
**{pair: on for pair, on in offer_boards(config).items() if pair not in pairs},
**{pair: None for pair in pairs},
}
def content_folder_tags(config: dict) -> set[str]:
"""The roms folders a platform launches each libretro core for, and the
ROM search paths its commands hand emulators and cores, as tags.
A core reading its BIOS sets beside the game (MAME 2003's osd_get_path
gives FILETYPE_ROM the content directory) reads them in the folder of
the system it is launched for. The folders come from the platform's own
lists: ``libretro_systems``, every core a folder of its rom folders file
offers (its default, its board defaults, ``offers``), the cores a system
offers under its own name, and the systems a RetroPie package registers.
A platform with no roms root, or one keeping no folder per system
(RetroArch, Lakka), gives none.
"""
if config.get("inherits_from") == "emulatorjs":
# EmulatorJS writes the BIOS a frontend hands it and the game to
# the root of one filesystem (data/src/emulator.js:845, 990, 1054):
# RomM's firmware folder is beside the content.
return {CONTENT_SYSTEM_TAG}
tags = {CONTENT_SCOPE_TAG}
if outer_layout(config, ROMS_ROOT) is None:
return tags
rows = config.get("_rom_folders") or []
folders = {str(r.get("folder")) for r in rows if r.get("folder")}
boards = content_folder_boards(config)
target = config.get(TARGET_KEY)
pairs = {pair for pair, on in boards.items() if not target or on is None or target in on}
from resolve.launchers import _roms_place
def place(folder: str) -> list:
return list(_roms_place(config, folder) or ())
# Without a board, a core a folder offers on some boards only carries
# them, for a manifest the installer narrows to one.
tags |= {
CONTENT_FOLDER_PREFIX + json.dumps([
c, f, place(f),
None if target or (offered_on := boards.get((c, f))) is None else sorted(offered_on),
])
for c, f in pairs if f in folders
}
for row in rows:
for search in row.get("searched_by") or []:
for read in search.get("reads") or []:
if read in folders:
tags.add(ROM_SEARCH_PREFIX + json.dumps([
str(search.get("core") or search["emulator"]), place(read),
str(row["folder"]), sorted(search.get("machines") or []),
bool(search.get("any_machine")), str(search.get("source_ref", "")),
"libretro" if search.get("core") else "standalone",
]))
return tags
# The machines ES-DE runs from a folder whose command starts the game itself
# (%BASENAME%), by the folder's system: its BIOS root, the driver source
# files of its board, or a device its machines carry. A system not listed
# holds any machine.
ANY_MACHINE_POPULATIONS: dict[str, tuple[str, tuple[str, ...]]] = {
"neogeo": ("bios", ("neogeo",)),
"stv": ("bios", ("stvbios",)),
"cps": ("source", ("capcom/cps1.cpp", "capcom/cps2.cpp", "capcom/cps3.cpp")),
"cps1": ("source", ("capcom/cps1.cpp",)),
"cps2": ("source", ("capcom/cps2.cpp",)),
"cps3": ("source", ("capcom/cps3.cpp",)),
"model2": ("source", ("sega/model2.cpp",)),
"model3": ("source", ("sega/model3.cpp",)),
"daphne": ("device_source", ("devices/machine/ld",)),
"laserdisc": ("device_source", ("devices/machine/ld",)),
"gameandwatch": ("source", ("handheld/",)),
"lcdgames": ("source", ("handheld/",)),
}
@functools.lru_cache(maxsize=8)
def _arcade_relation(profile_key: str) -> dict | None:
"""games/arcade/<profile>.json: the BIOS and device sets each game set
loads, from the -listxml of the version the profile pins."""
path = REPO_ROOT / "games" / "arcade" / f"{profile_key}.json"
if not path.is_file():
return None
with path.open(encoding="utf-8") as f:
return json.load(f)
def rom_search_sets(
profile_key: str, system: str, machines: Iterable[str], any_machine: bool,
) -> frozenset[str]:
"""The sets a command reads from the ROM search path it passes.
The machines it starts, the BIOS sets on their romof chain and the
device sets with ROMs they instantiate, as the -listxml records them.
A command starting the game itself reads them for each machine its
folder holds (ANY_MACHINE_POPULATIONS).
"""
return _rom_search_sets(profile_key, system, tuple(sorted(machines)), any_machine)
@functools.lru_cache(maxsize=256)
def _rom_search_sets(
profile_key: str, system: str, machines: tuple[str, ...], any_machine: bool,
) -> frozenset[str]:
relation = _arcade_relation(profile_key)
if relation is None:
return frozenset()
bios, devices = relation.get("bios") or {}, relation.get("devices") or {}
# A clone reads the ROMs it shares with its parent from the parent's
# archive: the search path is the set and every ancestor
# (src/emu/driver.cpp:31-38, src/emu/romload.cpp:67-84 at mame0289).
parents = relation.get("parents") or {}
sources = relation.get("sources") or {}
members: set[str] = set(machines)
kind, keys = ANY_MACHINE_POPULATIONS.get(system, ("all", ())) if any_machine else ("", ())
if kind == "bios":
members |= {g for k in keys for g in bios.get(k) or []} | set(keys)
elif kind == "source":
members |= {g for src, sets in sources.items() if src.startswith(keys) for g in sets}
elif kind == "device_source":
carried = {d for src, sets in sources.items() if src.startswith(keys) for d in sets}
members |= {g for d in carried for g in devices.get(d) or []}
def used(users: list[str]) -> bool:
return kind == "all" or not members.isdisjoint(users)
found = {b for b, users in bios.items() if used(users)}
found |= {p for p, users in parents.items() if used(users)}
found |= {d for d, users in devices.items() if used(users)}
return frozenset(found | members)
def _search_reads(emu_name: str, searches: list, name: str) -> list[tuple[str, str]]:
"""The (tree, folder) places a passed ROM search reads this set from."""
stem = name.rsplit(".", 1)[0]
return sorted({
tuple(where) for _emu, where, system, machines, any_machine, _ref, _build in searches
if where and stem in rom_search_sets(emu_name, system, machines, any_machine)
})
def _roms_entry(entry: dict, tree: str, folder: str, rel: str) -> dict:
"""The entry placed in a roms folder."""
# Below the roms root inside the install tree (EmuELEC's
# /storage/roms): a plain dest the platform prefix skips, as a
# standalone entry placed there (_placed_entry).
where: dict[str, object] = (
{"unprefixed": True} if tree == "install" else {"root": ROMS_ROOT}
)
return {**entry, **where, "path": f"{folder}/{rel}", "layout_path": rel}
def _content_folder_boards(tags: list[str], names: set[str]) -> dict[tuple, set[str] | None]:
"""Each roms folder the platform launches the core from, with its boards."""
# A place keeps the boards its core is offered on there, every board
# when one folder offers it everywhere.
on_boards: dict[tuple, set[str] | None] = {}
for core, _folder, where, on in (
json.loads(t[len(CONTENT_FOLDER_PREFIX):])
for t in tags if t.startswith(CONTENT_FOLDER_PREFIX)
):
if core not in names or not where:
continue
place = tuple(where)
known = on_boards.get(place, set())
on_boards[place] = None if on is None or known is None else known | set(on)
return on_boards
def _libretro_content_layout(
emu_name: str, view: dict, tags: list[str], names: set[str], searches: list,
) -> dict:
"""The libretro layout with each file read beside the content placed there."""
on_boards = _content_folder_boards(tags, names)
folders = sorted(on_boards)
# The folders a passed `-rompath` replaces the build's own search
# path with stand for these: libretro MAME hands MAME
# <system>/mame/bios unless the content's command line names
# another (retro_init.cpp Set_Path_Option, execute_game_cmd).
from resolve.launchers import pool_folders
pools = set(pool_folders({"standalone_pools": view.get("libretro_pools")}).values())
out: list = []
changed = False
for f in view.get("files") or []:
if not isinstance(f, dict):
out.append(f)
continue
if _content_load(f) != "content_dir" or f.get("category") == "game_data":
# Game data read beside the content is the game's own.
out.append(f)
parent, _, rel = str(f.get("path") or "").rpartition("/")
if searches and parent in pools and rel:
reads = _search_reads(emu_name, searches, rel)
changed |= bool(reads)
out.extend(_roms_entry(f, tree, folder, rel) for tree, folder in reads)
continue
changed = True
plain = _without_libretro_load(f)
if not folders:
out.append({**plain, "unplaced": OUTSIDE_BIOS_FOLDER})
continue
rel = str(f.get("path") or f.get("name") or "")
out.extend(
{**_roms_entry(plain, tree, folder, rel),
**({"boards": sorted(on)} if (on := on_boards[(tree, folder)]) is not None else {})}
for tree, folder in folders
)
return {**view, "files": out} if changed else view
def _standalone_content_layout(emu_name: str, view: dict, searches: list) -> dict:
"""The standalone layout with each set a passed search reads placed there."""
pools = {str(v).strip("/") for v in (view.get("standalone_pools") or {}).values()}
if not searches or "" not in pools:
return view
out: list = []
changed = False
for f in view.get("files") or []:
layout = (
(f.get("layout_path") or standalone_layout_path(f, view)) if isinstance(f, dict) else None
)
if not layout or "/" in layout:
out.append(f)
continue
reads = _search_reads(emu_name, searches, layout)
if f.get("unplaced") != OUTSIDE_BIOS_FOLDER:
# A set a launcher record placed stays there: EmuDeck's
# mame.ini rompath is read when Steam ROM Manager starts MAME
# with no `-rompath` (tools/launchers/mame.sh), and ES-DE's
# commands read the folders they pass.
out.append(f)
held = {(f.get("root") or "", f.get("standalone_path") or "")}
extra = [
_placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
]
extra = [e for e in extra if (e.get("root") or "", e["standalone_path"]) not in held]
changed |= bool(extra)
out.extend(extra)
continue
if not reads:
out.append(f)
continue
changed = True
placed = {k: v for k, v in f.items() if k != "unplaced"}
out.extend(
_placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
)
return {**view, "files": out} if changed else view
def content_layout(
emu_name: str, view: dict, standalone: bool, standalone_cores: Iterable[str],
) -> dict:
"""The layout with each file read in a roms folder placed in that folder.
A libretro entry read beside the content (``load_from: content_dir``)
goes to the folder of each system the platform launches the core for,
and is named as read outside the BIOS folder where it knows none. An
entry in the folder a passed ROM search path stands for (the root of a
standalone layout, a ``libretro_pools`` folder) also goes to each folder
a command passes for a machine that reads it, and a standalone entry no
launcher record places goes there only. Outside a platform (no
CONTENT_SCOPE_TAG) the view is left as it is.
"""
tags = [t for t in standalone_cores if t.startswith(CONTENT_TAG_PREFIXES)]
if CONTENT_SYSTEM_TAG in tags and not standalone:
files = [
_without_libretro_load(f)
if isinstance(f, dict) and _content_load(f) == "content_dir"
and f.get("category") != "game_data" else f
for f in view.get("files") or []
]
return {**view, "files": files}
if CONTENT_SCOPE_TAG not in tags:
return view
names = {_core_key(n) for n in {emu_name, *(str(c) for c in view.get("cores") or [])}}
searches = [
json.loads(t[len(ROM_SEARCH_PREFIX):])
for t in tags if t.startswith(ROM_SEARCH_PREFIX)
]
build = "standalone" if standalone else "libretro"
searches = [s for s in searches if _core_key(s[0]) in names and s[6] == build]
if not standalone:
return _libretro_content_layout(emu_name, view, tags, names, searches)
return _standalone_content_layout(emu_name, view, searches)
def _content_load(entry: dict) -> str:
load_from = entry.get("load_from") or ""
if isinstance(load_from, dict):
load_from = load_from.get("libretro") or ""
return str(load_from)
def _without_libretro_load(entry: dict) -> dict:
"""The entry without the libretro build's load_from: its folder is now its path."""
load_from = entry.get("load_from")
rest = {k: v for k, v in entry.items() if k != "load_from"}
if isinstance(load_from, dict) and load_from.get("standalone"):
rest["load_from"] = {"standalone": load_from["standalone"]}
return rest
+418
View File
@@ -0,0 +1,418 @@
"""The emulator profiles a platform runs, per target and per system."""
from __future__ import annotations
import functools
import sys
from collections.abc import Collection
from core.cli import suggest_names
from core.paths import sanitize_pack_path
from model.platforms import load_platform_config
from model.profiles import preferred_profile, upstream_profile_index
from model.systems import _norm_system_id, select_systems
from model.targets import list_available_targets, load_target_config
from core.paths import REPO_ROOT
def without_profile_blind(
platforms: list[str],
flags: list[str],
platforms_dir: str,
profiles: dict[str, dict],
target_cores: dict[str, set[str] | None] | None,
is_all: bool,
) -> list[str]:
"""The platforms a narrowing read from profiles can apply to.
Regions, search order and game data are read from the profiles of the
cores a platform runs. MiSTer and BizHawk declare `cores: []`: a
--region, --one-per-slot or --no-game-data pack of theirs withdrew
nothing while its name and README said it had. A named platform is
refused (exit 1). Under --all it is left out with a notice. generate_pack
and verify both read this.
"""
if not flags:
return platforms
blind = [
name for name in platforms
if not resolve_platform_cores(
load_platform_config(name, platforms_dir),
profiles,
target_cores=(target_cores or {}).get(name),
)
]
for name in blind:
message = (
f"{name} runs no core a profile describes, and {', '.join(flags)} "
"reads the profiles"
)
if not is_all:
print(f"ERROR: {message}: drop {', '.join(flags)}", file=sys.stderr)
sys.exit(1)
print(f" {message}: left out")
return [name for name in platforms if name not in blind]
def resolve_platform_cores(
config: dict,
profiles: dict[str, dict],
target_cores: set[str] | None = None,
) -> set[str]:
"""Resolve which emulator profiles are relevant for a platform.
Resolution strategies (by priority):
1. cores: "all_libretro" -- all profiles with libretro in type
2. cores: [list] -- profiles whose dict key matches a core name
3. cores: absent, fallback to systems intersection
Alias profiles are always excluded (they point to another profile).
If target_cores is provided, result is intersected with it.
"""
result, downloaded_only = _platform_profiles(config, profiles)
if target_cores is not None:
result = result & designated_profiles(profiles, target_cores)
result -= {
profile for profile, names in downloaded_only.items()
if not downloadable_on(target_cores, names)
}
return result
def downloaded_only_profiles(
config: dict, profiles: dict[str, dict]
) -> dict[str, frozenset[str]]:
"""The profiles a platform reaches only through its RetroArch core
downloader, each with the installable names that reach it."""
return _platform_profiles(config, profiles)[1]
def _platform_profiles(
config: dict, profiles: dict[str, dict]
) -> tuple[set[str], dict[str, frozenset[str]]]:
cores_config = config.get("cores")
platform_key = str(config.get("_key") or "")
downloaded_only: dict[str, set[str]] = {}
# The builds the platform compiles itself, by the names they answer to.
# Such a name means that build there, and another revision of the same
# project is not what the platform runs: ROCKNIX and RetroPie build only
# standalone Amiberry, Recalbox its standalone and libretro Amiberry 8.2.2.
# Only a platform listing the name both ways (dual_mode_cores) beside a
# standalone-only build of its own runs the buildbot core too (RetroBat).
# A core of another project under the name stays: RetroPie builds
# minivmac37 standalone beside the minivmac core.
own_builds = {
name: p for name, p in profiles.items()
if platform_key and platform_key in (p.get("built_by") or [])
}
def replaced_by_own(name: str, p: dict, libretro_only: bool = False) -> bool:
if platform_key in (p.get("built_by") or []):
return False
names = {name, *(str(c) for c in p.get("cores") or [])}
return any(
(not libretro_only or "libretro" in str(q.get("type", "")))
and q.get("source") == p.get("source")
and names & {key, *(str(c) for c in q.get("cores") or [])}
for key, q in own_builds.items()
)
def every_libretro() -> set[str]:
# A build only some platforms compile (built_by) is absent from the
# buildbot RetroArch installs from, so it is reached by name, or as one
# of the libretro cores of a platform that compiles it: ROCKNIX ships
# yabadabadoo with its RetroArch and names it nowhere else.
return {
name
for name, p in profiles.items()
if "libretro" in p.get("type", "") and p.get("type") != "alias"
and (
not p.get("built_by")
or (platform_key and platform_key in p["built_by"])
)
and not replaced_by_own(name, p)
}
if cores_config == "all_libretro":
result = every_libretro()
elif isinstance(cores_config, list):
# An emulator the platform launches standalone runs there even when
# its own list names only the cores: Batocera's es_systems.yml files
# lexaloffle and gsplus as standalone emulators and nowhere else. A
# core its RetroArch installs from the buildbot is a libretro build
# and designates libretro profiles only (below): Batocera downloads
# the linuxloader core and runs no standalone Linux Loader.
core_set = {str(c) for c in cores_config} | {
str(c) for c in config.get("standalone_cores") or []
}
index = upstream_profile_index(profiles)
platform = str(config.get("_key") or "")
dual_names = {str(c) for c in config.get("dual_mode_cores") or []}
def build_modes(p: dict) -> set[str]:
kind = str(p.get("type", ""))
return {mode for mode in ("standalone", "libretro") if mode in kind}
def designated(name: str) -> set[str]:
# A build the platform compiles itself (built_by) is what its
# name means there: Recalbox's uae4all is Chips-fr/uae4all-rpi,
# RetroPie's the standalone uae4all2 under the same name. A
# platform building one name in several revisions, one per board,
# runs all of them: RetroPie's amiberry is 5.7.2 and 6.3.3 on x86.
own = {
p for p in index.get(name, ())
if platform and platform in (profiles[p].get("built_by") or [])
}
preferred = preferred_profile(index, name)
if not own:
return {preferred} if preferred is not None else set()
# The own builds stand for the modes they are built in only.
# Batocera builds LRPS2 as pcsx2_libretro.so and launches
# standalone PCSX2 under the same name.
own_modes = set().union(*(build_modes(profiles[p]) for p in own))
if (
name in dual_names
and preferred is not None
and preferred not in own
and not build_modes(profiles[preferred]) & own_modes
):
own.add(preferred)
return own
result = {profile for c in core_set for profile in designated(c)}
# A name the platform launches both ways designates its libretro
# build too. Batocera, Recalbox and RetroBat run pcsx2 standalone and
# as LRPS2, two profiles: the key match kept the standalone one and
# LRPS2's files never reached their packs. A core its RetroArch
# installs is a libretro build as well (amiberry's buildbot core
# beside Batocera's standalone amiberry).
def libretro_builds(name: object) -> set[str]:
return {
profile
for profile in index.get(str(name), set())
if "libretro" in str(profiles[profile].get("type", ""))
and not profiles[profile].get("built_by")
and not replaced_by_own(profile, profiles[profile], libretro_only=True)
}
dual = {p for c in config.get("dual_mode_cores") or [] for p in libretro_builds(c)}
# A core reached only through the RetroArch downloader runs on the
# boards whose downloader offers it: Batocera's x86_64 RetroArch
# installs the amiberry core, its armv7 and aarch64 boards cannot.
# Every installable name counts: Batocera's x86_64 downloader offers
# nside_sfc_balanced, not the higan_sfc_balanced it also lists.
for c in config.get("installable_cores") or []:
for profile in libretro_builds(c) - dual - result:
downloaded_only.setdefault(profile, set()).add(str(c))
result |= dual | set(downloaded_only)
# Support "all_libretro" as a list element: combines all libretro
# profiles with explicitly listed standalone cores (e.g. RetroDECK
# ships RetroArch + standalone emulators)
if "all_libretro" in core_set or "retroarch" in core_set:
result |= every_libretro()
else:
# Fallback: system ID intersection with normalization
norm_plat_systems = {_norm_system_id(s) for s in config.get("systems", {})}
result = {
name
for name, p in profiles.items()
if {_norm_system_id(s) for s in p.get("systems", [])} & norm_plat_systems
and p.get("type") != "alias"
and not p.get("built_by")
}
return result, {p: frozenset(names) for p, names in downloaded_only.items()}
@functools.lru_cache(maxsize=1)
def _retroarch_target_sets() -> tuple[frozenset[str], ...]:
platforms = str(REPO_ROOT / "platforms")
return tuple(
frozenset(found)
for t in list_available_targets("retroarch", platforms)
if (found := load_target_config("retroarch", t["name"], platforms))
)
def downloadable_on(target_cores: set[str], names: Collection[str]) -> bool:
"""Whether a board's core set holds a RetroArch download list offering
one of `names`.
A board with a downloader carries a whole RetroArch targets entry in its
set (load_target_config, `downloads`), a board without one only what it
builds.
"""
return any(
found <= target_cores and not found.isdisjoint(names)
for found in _retroarch_target_sets()
)
def unresolved_platform_cores(config: dict, profiles: dict[str, dict]) -> set[str]:
"""The core names a platform lists that no profile answers to.
resolve_platform_cores drops them without a word: ROCKNIX's `dolphin-sa`
or Batocera's `wine` designate no profile, so nothing is known of the
files they open. `retroarch` and `all_libretro` stand for every libretro
profile and are never unresolved. A platform without a `cores:` list
names no core.
"""
cores_config = config.get("cores")
if not isinstance(cores_config, list):
return set()
index = upstream_profile_index(profiles)
return {
name
for name in (str(c) for c in cores_config)
if name not in ("retroarch", "all_libretro") and not index.get(name)
}
def designated_profiles(profiles: dict[str, dict], names: set[str]) -> set[str]:
"""The profiles a list of upstream core names designates.
The buildbot and es_systems name cores their own way (`mednafen_psx` for
beetle_psx), and a profile's `cores:` lists those names. A name no profile
claims stands for itself.
"""
index = upstream_profile_index(profiles, include_aliases=True)
return {profile for c in names for profile in index.get(c, {c})}
def _destination_cores(profiles: dict[str, dict]) -> dict[str, set[str]]:
"""Each lowercased destination with a directory -> the cores reading it."""
dest_cores: dict[str, set[str]] = {}
for name, p in profiles.items():
if p.get("type") == "alias":
continue
for f in p.get("files", []):
for key in ("path", "standalone_path"):
dest = f.get(key)
if not isinstance(dest, str):
continue
if dest.endswith("/"):
dest += f.get("name", "")
dest = sanitize_pack_path(dest).lower()
if "/" in dest:
dest_cores.setdefault(dest, set()).add(name)
return dest_cores
def system_core_reach(
systems: dict[str, dict],
profiles: dict[str, dict],
platform_cores: set[str] | None,
) -> dict[str, set[str] | None]:
"""For each platform system, the cores whose presence keeps it.
A system is reachable if at least one core that emulates it is available.
Only cores relevant to the platform (platform_cores) can rule a system
out: a system whose cores are all outside the platform's scope maps to
None, kept whatever is available, there being no information to exclude
it.
"""
_norm_sid = _norm_system_id
# Normalized system -> cores, from ALL profiles
norm_system_cores: dict[str, set[str]] = {}
for name, p in profiles.items():
if p.get("type") == "alias":
continue
for sid in p.get("systems", []):
norm_system_cores.setdefault(_norm_sid(sid), set()).add(name)
# Platform-scoped mapping (for distinguishing "no info" from "known but off-target")
norm_plat_system_cores: dict[str, set[str]] = {}
if platform_cores is not None:
for name in platform_cores:
p = profiles.get(name, {})
for sid in p.get("systems", []):
norm_plat_system_cores.setdefault(_norm_sid(sid), set()).add(name)
# A platform can file a system under an id no profile uses: Batocera's
# enterprise-64-128 is ep128emu's enterprise-64 and enterprise-128, and
# only CLK, off most targets, carries the joined id. The destinations a
# system declares name the cores that read its files. A bare name proves
# nothing (bios.bin belongs to many systems), so only a path counts.
# The evidence only keeps: a path shared with an off-target core says
# nothing of the other files, and Batocera's bbc runs on MAME, which no
# profile ties to bbcb.zip, while CLK reads two of its ROMs.
dest_cores = _destination_cores(profiles)
reach: dict[str, set[str] | None] = {}
for sys_id, sys_data in systems.items():
norm_key = _norm_sid(sys_id)
if not norm_plat_system_cores.get(norm_key):
reach[sys_id] = None
continue
file_cores = {
core
for fe in sys_data.get("files", [])
for core in dest_cores.get(
sanitize_pack_path(fe.get("destination") or fe.get("name", "")).lower(),
(),
)
}
reach[sys_id] = file_cores | norm_system_cores.get(norm_key, set())
return reach
def filter_systems_by_target(
systems: dict[str, dict],
profiles: dict[str, dict],
target_cores: set[str] | None,
platform_cores: set[str] | None = None,
) -> dict[str, dict]:
"""Filter platform systems to only those reachable by target cores.
Returns the filtered systems dict (or all if no target).
"""
if target_cores is None:
return systems
available = designated_profiles(profiles, target_cores)
reach = system_core_reach(systems, profiles, platform_cores)
return {
sys_id: sys_data
for sys_id, sys_data in systems.items()
if (cores := reach[sys_id]) is None or cores & available
}
def platform_scope_systems(
config: dict,
profiles: dict[str, dict],
target_cores: set[str] | None,
system_filter: list[str] | None = None,
) -> dict[str, dict]:
"""The systems a pack or a report of a platform covers.
Those a core of the target runs, then the ones a --system list keeps.
verify.py and generate_pack.py read this one function.
"""
plat_cores = resolve_platform_cores(config, profiles) if target_cores else None
systems = filter_systems_by_target(
config.get("systems", {}), profiles, target_cores, platform_cores=plat_cores
)
return select_systems(systems, system_filter) if system_filter else systems
def system_scope_error(
config: dict, platform_name: str, system_filter: list[str], target: str | None
) -> str:
"""Why a --system list leaves a platform no system.
A system the platform declares but no core of the target runs was
reported as a system the platform lacks, with a lookalike to try and a
listing that refuses --target.
"""
systems = config.get("systems", {})
declared = select_systems(systems, system_filter)
if declared and target:
return (
f"no core {platform_name} runs on target {target} emulates "
f"{', '.join(sorted(declared))}"
)
hint = suggest_names(
system_filter, sorted(systems), f"--platform {platform_name} --list-systems"
)
return f"{platform_name} has no system matching {', '.join(system_filter)}. {hint}"
+121
View File
@@ -0,0 +1,121 @@
"""Finding a declared file inside the cached data directories."""
from __future__ import annotations
import filecmp
import os
from collections.abc import Callable
from resolve.content import adler32_fits, content_fits, name_match_size_ok
def _resolve_in_data_dirs(
names_to_try: list[str],
data_dir_registry: dict,
verdict: Callable[[str], str],
) -> tuple[tuple[str, str] | None, str | None]:
"""Look for one of these names in the cached data directories.
Returns the first candidate whose content satisfies the entry, and
separately the first that answered to the name but contradicted it: a
name match alone never decides, so the caller reports the contradiction
rather than shipping the file.
"""
mismatch: str | None = None
for dd_entry in data_dir_registry.values():
cache_dir = dd_entry.get("local_cache", "")
if not cache_dir or not os.path.isdir(cache_dir):
continue
for try_name in names_to_try:
candidate = os.path.join(cache_dir, try_name)
if os.path.isfile(candidate):
status = verdict(candidate)
if status != "hash_mismatch":
return (candidate, status), mismatch
mismatch = mismatch or candidate
# The declared path may not be where the cache put it, so the tree
# is searched for the bare filename, case-insensitively, in the order
# a walk meets it.
basename_targets = {
(n.rsplit("/", 1)[-1] if "/" in n else n).casefold()
for n in names_to_try
}
index = _data_dir_basenames(cache_dir)
found = sorted(
(order, path)
for target in basename_targets
for order, path in index.get(target, ())
)
for _order, candidate in found:
status = verdict(candidate)
if status != "hash_mismatch":
return (candidate, status), mismatch
mismatch = mismatch or candidate
return None, mismatch
def _data_dir_tail(
dest_hint: str, data_dir_registry: dict, file_entry: dict, db: dict
) -> str | None:
"""The cached data-directory file at the destination's own tail.
The full destination first, then without its leading segment, never
down to the bare name. A shortened tail two caches hold with different
bytes proves nothing. The size and Adler-32 the code checks still bound
the file, as on every name or path step without a hash.
"""
parts = dest_hint.split("/")
for start in range(min(2, len(parts) - 1)):
tail = "/".join(parts[start:])
hits = [
os.path.join(cache_dir, tail)
for cache_dir in (
dd_entry.get("local_cache", "") for dd_entry in data_dir_registry.values()
)
if cache_dir and os.path.isfile(os.path.join(cache_dir, tail))
]
if start and any(
not filecmp.cmp(hits[0], other, shallow=False) for other in hits[1:]
):
continue
for candidate in hits:
if name_match_size_ok(
file_entry, os.path.getsize(candidate)
) and adler32_fits(file_entry, candidate, db) and content_fits(
file_entry, candidate
):
return candidate
return None
# Basename index per data-directory cache. Walking the whole tree again for
# every unresolved name made resolution O(names x tree) on each pack build.
_data_dir_index: dict[str, dict[str, list[tuple[int, str]]]] = {}
def _data_dir_basenames(cache_dir: str) -> dict[str, list[tuple[int, str]]]:
"""Casefolded basename -> (walk order, path) of every file in a cache.
Keyed by the tree's identity as well as its path: a refresh swaps in a
new directory under the same name, and an index of the old one named
files that were gone.
"""
try:
stat = os.stat(cache_dir)
except OSError:
return {}
key = f"{os.path.realpath(cache_dir)}:{stat.st_dev}:{stat.st_ino}"
if key not in _data_dir_index:
index: dict[str, list[tuple[int, str]]] = {}
order = 0
for root, _dirs, fnames in os.walk(cache_dir):
for fname in fnames:
index.setdefault(fname.casefold(), []).append((order, os.path.join(root, fname)))
order += 1
_data_dir_index[key] = index
return _data_dir_index[key]
def forget_data_dir_index() -> None:
"""Drop the basename indexes, after a data directory was refreshed."""
_data_dir_index.clear()
+122
View File
@@ -0,0 +1,122 @@
"""Entries that name a directory, expanded to the files the collection holds under it."""
from __future__ import annotations
_directory_members_cache: dict[int, tuple[dict, dict[str, dict[str, str]]]] = {}
def directory_members(db: dict, directory: str) -> dict[str, str]:
"""Files the collection holds under a directory an emulator reads whole.
Returns {destination: sha1}, each destination starting with the directory
as the profile writes it. The collection and the destination meet on a
tail, so the members are the indexed tails that begin with it.
A generic directory name can sit in two unrelated trees (``voice/``,
``data/``). Members that do not share one parent, or a destination two
contents claim, would merge them into one emulator's directory: nothing
is returned and the entry stays a reported gap.
"""
tail = directory.strip("/")
if not tail:
return {}
by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {})
cached = _directory_members_cache.get(id(by_path_suffix))
if cached is None or cached[0] is not by_path_suffix:
cached = (by_path_suffix, {})
_directory_members_cache[id(by_path_suffix)] = cached
if tail in cached[1]:
return cached[1][tail]
prefix = f"{tail}/"
infix = f"/{prefix}"
held: dict[str, list[str]] = {}
parent: dict[str, str] = {}
for key, sha1s in by_path_suffix.items():
if key.startswith(prefix):
held[key] = sha1s
continue
at = key.find(infix)
if at > 0:
member = key[at + 1:]
if len(key[:at]) > len(parent.get(member, "")):
parent[member] = key[:at]
held = {
dest: sha1s for dest, sha1s in held.items() if "/.variants/" not in dest
}
one_tree = len({parent.get(dest, "") for dest in held}) <= 1
one_content = all(len(sha1s) == 1 for sha1s in held.values())
members = (
{dest: held[dest][0] for dest in sorted(held)}
if one_tree and one_content
else {}
)
cached[1][tail] = members
return members
def expand_directory_entries(
files: list[dict], db: dict, standalone: bool = False
) -> list[dict]:
"""Replace each ``type: directory`` entry by the files held under it.
A profile declares the directory its code walks, but what a pack can carry
is the files. Each member keeps the entry's fields and is pinned to the
content the collection holds at that destination. A directory nothing
answers is kept as declared, one gap, and a member the profile also
names as a file is left to that entry.
"""
def destination(entry: dict) -> str:
chosen = entry.get("standalone_path") if standalone else None
return chosen or entry.get("path") or entry.get("name", "")
if not any(entry.get("type") == "directory" for entry in files):
return files
# A file the profile names itself is left to that entry, in the same
# build and below the same root: MAME's libretro floppy samples share
# their path with the standalone tree RetroPie reads below roms/.
other_build = "libretro" if standalone else "standalone"
named = {
(entry.get("root") or "", destination(entry)) for entry in files
if entry.get("type") != "directory" and entry.get("mode") != other_build
}
expanded: list[dict] = []
for entry in files:
if entry.get("type") != "directory":
expanded.append(entry)
continue
target = destination(entry)
# A directory a platform moved (platform_layouts) is the profile's
# tree at the platform's place: the collection holds it under the
# layout path, and the platform's folder proves nothing (RetroDECK
# hands MAME samplepath $bios_path/mame-sa/samples).
layout = str(entry.get("layout_path") or "") if standalone else ""
members = directory_members(db, layout) if layout else {}
if not members:
# A layout tail two trees answer (MAME's hash/) leaves the
# platform's own tail.
layout = ""
members = directory_members(db, target)
if layout and layout.strip("/") != target.strip("/"):
source, place = layout.strip("/") + "/", target.strip("/") + "/"
members = {
place + dest[len(source):]: sha1
for dest, sha1 in members.items() if dest.startswith(source)
}
if not members:
expanded.append(entry)
continue
inherited = {
key: value
for key, value in entry.items()
if key not in ("type", "standalone_path", "layout_path")
}
expanded.extend(
{**inherited, "name": dest, "path": dest, "sha1": sha1}
for dest, sha1 in members.items()
if (entry.get("root") or "", dest) not in named
)
return expanded
+1 -1
View File
@@ -15,7 +15,7 @@ from __future__ import annotations
from dataclasses import dataclass
from common import resolve_platform_cores
from resolve.cores import resolve_platform_cores
from resolve.categories import GAME_DATA, EntryCategories
+92
View File
@@ -0,0 +1,92 @@
"""Platforms whose packs are identical, grouped under one build."""
from __future__ import annotations
import hashlib
import json
import os
from model.platforms import load_platform_config
from model.sources import source_yaml
from resolve.layout import CORE_DIR_PREFIX
from resolve.standalone import standalone_set
def group_identical_platforms(
platforms: list[str],
platforms_dir: str,
target_cores_cache: dict[str, set[str] | None] | None = None,
) -> list[tuple[list[str], str]]:
"""Group platforms that produce identical packs.
A pack is the platform's own files plus those of the emulators it runs,
so two platforms share one only when both agree. base_destination does
not separate them: destinations inside a pack are relative to it.
Returns [(group_of_platform_names, representative), ...].
The representative is the root platform (one that does not inherit).
"""
fingerprints: dict[str, list[str]] = {}
representatives: dict[str, str] = {}
inherits: dict[str, bool] = {}
for platform in platforms:
try:
raw_path = os.path.join(platforms_dir, f"{platform}.yml")
with open(raw_path) as f:
raw = source_yaml(f) or {}
inherits[platform] = "inherits" in raw
config = load_platform_config(platform, platforms_dir)
except FileNotFoundError:
fingerprints.setdefault(platform, []).append(platform)
representatives.setdefault(platform, platform)
inherits[platform] = False
continue
# Every field of every entry: the builder reads required, zipped_file,
# size and crc32 too, so two lists that differ only there are two
# packs. So is the way the frontend checks a file.
entries = [
json.dumps(fe, sort_keys=True, default=str)
for _sys_id, system in sorted(config.get("systems", {}).items())
for fe in system.get("files", [])
]
entries.append(
f"mode={config.get('verification_mode', '')}|rule={config.get('hash_rule', '')}"
)
fp = hashlib.sha1("|".join(sorted(entries)).encode()).hexdigest()
cores = config.get("cores")
emulators = [
cores if isinstance(cores, str) else sorted(map(str, cores or [])),
sorted(map(str, config.get("standalone_cores") or [])),
sorted(map(str, config.get("dual_mode_cores") or [])),
sorted(map(str, config.get("installable_cores") or [])),
# One archive cannot serve a filesystem that folds case and one
# that does not: Lakka keeps bios.col beside BIOS.col.
bool(config.get("case_insensitive_fs")),
# Where each core's files go: the same cores handed other
# folders make another pack.
sorted(
tag for tag in standalone_set(config) if tag.startswith(CORE_DIR_PREFIX)
),
]
fp = hashlib.sha1(f"{fp}|{emulators}".encode()).hexdigest()
if target_cores_cache:
tc = target_cores_cache.get(platform)
if tc is not None:
tc_str = "|".join(sorted(tc))
fp = hashlib.sha1(f"{fp}|{tc_str}".encode()).hexdigest()
fingerprints.setdefault(fp, []).append(platform)
# Prefer the root platform (no inherits) as representative
if fp not in representatives or (
not inherits[platform] and inherits.get(representatives[fp], False)
):
representatives[fp] = platform
result = []
for fp, group in fingerprints.items():
rep = representatives[fp]
ordered = [rep] + [p for p in group if p != rep]
result.append((ordered, rep))
return result
+9 -6
View File
@@ -20,7 +20,10 @@ import re
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
from common import declared_root, name_match_size_ok, resolve_local_file, sanitize_pack_path
from model.declarations import declared_root
from resolve.content import name_match_size_ok
from resolve.localfile import resolve_local_file
from core.paths import sanitize_pack_path
from core.paths import REPO_ROOT
# The kinds whose names say which file the launcher opens. A link of a named
@@ -509,7 +512,7 @@ def _profiles_or_repo(profiles: Mapping[str, dict] | None) -> Mapping[str, dict]
return profiles
if _DEFAULT_PROFILES is None:
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
_DEFAULT_PROFILES = load_emulator_profiles(
str(REPO_ROOT / "emulators")
@@ -895,7 +898,7 @@ def _roms_place(config: dict, path: str | None) -> Place | None:
platform installs above its BIOS folder (AmberELEC), else the roms tree."""
if path is None:
return None
from common import ROMS_ROOT, outer_layout
from resolve.layout import ROMS_ROOT, outer_layout
layout = outer_layout(config, ROMS_ROOT) or {}
if "install_prefix" in layout:
@@ -911,7 +914,7 @@ def folder_in_configs(directory: str, config: dict) -> str | None:
(``configs_root.path``): Batocera's /userdata/system/configs, where its
generators start shadPS4 from configs/shadps4.
"""
from common import CONFIGS_ROOT
from resolve.layout import CONFIGS_ROOT
return folder_in_root(directory, config, CONFIGS_ROOT)
@@ -923,7 +926,7 @@ def folder_in_roms(directory: str, config: dict) -> str | None:
(``roms_root.path``): ROCKNIX's /storage/roms, which holds its BIOS
folder and the folders its launchers run programs from.
"""
from common import ROMS_ROOT, outer_layout
from resolve.layout import ROMS_ROOT, outer_layout
spelled = directory.strip().rstrip("/")
for variable in ROMS_ROOT_VARIABLES:
@@ -937,7 +940,7 @@ def folder_in_roms(directory: str, config: dict) -> str | None:
def folder_in_root(directory: str, config: dict, root: str) -> str | None:
"""A directory relative to an outer root's path, None outside it."""
from common import outer_layout
from resolve.layout import outer_layout
roms = str((outer_layout(config, root) or {}).get("path") or "").rstrip("/")
directory = directory.strip().rstrip("/")
+324
View File
@@ -0,0 +1,324 @@
"""Where a platform's launch code puts a file: roots, tag prefixes, standalone layout paths."""
from __future__ import annotations
import json
import os
from collections.abc import Iterable, Mapping
from model.declarations import declared_root
def runs_standalone(
emu_name: str, profile: dict, standalone_cores: set[str]
) -> bool:
"""Whether a platform lays this emulator's files out for its standalone build.
A platform names the emulators it launches standalone in
``standalone_cores``, by profile key or by any name in ``cores:``. The
name alone is not enough: Recalbox and Batocera call their standalone
ScummVM ``scummvm``, which is also the key of the libretro core's
profile, and that profile documents no standalone build. Laid out
"standalone" it would lose every ``path:`` and drop its files at the
root, so a profile whose ``type`` has no standalone build keeps its
libretro layout whatever the platform calls it.
"""
if not standalone_cores:
return False
if "standalone" not in str(profile.get("type", "")):
return False
names = {emu_name, *(str(c) for c in profile.get("cores", []))}
# A name a build the platform compiles itself answers to means that
# build there: RetroBat's standalone amiberry is 8.3.0, and the 8.5.0
# profile, run there as the buildbot core, keeps its libretro layout.
owners: dict[str, set[str]] = {}
for tag in standalone_cores:
if tag.startswith(OWN_BUILD_PREFIX):
name, owner, source = json.loads(tag[len(OWN_BUILD_PREFIX):])
if source == profile.get("source"):
owners.setdefault(name, set()).add(owner)
if any(emu_name not in owners[n] for n in names & owners.keys()):
return False
return emu_name in standalone_cores or bool(standalone_cores & names)
# Marks, in a platform's standalone set, an emulator it also launches as a
# libretro core. No core name starts with it.
DUAL_MODE_PREFIX = "dual:"
# Marks, in the same set, a whole directory the platform's launcher hands a
# standalone emulator (launchers.handed_directories), as JSON.
HANDED_PREFIX = "handed:"
# Marks, in the same set, a libretro core and the system directory the
# platform hands it (``core_system_dirs``), as JSON.
CORE_DIR_PREFIX = "coredir:"
# Marks, in the same set, a file the platform's launcher executes
# (launchers.executed_files), as JSON.
EXECUTED_PREFIX = "exec:"
# Marks, in the same set, a standalone name a build the platform compiles
# itself (built_by) answers to, as JSON [name, profile, source].
OWN_BUILD_PREFIX = "ownbuild:"
# Marks, in the same set, a file name the platform declares under one of the
# systems a launcher record is written for, as JSON [system, name]: it says
# which launch reads a profile entry of that name.
SYSTEM_FILE_PREFIX = "sysfile:"
# The key, in that index, of a machine a launcher record offers.
MACHINE_KEY = "machine:"
# The platform is known: an entry read beside the content is placed in the
# roms folders a core is launched for, or named as read outside the BIOS
# folder. The tags below carry those folders.
CONTENT_SCOPE_TAG = "contentscope:"
# [core name, roms folder, (tree, path)]: a libretro core the platform
# launches for the games of that folder, which it reads beside.
CONTENT_FOLDER_PREFIX = "contentdir:"
# [emulator or core, (tree, path), system, machines, any machine,
# source_ref, build]: a standalone emulator, or a libretro core in the
# command line it is handed as content, given a roms folder as its ROM
# search path by a system's launch command.
ROM_SEARCH_PREFIX = "romsearch:"
# The frontend writes the BIOS it hands a core beside the content: the
# folder it gives the BIOS is the content's.
CONTENT_SYSTEM_TAG = "contentsystem:"
CONTENT_TAG_PREFIXES = (
CONTENT_SCOPE_TAG, CONTENT_FOLDER_PREFIX, ROM_SEARCH_PREFIX, CONTENT_SYSTEM_TAG,
)
def core_system_dirs(
emu_name: str, profile: dict, standalone_cores: Iterable[str]
) -> list[str] | None:
"""The system directories a platform hands this libretro core, or None.
None when the platform declares no per-core directory: the core reads
the one system directory every core shares. A platform that declares
them (MinUI hands each launch tag its own Bios/<TAG>/) gives a core it
lists no directory at all, so the list is then empty.
"""
pairs = [
json.loads(tag[len(CORE_DIR_PREFIX):])
for tag in standalone_cores if tag.startswith(CORE_DIR_PREFIX)
]
if not pairs:
return None
names = {emu_name, *(str(c) for c in profile.get("cores") or [])}
return sorted({directory for core, directory in pairs if core in names})
def system_dir_view(profile: dict, directory: str) -> dict:
"""The profile as a core reads it from one handed system directory.
Each file keeps its own path, relative to the system directory, and
carries the directory: destinations put it in front, resolution takes
it off again (resolve_local_file), so the collection is still searched
by the core's own path. A core's archive subfolder moves with it.
"""
view = {
**profile,
"files": [
{**f, "system_dir": directory} if isinstance(f, dict) else f
for f in profile.get("files") or []
],
}
if profile.get("archive_prefix"):
view["archive_prefix"] = f"{directory}/{profile['archive_prefix']}"
return view
def system_dir_path(entry: dict, path: str) -> str:
"""``path`` below the system directory the entry carries, if any."""
directory = entry.get("system_dir")
return f"{directory}/{path}" if directory else path
def _handed(standalone_cores: Iterable[str]) -> list:
"""The directories a standalone set carries, as launchers built them."""
from resolve.launchers import HandedDirectory
found = []
for tag in standalone_cores:
if not tag.startswith(HANDED_PREFIX):
continue
position, emulator, folder, directory, handles, ref, roms, systems, held = json.loads(
tag[len(HANDED_PREFIX):]
)
found.append(((position, tag), HandedDirectory(
emulator, folder, directory, frozenset(handles), ref,
tuple(roms) if roms else None, frozenset(systems), held,
)))
return [h for _key, h in sorted(found, key=lambda pair: pair[0])]
def system_file_index(standalone_cores: Iterable[str]) -> dict[str, set[str]]:
"""File name, lower case -> the platform systems declaring it (SYSTEM_FILE_PREFIX)."""
index: dict[str, set[str]] = {}
for tag in standalone_cores:
if tag.startswith(SYSTEM_FILE_PREFIX):
slug, name = json.loads(tag[len(SYSTEM_FILE_PREFIX):])
index.setdefault(name, set()).add(slug)
return index
def entry_launch_systems(entry: dict, index: Mapping[str, set[str]]) -> frozenset[str]:
"""The platform systems, by our ids, that launch the emulator for an entry.
The systems the entry names, and those under which the platform declares
a file of one of its names (``index``, system_file_index): Recalbox lists
XRoar's coco3.rom under trs80coco, which our coco is.
"""
systems = {str(s) for s in entry.get("systems") or []}
if entry.get("system"):
systems.add(str(entry["system"]))
for name in [entry.get("name"), *(entry.get("aliases") or [])]:
if name:
systems |= index.get(str(name).lower(), set())
return frozenset(systems)
def _executed(standalone_cores: Iterable[str]) -> list:
"""The files a standalone set's launchers execute, as launchers read them."""
from resolve.launchers import ExecutedFile
found = []
for tag in standalone_cores:
if tag.startswith(EXECUTED_PREFIX):
emulator, name, place, ref = json.loads(tag[len(EXECUTED_PREFIX):])
found.append(ExecutedFile(emulator, name, tuple(place) if place else None, ref))
return found
# Why a standalone entry has no destination on a platform that relocates its
# layout: the manifest's omission reason, named as the installer words it.
OUTSIDE_BIOS_FOLDER = "outside_bios_folder"
# The entry root of a file read below the platform's roms directory, and of
# one read in an emulator's folder outside the BIOS tree that the registry
# describes. Each is located by the registry entry <root>_directory.
ROMS_ROOT = "roms"
EMULATORS_ROOT = "emulators"
CONFIGS_ROOT = "configs"
OUTER_ROOTS = (ROMS_ROOT, EMULATORS_ROOT, CONFIGS_ROOT)
def outer_layout(config: dict, root: str) -> dict | None:
"""Where a platform keeps the folder an outer root names, or None.
roms: the roms root its rom folders file records (``path``, the OS's
spelling, and ``from_bios``, relative to the BIOS folder), with the
BIOS folder's own name, base_destination, that a run's folder must
carry before ``from_bios`` is followed from it. emulators: the
registry's ``emulators_directory``, the folders a launcher searches
for an emulator by key, which no rom folders file describes.
"""
if root == ROMS_ROOT:
found = config.get("_roms_root") or {}
base = str(config.get("base_destination") or "")
path, relation = found.get("path"), found.get("from_bios")
if not (path and relation) or "<" in str(path):
return None
if base:
return {"path": str(path), "from_bios": str(relation), "bios_folder": base}
# A list whose dests start above the BIOS folder (AmberELEC's
# bios/...) installs into the folder holding it: a roms root there
# or below is part of the install tree, written as a plain dest.
declared = declared_root(config)
if not declared:
return None
inside = os.path.normpath(f"{declared}/{relation}")
if inside == ".." or inside.startswith("../"):
return None
return {"path": str(path), "install_prefix": "" if inside == "." else inside}
if root == EMULATORS_ROOT:
return config.get("emulators_directory") or None
if root == CONFIGS_ROOT:
# The frontend's configs folder, as its path code builds it
# (configs_root, Batocera's batoceraPaths CONFIGS).
found = config.get("configs_root") or {}
base = str(config.get("base_destination") or "")
if not (found.get("path") and found.get("from_bios") and base):
return None
return {"path": str(found["path"]), "from_bios": str(found["from_bios"]),
"bios_folder": base}
return None
def standalone_layout_path(entry: dict, profile: dict) -> str | None:
"""The path of an entry relative to the directories its standalone build declares.
``standalone_path`` when the entry has one. A profile with no libretro
build has one layout, so its ``path`` is that layout: UAE4All2 reads
kickstarts/kick13.rom below its working directory. So does an entry only
the standalone build reads (``mode: standalone``), whose destination is
its ``path``: Dolphin's Load/Firmware/rtl_bt/ under its User directory.
"""
own = entry.get("standalone_path")
if own:
return own
if "libretro" in str(profile.get("type", "")) and entry.get("mode") != "standalone":
return None
return entry.get("path") or None
def standalone_destination(
entry: dict, profile: dict, bindings: dict[str, tuple[str, str]]
) -> tuple[str, str] | None:
"""Where a platform puts a standalone entry: (tree, path).
``bindings`` are the places the platform's launchers give the layout
(launchers.standalone_bindings): RetroPie and ROCKNIX give Flycast bios/dc,
EmuDeck bios/flycast/bios, RetroPie gives UAE4All2's kickstarts/ bios/amiga,
ROCKNIX runs PICO-8 from roms/pico-8. The tree is launchers.BIOS_TREE or
launchers.ROMS_TREE. None when no binding covers the entry.
"""
layout = standalone_layout_path(entry, profile)
if layout is None or not bindings:
return None
from resolve.launchers import bound_path
return bound_path(layout, bindings)
def standalone_bindings_for(
emu_name: str, profile: dict, standalone_cores: Iterable[str],
systems: Iterable[str] = (),
) -> dict[str, tuple[str, str]]:
"""The places a platform gives this emulator's standalone layout, by subfolder.
``systems`` are those the entry is launched for (entry_launch_systems).
"""
from resolve.launchers import directory_handles, pool_folders, standalone_bindings
declared = directory_handles(profile)
pools = pool_folders(profile)
if not declared and not pools:
return {}
names = {emu_name, *(str(c) for c in profile.get("cores") or [])}
layout = [
path for f in profile.get("files") or []
if isinstance(f, dict) and (path := standalone_layout_path(f, profile))
]
return standalone_bindings(
names, declared, _handed(standalone_cores), _executed(standalone_cores), layout,
pools, systems,
)
def _placed_entry(entry: dict, profile: dict, placed: tuple[str, str]) -> dict:
"""A standalone entry moved to the (tree, path) a platform reads it from."""
tree, path = placed
moved = {**entry, "standalone_path": path,
"layout_path": standalone_layout_path(entry, profile)}
if entry.get("load_from"):
# The build's own root no longer applies: RetroDECK hands
# Cemu's MLC, read from its data directory, to bios/cemu.
load_from = entry["load_from"]
moved["load_from"] = {
**(load_from if isinstance(load_from, dict) else {"libretro": load_from}),
"standalone": "system_dir",
}
if tree == "install":
# Below the roms root inside the install tree (AmberELEC's
# /storage/roms): a plain dest the platform prefix skips.
return {**moved, "unprefixed": True}
# A file the launcher runs from the roms directory (ROCKNIX's
# roms/pico-8) or an emulator folder (RetroBat's emulators/pico8)
# is relative to it, and says so.
return {**moved, "root": tree} if tree else moved
File diff suppressed because it is too large. Load diff
+127
View File
@@ -0,0 +1,127 @@
"""Which emulator, engine or manufacturer a path of the collection belongs to."""
from __future__ import annotations
import re
# bios/Other/<emulator> and bios/Arcade/<emulator or board> file a copy by
# who loads it, not by machine.
BUCKET_FOLDERS = frozenset({"Other", "Arcade"})
def names_manufacturer(sys_id: str, manufacturer: str) -> bool:
"""Whether a system id names a maker folder: nec-pc-88 names NEC."""
slug = manufacturer.lower().replace(" ", "-")
return sys_id == slug or sys_id.startswith(f"{slug}-")
def _maker_folder(path: str, bios_dir: str) -> str | None:
"""The bios/<maker>/ folder a collection path is filed under."""
prefix = f"{bios_dir.rstrip('/')}/"
if not path.startswith(prefix):
return None
parts = path[len(prefix):].split("/")
return parts[0] if len(parts) >= 2 else None
# One slot, keyed like the casefold view: the files dict, its size, the folders.
_maker_folders_cache: list[tuple[dict, int, frozenset[str]]] = []
def _maker_folders(db: dict) -> frozenset[str]:
"""Every maker folder the collection files a copy under."""
files_db = db.get("files", {})
if _maker_folders_cache:
source, size, folders = _maker_folders_cache[0]
if source is files_db and size == len(files_db):
return folders
bios_dir = str(db.get("bios_dir") or "bios")
folders = frozenset(
folder
for entry in files_db.values()
if (folder := _maker_folder(str(entry.get("path", "")), bios_dir))
and folder not in BUCKET_FOLDERS
)
_maker_folders_cache[:] = [(files_db, len(files_db), folders)]
return folders
def system_makers(file_entry: dict, db: dict) -> frozenset[str]:
"""The maker folders a platform entry's system names.
Only a platform's own entry is asked: one that names an owning emulator
is placed by that emulator's tree. Empty when the system names no maker
(pc88, arcade), so nothing is narrowed there.
"""
sys_id = str(file_entry.get("platform_system") or "")
if not sys_id or _owner_tokens(file_entry):
return frozenset()
return frozenset(
folder for folder in _maker_folders(db) if names_manufacturer(sys_id, folder)
)
def other_maker(path: str, makers: frozenset[str], db: dict) -> bool:
"""Whether a path is filed under a maker the entry's system does not name."""
if not makers:
return False
folder = _maker_folder(path, str(db.get("bios_dir") or "bios"))
return folder is not None and folder not in BUCKET_FOLDERS and folder not in makers
def _affinity_tokens(text: str) -> set[str]:
return {
token
for token in (re.sub(r"[^0-9a-z]", "", part.casefold()) for part in text.split("/"))
if token
}
def _owner_tokens(file_entry: dict) -> set[str]:
"""Tokens naming the profile that asks for the file.
A profile named after another with a suffix (cxbx-reloaded-2023,
mame4droid-2024) is a release of that emulator, and the tree named by
the shorter name is its own: cxbx-reloaded-2023 was served xemu's
encrypted EEPROM because bios/Other/cxbx-reloaded/ read as foreign.
Only whole leading words count, so dolphin-mmjr2 is not dolphin-mmjr.
"""
tokens: set[str] = set()
for owner in (file_entry.get("source_profile"), file_entry.get("source_emulator")):
if owner:
tokens |= _affinity_tokens(str(owner).replace(" ", ""))
profile = str(file_entry.get("source_profile") or "").casefold()
words = [word for word in re.split(r"[^0-9a-z]+", profile) if word]
tokens |= {"".join(words[:end]) for end in range(1, len(words))}
return tokens
def _foreign_tree(path: str, owners: set[str]) -> bool:
"""Whether a path lives in the tree of an emulator that is not the asker.
bios/Other/<emulator>/ holds what one emulator ships. A same-named file
found there answers that emulator's entry, not another's: EmuCoreX's
unlock.wav was served from NetherSX2's tree, and upstream PCSX2's
GameIndex.yaml from EmuCoreX's, while the system directory held a copy.
"""
parts = path.split("/")
if not owners or len(parts) < 4 or parts[0] != "bios" or parts[1] != "Other":
return False
return not (owners & _affinity_tokens(parts[2]))
def _engine_tree(path: str, owners: set[str]) -> bool:
"""Whether a path lives in another game's folder under bios/Game Engines/."""
parts = path.split("/")
if len(parts) < 4 or parts[0] != "bios" or parts[1] != "Game Engines":
return False
return not (owners & _affinity_tokens(parts[2]))
def _own_tree(path: str, owners: set[str]) -> bool:
"""Whether a path lives in the bios/Other/<emulator>/ tree of the asker."""
parts = path.split("/")
if not owners or len(parts) < 4 or parts[0] != "bios" or parts[1] != "Other":
return False
return bool(owners & _affinity_tokens(parts[2]))
+3 -2
View File
@@ -17,7 +17,7 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from common import _norm_system_id
from model.systems import _norm_system_id
from core.paths import REPO_ROOT
HASH_FIELDS = ("sha1", "md5", "sha256", "crc32")
@@ -771,7 +771,8 @@ def _attach_runners(systems: dict[str, NativeSystem], scraped: dict | None) -> N
"""
if not scraped:
return
from common import load_emulator_profiles, runs_standalone
from model.profiles import load_emulator_profiles
from resolve.layout import runs_standalone
declared = scraped.get("cores")
libretro = {str(c) for c in declared} if isinstance(declared, list) else set()
+1 -1
View File
@@ -53,7 +53,7 @@ def platform_slot_claims(
config: dict, profiles: dict, target_cores: set[str] | None = None
) -> dict[str, dict[str, dict]]:
"""What each emulator a platform runs declares at each key, unmerged."""
from common import resolve_platform_cores
from resolve.cores import resolve_platform_cores
cores = resolve_platform_cores(config, profiles, target_cores=target_cores)
return slot_claims({n: profiles[n] for n in cores if n in profiles})
+342
View File
@@ -0,0 +1,342 @@
"""The standalone builds a platform launches and the layouts their files take."""
from __future__ import annotations
import dataclasses
import json
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from model.profiles import load_emulator_profiles
from model.systems import _norm_system_id
from resolve.contentlayout import content_folder_tags, content_layout
from resolve.layout import (
CONTENT_TAG_PREFIXES,
CORE_DIR_PREFIX,
DUAL_MODE_PREFIX,
EXECUTED_PREFIX,
HANDED_PREFIX,
MACHINE_KEY,
OUTSIDE_BIOS_FOLDER,
OWN_BUILD_PREFIX,
SYSTEM_FILE_PREFIX,
_handed,
_placed_entry,
core_system_dirs,
entry_launch_systems,
runs_standalone,
standalone_bindings_for,
standalone_destination,
standalone_layout_path,
system_dir_view,
system_file_index,
)
from core.paths import REPO_ROOT
def own_build_tags(config: dict, standalone: set[str]) -> set[str]:
"""The standalone names the platform's own builds answer to, tagged.
Read from the profiles of this repository, the ones every pack, manifest
and report is built from.
"""
platform = str(config.get("_key") or "")
if not platform or not standalone:
return set()
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
return {
OWN_BUILD_PREFIX + json.dumps([n, key, p.get("source")])
for key, p in profiles.items()
if platform in (p.get("built_by") or []) and "standalone" in str(p.get("type", ""))
for n in {key, *(str(c) for c in p.get("cores") or [])} & standalone
}
def twin_build_names(config: dict) -> set[str]:
"""The libretro core names of emulators a platform also runs standalone
under another name.
RetroBat's es_systems.cfg offers MAME as the libretro core mame and as
the standalone mame64, two names of one profile: the platform runs it
both ways, and each build reads its own layout.
"""
standalone = {str(c) for c in config.get("standalone_cores") or []}
libretro = {str(c) for c in config.get("cores") or []} - standalone if isinstance(
config.get("cores"), list
) else set()
if not standalone or not libretro:
return set()
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
found: set[str] = set()
for key, profile in profiles.items():
kind = str(profile.get("type", ""))
if "libretro" not in kind or "standalone" not in kind:
continue
names = {key, *(str(c) for c in profile.get("cores") or [])}
if names & standalone:
found |= names & libretro
return found
def standalone_set(config: dict) -> set[str]:
"""The emulators a platform launches standalone, with its dual-mode ones.
``dual_mode_cores`` names those it offers both ways (Batocera lists
libretro:dolphin and standalone dolphin for GameCube). They travel in the
same set, tagged, so every reader of standalone_cores sees them.
"""
names = {str(c) for c in config.get("standalone_cores") or []}
names |= {DUAL_MODE_PREFIX + str(c) for c in config.get("dual_mode_cores") or []}
# A buildbot core the platform's RetroArch installs under the name of an
# emulator it runs standalone is that emulator's libretro build: run
# both ways, as Batocera runs amiberry standalone and can fetch
# amiberry_libretro.
names |= {
DUAL_MODE_PREFIX + str(c)
for c in set(map(str, config.get("installable_cores") or []))
& set(map(str, config.get("standalone_cores") or []))
}
names |= own_build_tags(config, names)
names |= {DUAL_MODE_PREFIX + n for n in twin_build_names(config)}
# The system directory each core is handed travels the same way, so
# platform_layouts places a core's files below it for every reader.
names |= {
CORE_DIR_PREFIX + json.dumps([str(core), directory])
for directory, entry in (config.get("core_system_dirs") or {}).items()
for core in entry.get("cores") or []
}
if names - {n for n in names if n.startswith(CORE_DIR_PREFIX)}:
from resolve.launchers import executed_files, handed_directories
handed = handed_directories(config)
# The record's position travels too: a search list is read in order.
names |= {
HANDED_PREFIX + json.dumps(
[position, h.emulator, h.folder, h.directory, sorted(h.handles), h.source_ref,
h.roms_place, sorted(h.systems), h.holds_declared]
)
for position, h in enumerate(handed)
}
named = {system for h in handed for system in h.systems}
names |= {
SYSTEM_FILE_PREFIX + json.dumps([slug, str(f["name"]).lower()])
for slug, system in (config.get("systems") or {}).items()
if slug in named
for f in system.get("files") or []
if f.get("name")
}
# The machines a record offers under its systems, by normalized id.
from resolve.launchers import native_systems
natives = native_systems(config)
names |= {
SYSTEM_FILE_PREFIX + json.dumps(
[natives.get(str(native), str(native)), MACHINE_KEY + _norm_system_id(str(m))]
)
for record in config.get("launchers") or []
for native in record.get("systems") or []
for m in record.get("machines") or []
}
names |= {
EXECUTED_PREFIX + json.dumps([run.emulator, run.name, run.place, run.source_ref])
for run in executed_files(config)
}
return names | content_folder_tags(config)
def merged_standalone_set(configs: Iterable[dict]) -> set[str]:
"""The standalone set of several platforms read as one tree.
A per-core directory marker says which cores one platform hands a folder
and that it hands the others none. Carried into the union, MinUI's 86
markers left every core they do not list without a layout: the global
gap report lost 238 profiles and 1201 files without a word.
"""
return {
tag
for config in configs
for tag in standalone_set(config)
if not tag.startswith((CORE_DIR_PREFIX, *CONTENT_TAG_PREFIXES))
}
def platform_layouts(
emu_name: str, profile: dict, standalone_cores: set[str]
) -> list[tuple[dict, bool]]:
"""The layouts a platform gives an emulator: (profile, standalone?) each,
with the files read in a roms folder placed there (content_layout)."""
return [
(content_layout(emu_name, view, standalone, standalone_cores), standalone)
for view, standalone in _build_layouts(emu_name, profile, standalone_cores)
]
@dataclass
class _StandaloneLaunches:
"""Where a platform's launches of a standalone emulator read its files."""
emu_name: str
profile: dict
standalone_cores: set[str]
per_system: bool
index: Mapping[str, set[str]]
# A profile system the platform launches under a system of its own, as
# its list says for one entry, is launched there for every entry.
family: dict[str, set[str]]
# The systems the launcher records name.
named_systems: frozenset[str]
# The layout folders a search setting stands for (standalone_pools).
pool_folders: set[str]
# Bindings can depend on the system an entry is launched for, so each
# set of launch systems gets its own.
by_systems: dict[frozenset[str], dict[str, tuple[str, str]]] = dataclasses.field(default_factory=dict)
@classmethod
def of(cls, emu_name: str, profile: dict, standalone_cores: set[str]) -> _StandaloneLaunches:
names = {emu_name, *(str(c) for c in profile.get("cores") or [])}
per_system = bool(
profile.get("standalone_directories") or profile.get("standalone_pools")
) and any(h.systems and h.emulator in names for h in _handed(standalone_cores))
index = system_file_index(standalone_cores) if per_system else {}
# A profile system the platform launches under a system of its own, as
# its list says for one entry, is launched there for every entry:
# Recalbox lists mc10.rom under trs80coco, so alice.rom is read there.
family: dict[str, set[str]] = {}
for f in (profile.get("files") or []) if per_system else []:
if isinstance(f, dict):
own = entry_launch_systems(f, {})
for system in own:
family.setdefault(system, set()).update(entry_launch_systems(f, index) - own)
# The systems the launcher records name: a launch for one of them reads
# the folder its record gives, every other launch the folder the records
# naming none give.
named_systems = frozenset().union(*(
h.systems for h in _handed(standalone_cores) if h.emulator in names
)) if per_system else frozenset()
# The layout folders a search setting stands for (standalone_pools):
# bound, the launcher passes the setting and the default is not read.
from resolve.launchers import pool_folders as _pool_folders
pool_folders = {v.strip("/") for v in _pool_folders(profile).values()} - {""}
return cls(
emu_name, profile, standalone_cores, per_system, index, family,
named_systems, pool_folders,
)
def launch_systems(self, entry: dict) -> frozenset[str]:
systems: frozenset[str] = frozenset()
if self.per_system:
own = entry_launch_systems(entry, {})
systems = entry_launch_systems(entry, self.index)
if systems == own:
systems = systems.union(*(self.family.get(s, set()) for s in own))
if systems == own:
# The platform's list names none of the entry's names: its
# own system selects the launch that offers it as a machine
# (RetroBat runs XRoar's coco3 under coco).
systems = systems.union(*(
self.index.get(MACHINE_KEY + _norm_system_id(s), set()) for s in own
))
return systems
def bindings_for(self, systems: frozenset[str]) -> dict[str, tuple[str, str]]:
if systems not in self.by_systems:
self.by_systems[systems] = standalone_bindings_for(
self.emu_name, self.profile, self.standalone_cores, systems
)
return self.by_systems[systems]
def bindings_of(self, entry: dict) -> dict[str, tuple[str, str]]:
return self.bindings_for(self.launch_systems(entry))
def passed_setting(self, entry: dict) -> bool:
layout = str(standalone_layout_path(entry, self.profile) or "")
bindings = self.bindings_of(entry)
return any(
folder in bindings and (layout == folder or layout.startswith(folder + "/"))
for folder in self.pool_folders
)
def destinations(self, entry: dict) -> list[tuple[str, str] | None]:
"""Each place the entry's launches read it from, in launch order.
An entry of a system a record names is read where that record puts
it. One also launched for systems no record names is read, for those
launches, where the records naming none put it: EmuELEC starts
AdvanceMAME with dir_rom roms/arcade for arcade and roms/mame for
mame and cps1-3 (advmame.sh:26-30), and an arcade set is read in both.
"""
systems = self.launch_systems(entry)
found = [standalone_destination(entry, self.profile, self.bindings_for(systems))]
# A system the platform's list or machines put the entry under
# stands for the entry's own ids: XRoar's coco3 is launched as coco.
own = entry_launch_systems(entry, {})
launched = (systems - own) | (own & self.named_systems) if systems != own else systems
if launched & self.named_systems and launched - self.named_systems:
generic = standalone_destination(entry, self.profile, self.bindings_for(frozenset()))
if generic not in found:
found.append(generic)
return found
def placed_files(self) -> list:
"""The profile's files, each layout entry at the folders its launches read."""
files = []
for f in self.profile.get("files") or []:
if not isinstance(f, dict) or standalone_layout_path(f, self.profile) is None:
files.append(f)
continue
places = [p for p in self.destinations(f) if p is not None and p[0] != "outside"]
if not places:
files.append({**f, "unplaced": OUTSIDE_BIOS_FOLDER})
continue
moved = f
if f.get("bundled") and self.passed_setting(f):
# The copy installed with the emulator sits where the setting
# pointed before the launcher moved it: RetroBat passes MAME
# -hash bios/mame/hash (Mame64.Generator.cs:172, 177-178), and
# the hash/ beside mame.exe is no longer read.
moved = {k: v for k, v in f.items() if k != "bundled"}
files.extend(_placed_entry(moved, self.profile, placed) for placed in places)
return files
def _build_layouts(
emu_name: str, profile: dict, standalone_cores: set[str]
) -> list[tuple[dict, bool]]:
"""The layouts a platform gives an emulator: (profile, standalone?) each.
One, libretro or standalone, for most. Both for an emulator the platform
launches either way: laid out standalone only, Batocera's libretro
Dolphin found dolphin-emu/Sys/GC/ empty. Each layout keeps its own rules
(what the build reads from the system directory, where it reads it).
"""
if not runs_standalone(emu_name, profile, standalone_cores):
directories = core_system_dirs(emu_name, profile, standalone_cores)
if directories is None:
return [(profile, False)]
return [(system_dir_view(profile, d), False) for d in directories]
standalone = profile
launches = _StandaloneLaunches.of(emu_name, profile, standalone_cores)
layout_entries = [
f for f in profile.get("files") or []
if isinstance(f, dict) and standalone_layout_path(f, profile) is not None
]
if any(launches.bindings_of(f) for f in layout_entries):
# The standalone view carries the platform's destination, so every
# reader of standalone_path (builder, manifest, verify, slots) places
# the file in the folder the platform hands the emulator.
# An entry of the layout no binding covers is read in a folder the
# platform keeps outside the BIOS tree: UAE4All2's kick.rom in
# RetroPie's $md_inst. It is marked, never left at the BIOS root
# where the emulator does not read it.
standalone = {**profile, "files": launches.placed_files()}
dual = {c.removeprefix(DUAL_MODE_PREFIX) for c in standalone_cores
if c.startswith(DUAL_MODE_PREFIX)}
if "libretro" in str(profile.get("type", "")) and dual & {
emu_name, *(str(c) for c in profile.get("cores", []))
}:
return [(profile, False), (standalone, True)]
return [(standalone, True)]
+5 -8
View File
@@ -11,14 +11,11 @@ import os
import sys
from dataclasses import dataclass
from common import (
OUTER_ROOTS,
_norm_system_id,
load_data_dir_registry,
platform_layouts,
resolve_platform_cores,
standalone_set as platform_standalone_set,
)
from resolve.layout import OUTER_ROOTS
from model.systems import _norm_system_id
from model.registry import load_data_dir_registry
from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set
from resolve.cores import resolve_platform_cores
from model.alternatives import groups_of
from core.hashing import compute_hashes
from resolve.validation import (
+5 -6
View File
@@ -13,18 +13,17 @@ import zipfile
from collections.abc import Callable, Collection, Iterator, Mapping, Sequence
from typing import TYPE_CHECKING, TypedDict
from common import (
from resolve.content import (
adler32_of,
archive_members,
CONTENT_CHECKS,
compute_hashes,
content_fits,
declared_content_checks,
entry_system_ids,
name_match_size_ok,
sanitize_pack_path,
shape_fits,
)
from resolve.archives import archive_members
from model.profiles import CONTENT_CHECKS, entry_system_ids
from core.hashing import compute_hashes
from core.paths import sanitize_pack_path
from core.hashing import md5_composite, parse_hash_list, parse_md5_list
from resolve.nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file
from core.ziptools import check_inside_zip