mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-24 10:37:54 -06:00
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:
1 parent
c784aef883
commit
83cfa6fd0f
281 files changed
+7036
-6794
No files matched your search
@@ -0,0 +1,140 @@
|
||||
"""Command-line arguments and listings read from the registry and the profiles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None
|
||||
|
||||
from model.platforms import load_platform_config
|
||||
from model.profiles import load_emulator_profiles
|
||||
from model.registry import list_registered_platforms, list_release_pack_platforms
|
||||
from model.systems import platform_system_names, system_index
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
def work_from_repo_root(
|
||||
args: argparse.Namespace, parser: argparse.ArgumentParser, path_flags: list[str]
|
||||
) -> None:
|
||||
"""Run from the repository root, whichever directory the command started in.
|
||||
|
||||
database.json records every file from the root and the data registry
|
||||
names its caches the same way, so a run from scripts/ ended on a
|
||||
FileNotFoundError traceback. A path the caller typed is read from where
|
||||
they typed it, a default from the root.
|
||||
"""
|
||||
root = REPO_ROOT
|
||||
if Path.cwd().resolve() == root:
|
||||
return
|
||||
for flag in path_flags:
|
||||
value = getattr(args, flag, None)
|
||||
if value and value != parser.get_default(flag):
|
||||
# A Path stays a Path for the code that joins onto it.
|
||||
setattr(args, flag, type(value)(os.path.abspath(value)))
|
||||
os.chdir(root)
|
||||
if getattr(args, "platform", None):
|
||||
# Read before the move, the registry was not there to map
|
||||
# "RetroArch" to its slug.
|
||||
args.platform = platform_arg(args.platform)
|
||||
|
||||
|
||||
def platform_arg(value: str) -> str:
|
||||
"""--platform as typed, mapped to the registry's slug when it names one.
|
||||
|
||||
The site and the pack names say RetroArch and MiSTer FPGA, but verify and
|
||||
generate_pack refused both while install.py took them. Letters and
|
||||
digits decide, as for pack names. Anything else reaches require_platform
|
||||
unchanged and gets its suggestion.
|
||||
"""
|
||||
key = re.sub(r"[^a-z0-9]", "", value.lower())
|
||||
if yaml is None or not os.path.isdir("platforms"):
|
||||
return value
|
||||
known = list_registered_platforms("platforms")
|
||||
for name in known:
|
||||
if re.sub(r"[^a-z0-9]", "", name.lower()) == key:
|
||||
return name
|
||||
return value
|
||||
|
||||
|
||||
def require_platform(name: str, platforms_dir: str = "platforms") -> None:
|
||||
"""Exit with a usable message when no platform answers to a name.
|
||||
|
||||
A typo used to end in a traceback (verify, cross_reference) or in "no
|
||||
pack for batocra" after the whole build ran (generate_pack).
|
||||
"""
|
||||
if "," in name:
|
||||
# generate_pack split the list to validate it, then used the whole
|
||||
# string as one name and ended in a traceback.
|
||||
raise SystemExit(
|
||||
f"ERROR: --platform takes one platform, not '{name}'. "
|
||||
"Run once per platform, or use --all."
|
||||
)
|
||||
if os.path.exists(os.path.join(platforms_dir, f"{name}.yml")):
|
||||
return
|
||||
import difflib
|
||||
|
||||
known = list_registered_platforms(platforms_dir)
|
||||
close = difflib.get_close_matches(name, known, n=1)
|
||||
hint = f" Close match: '{close[0]}'." if close else ""
|
||||
raise SystemExit(
|
||||
f"ERROR: unknown platform '{name}'.{hint}\nKnown platforms: {', '.join(known)}"
|
||||
)
|
||||
|
||||
|
||||
def list_emulator_profiles(emulators_dir: str, skip_aliases: bool = True) -> None:
|
||||
"""Print available emulator profiles."""
|
||||
profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
|
||||
for name in sorted(profiles):
|
||||
p = profiles[name]
|
||||
if p.get("type") == "alias" or p.get("role") == "test":
|
||||
continue
|
||||
display = p.get("emulator", name)
|
||||
ptype = p.get("type", "libretro")
|
||||
systems = ", ".join(p.get("systems", [])[:3])
|
||||
more = "..." if len(p.get("systems", [])) > 3 else ""
|
||||
# The type is padded to its longest value, so the systems start in
|
||||
# one column whatever the type reads.
|
||||
kind = f"[{ptype}]"
|
||||
print(f" {name:30s} {display:40s} {kind:24s}{systems}{more}".rstrip())
|
||||
|
||||
|
||||
def list_system_ids(emulators_dir: str) -> None:
|
||||
"""Print available system IDs with emulator count."""
|
||||
index = system_index(load_emulator_profiles(emulators_dir))
|
||||
for _key, (spelling, emulators) in sorted(index.items(), key=lambda kv: kv[1][0]):
|
||||
count = len(emulators)
|
||||
print(f" {spelling:35s} ({count} emulator{'s' if count > 1 else ''})")
|
||||
|
||||
|
||||
def print_platform_listing(platforms_dir: str) -> None:
|
||||
"""Every registered platform, one per line, marked when the installer
|
||||
alone serves it.
|
||||
|
||||
Every platform takes --platform. --all covers every one, and the pack
|
||||
builder's --all the release packs. Printed by --list-platforms in
|
||||
verify.py and generate_pack.py, the name install.py gives it.
|
||||
"""
|
||||
released = set(list_release_pack_platforms(platforms_dir))
|
||||
for name in list_registered_platforms(platforms_dir):
|
||||
print(name if name in released else f"{name} (installer only)")
|
||||
|
||||
|
||||
def list_platform_system_ids(platform_name: str, platforms_dir: str) -> None:
|
||||
"""Print system IDs from a platform's YAML config, with the platform's
|
||||
own names for them, which --system also accepts."""
|
||||
config = load_platform_config(platform_name, platforms_dir)
|
||||
systems = config.get("systems", {})
|
||||
names = platform_system_names(config, list(systems))
|
||||
for sys_id in sorted(systems):
|
||||
file_count = len(systems[sys_id].get("files", []))
|
||||
mfr = systems[sys_id].get("manufacturer", "")
|
||||
mfr_display = f" [{mfr.split('|')[0]}]" if mfr else ""
|
||||
count = f"({file_count} file{'s' if file_count != 1 else ''})"
|
||||
also = f" also: {', '.join(names[sys_id])}" if sys_id in names else ""
|
||||
print(f" {sys_id:35s} {count:12s}{mfr_display}{also}".rstrip())
|
||||
@@ -0,0 +1,74 @@
|
||||
"""What the collection holds by tree area: systems, arcade sets, game data."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
|
||||
|
||||
# Trees that hold game and engine data rather than the system files of a
|
||||
# machine: the engine trees, and the publishers whose games an engine runs.
|
||||
GAME_DATA_TOPS = (
|
||||
"RPG Maker",
|
||||
"ScummVM",
|
||||
"Game Engines",
|
||||
"sdlpal",
|
||||
"Dinothawr",
|
||||
"3D Realms",
|
||||
"Apogee",
|
||||
"Blizzard",
|
||||
"Bungie",
|
||||
"Crack dot Com",
|
||||
"Electronic Arts",
|
||||
"Epic MegaGames",
|
||||
"Id Software",
|
||||
"Interplay",
|
||||
"Monolith",
|
||||
"Softdisk",
|
||||
"Toys for Bob",
|
||||
"Valve",
|
||||
)
|
||||
|
||||
|
||||
def composition_tier(path: str) -> str:
|
||||
"""Which composition bucket a repository path belongs to."""
|
||||
parts = path.split("/")
|
||||
top = parts[1] if len(parts) > 1 else ""
|
||||
if top == "Arcade":
|
||||
return "arcade"
|
||||
if top in GAME_DATA_TOPS:
|
||||
return "game_data"
|
||||
return "systems"
|
||||
|
||||
|
||||
def compute_composition(db: dict) -> dict:
|
||||
"""File and byte counts by tree area.
|
||||
|
||||
Three buckets, each re-derivable from paths alone: arcade ROM sets
|
||||
(Arcade/), game and engine data (the trees of GAME_DATA_TOPS), and
|
||||
console or computer system files (everything else).
|
||||
"""
|
||||
buckets = {
|
||||
"systems": {"files": 0, "size_bytes": 0},
|
||||
"arcade": {"files": 0, "size_bytes": 0},
|
||||
"game_data": {"files": 0, "size_bytes": 0},
|
||||
}
|
||||
for entry in db.get("files", {}).values():
|
||||
bucket = buckets[composition_tier(entry.get("path", ""))]
|
||||
bucket["files"] += 1
|
||||
bucket["size_bytes"] += entry.get("size", 0)
|
||||
return buckets
|
||||
|
||||
|
||||
def count_catalog_matched(db: dict) -> int:
|
||||
"""System files byte-identical to a dump-preservation catalog entry.
|
||||
|
||||
Scoped to the systems bucket, the denominator every surface pairs it
|
||||
with: No-Intro, Redump and TOSEC index console and computer dumps, so
|
||||
arcade ROM sets and engine data sit on neither side of the ratio.
|
||||
"""
|
||||
return sum(
|
||||
1
|
||||
for entry in db.get("files", {}).values()
|
||||
if entry.get("provenance")
|
||||
and composition_tier(entry.get("path", "")) == "systems"
|
||||
)
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Loading database.json and the MAME clone map written beside the collection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from core.cli import InputMissing
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
class DatabaseUnreadable(InputMissing):
|
||||
"""The database a command was pointed at does not exist or is not JSON."""
|
||||
|
||||
|
||||
def load_database(db_path: str) -> dict:
|
||||
"""Load database.json and return parsed dict.
|
||||
|
||||
A missing or damaged file raises DatabaseUnreadable, which run_cli turns
|
||||
into one line saying how to build it: `--db nosuch.json` ended at the
|
||||
bottom of a stack trace.
|
||||
"""
|
||||
try:
|
||||
with open(db_path) as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
# A mistyped --db beside the real database was told to rescan the
|
||||
# whole collection into a second file under the typo.
|
||||
import difflib
|
||||
|
||||
typed = Path(db_path)
|
||||
close = difflib.get_close_matches(
|
||||
typed.name, [p.name for p in typed.parent.glob("*.json")], n=1, cutoff=0.8
|
||||
)
|
||||
if close:
|
||||
raise DatabaseUnreadable(
|
||||
f"{db_path} not found. Close match: {typed.with_name(close[0])}"
|
||||
) from None
|
||||
raise DatabaseUnreadable(
|
||||
f"{db_path} not found. Build it with: python scripts/generate_db.py "
|
||||
f"--force --bios-dir bios --output {db_path}"
|
||||
) from None
|
||||
except json.JSONDecodeError as exc:
|
||||
raise DatabaseUnreadable(
|
||||
f"{db_path} is not valid JSON ({exc}). Rebuild it with: "
|
||||
f"python scripts/generate_db.py --force --bios-dir bios --output {db_path}"
|
||||
) from None
|
||||
|
||||
|
||||
_mame_clone_map_cache: dict[str, dict[str, str]] = {}
|
||||
|
||||
|
||||
def get_mame_clone_map(bios_dir: str | None = None) -> dict[str, str]:
|
||||
"""The MAME clone map (clone_name -> canonical_name) of a scanned tree.
|
||||
|
||||
dedup.py writes _mame_clones.json beside the tree it scanned, and the
|
||||
map of one tree says nothing about another: read from the repository
|
||||
root whatever ``--bios-dir`` said, an alternate tree's renamed clones
|
||||
fell out of its packs. Without a tree the repository's own is read.
|
||||
"""
|
||||
if bios_dir is None:
|
||||
bios_dir = os.path.join(
|
||||
REPO_ROOT, "bios"
|
||||
)
|
||||
clone_path = os.path.join(os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json")
|
||||
cached = _mame_clone_map_cache.get(clone_path)
|
||||
if cached is not None:
|
||||
return cached
|
||||
clone_map: dict[str, str] = {}
|
||||
if os.path.exists(clone_path):
|
||||
with open(clone_path) as f:
|
||||
data = json.load(f)
|
||||
for canonical, info in data.items():
|
||||
for clone in info.get("clones", []):
|
||||
clone_map[clone] = canonical
|
||||
_mame_clone_map_cache[clone_path] = clone_map
|
||||
return clone_map
|
||||
@@ -0,0 +1,145 @@
|
||||
"""What a platform configuration declares: destinations, archive contents, names."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
|
||||
from core.paths import sanitize_pack_path
|
||||
|
||||
|
||||
def platform_declarations(
|
||||
config: dict, db: dict, *, enrich: bool = True
|
||||
) -> dict[str, list[tuple[int | None, str]]]:
|
||||
"""Every file name a platform declares, with each declaration's size and slot.
|
||||
|
||||
A name alone does not say which file a declaration is: RetroArch declares
|
||||
galaksija/ROM1.BIN, a 4 KiB ROM, and DOSBox reads a 32 KiB SC-55 ROM1.BIN.
|
||||
The size, from the platform entry or else from the file its hash names,
|
||||
tells a declaration of the same file from a same-named one. None stands
|
||||
for a size nobody knows. The slot is the declared destination, sanitized
|
||||
and case-folded, relative to the directory core files go to: RetroDECK
|
||||
writes bios/ in front of every destination, the others put it in
|
||||
base_destination.
|
||||
|
||||
With ``enrich``, a declaration also answers for the canonical name and
|
||||
the aliases the database knows its MD5 under. This handles a platform
|
||||
declaring a file under a different name than the emulator profile
|
||||
(e.g. Batocera ROM1 vs gsplus ROM).
|
||||
"""
|
||||
prefix = declared_root(config).lower()
|
||||
declared: dict[str, list[tuple[int | None, str]]] = {}
|
||||
by_md5 = db.get("indexes", {}).get("by_md5", {})
|
||||
files_db = db.get("files", {})
|
||||
for system in config.get("systems", {}).values():
|
||||
for fe in system.get("files", []):
|
||||
name = fe.get("name", "")
|
||||
slot = sanitize_pack_path(fe.get("destination") or name).lower()
|
||||
if prefix and slot.startswith(prefix + "/"):
|
||||
slot = slot[len(prefix) + 1:]
|
||||
# A zipped_file entry pins a member of the archive it names: its
|
||||
# md5 and its size, when stated, are not the archive's.
|
||||
by_hash: dict = {}
|
||||
size = None
|
||||
if not fe.get("zipped_file"):
|
||||
md5 = (fe.get("md5") or "").lower()
|
||||
if md5 and "," not in md5:
|
||||
by_hash = files_db.get(by_md5.get(md5, ""), {})
|
||||
size = fe.get("size")
|
||||
if size is None:
|
||||
size = files_db.get(
|
||||
(fe.get("sha1") or "").lower(), by_hash
|
||||
).get("size")
|
||||
if name:
|
||||
declared.setdefault(name, []).append((size, slot))
|
||||
if not enrich:
|
||||
continue
|
||||
for other in (by_hash.get("name", ""), *by_hash.get("aliases", [])):
|
||||
if other:
|
||||
declared.setdefault(other, []).append((by_hash.get("size"), slot))
|
||||
return declared
|
||||
|
||||
|
||||
def declared_root(config: dict) -> str:
|
||||
"""The BIOS directory a platform writes into every destination, if any.
|
||||
|
||||
Only a platform whose base_destination is explicitly empty does that
|
||||
(RetroDECK writes bios/ in front of each file), and core files go under
|
||||
the same directory. A config that does not state a base says nothing,
|
||||
and its common folder is a system's, not the BIOS root. A platform whose
|
||||
list also names folders beside the BIOS one states it as
|
||||
core_destination: EmuELEC's ports/ entries are a quarter of its list.
|
||||
"""
|
||||
if config.get("base_destination") != "":
|
||||
return ""
|
||||
if config.get("core_destination"):
|
||||
return str(config["core_destination"])
|
||||
roots = [
|
||||
d.split("/", 1)[0]
|
||||
for system in config.get("systems", {}).values()
|
||||
for f in system.get("files", [])
|
||||
if "/" in (d := f.get("destination", "") or "")
|
||||
]
|
||||
if not roots:
|
||||
return ""
|
||||
root, count = Counter(roots).most_common(1)[0]
|
||||
return root if count / len(roots) > 0.9 else ""
|
||||
|
||||
|
||||
def platform_declared_contents(config: dict, db: dict) -> dict[str, set[str]]:
|
||||
"""The folders each declared file's content sits in, keyed by its hashes.
|
||||
|
||||
A core that scans a folder and identifies a ROM by its checksum reads a
|
||||
declared file whatever its name: RetroDECK lists atari800's Atari BASIC
|
||||
Rev A as ROM_BASIC_A, and the core takes it by CRC32. Keys are
|
||||
"md5:", "sha1:" and "crc32:" values of the database file the
|
||||
declaration resolves to, each with the declared slot's folder.
|
||||
"""
|
||||
prefix = declared_root(config).lower()
|
||||
by_md5 = db.get("indexes", {}).get("by_md5", {})
|
||||
files_db = db.get("files", {})
|
||||
contents: dict[str, set[str]] = {}
|
||||
for system in config.get("systems", {}).values():
|
||||
for fe in system.get("files", []):
|
||||
if fe.get("zipped_file"):
|
||||
continue
|
||||
record = files_db.get((fe.get("sha1") or "").lower())
|
||||
md5 = (fe.get("md5") or "").lower()
|
||||
if record is None and md5 and "," not in md5:
|
||||
sha1 = by_md5.get(md5, "")
|
||||
record = files_db.get(sha1[0] if isinstance(sha1, list) else sha1)
|
||||
if not record:
|
||||
continue
|
||||
slot = sanitize_pack_path(fe.get("destination") or fe.get("name", "")).lower()
|
||||
if prefix and slot.startswith(prefix + "/"):
|
||||
slot = slot[len(prefix) + 1:]
|
||||
folder = slot.rpartition("/")[0]
|
||||
for field in ("md5", "sha1", "crc32"):
|
||||
value = str(record.get(field) or "").lower()
|
||||
if value:
|
||||
contents.setdefault(f"{field}:{value}", set()).add(folder)
|
||||
return contents
|
||||
|
||||
|
||||
def merged_platform_declared_contents(configs: list[dict], db: dict) -> dict[str, set[str]]:
|
||||
"""`platform_declared_contents` of several platforms, one index."""
|
||||
merged: dict[str, set[str]] = {}
|
||||
for config in configs:
|
||||
for key, folders in platform_declared_contents(config, db).items():
|
||||
merged.setdefault(key, set()).update(folders)
|
||||
return merged
|
||||
|
||||
|
||||
def merged_platform_declarations(
|
||||
configs: list[dict], db: dict
|
||||
) -> dict[str, list[tuple[int | None, str]]]:
|
||||
"""`platform_declarations` of several platforms, one index."""
|
||||
merged: dict[str, list[tuple[int | None, str]]] = {}
|
||||
for config in configs:
|
||||
for name, places in platform_declarations(config, db).items():
|
||||
merged.setdefault(name, []).extend(places)
|
||||
return merged
|
||||
|
||||
|
||||
def expand_platform_declared_names(config: dict, db: dict) -> set[str]:
|
||||
"""The names a platform declares, enriched as `platform_declarations`."""
|
||||
return set(platform_declarations(config, db))
|
||||
@@ -392,7 +392,7 @@ def _served_digests() -> dict[str, str]:
|
||||
f"{LARGE_FILES_RELEASE}"
|
||||
)
|
||||
headers = {"User-Agent": "retrobios/1.0", "Accept": "application/vnd.github+json"}
|
||||
from common import github_token
|
||||
from core.github import github_token
|
||||
|
||||
token = github_token()
|
||||
if token:
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""Loading a platform's configuration: inheritance, shared groups, registry cores, rom folders."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None
|
||||
|
||||
from model.sources import source_yaml
|
||||
|
||||
|
||||
_shared_yml_cache: dict[str, dict] = {}
|
||||
_platform_config_cache: dict[tuple[str, str], dict] = {}
|
||||
|
||||
|
||||
def _inherited_yaml(platform_name: str, platforms_dir: str) -> tuple[dict, list[str]]:
|
||||
"""The platform's YAML merged over its parents', and the chain of names.
|
||||
|
||||
Built from fresh copies: merging over the parent's cached config shared
|
||||
its systems, so a child's overrides rewrote the parent for the rest of
|
||||
the run.
|
||||
"""
|
||||
if yaml is None:
|
||||
raise ImportError("PyYAML required: pip install pyyaml")
|
||||
|
||||
config_file = os.path.join(platforms_dir, f"{platform_name}.yml")
|
||||
if not os.path.exists(config_file):
|
||||
raise FileNotFoundError(f"Platform config not found: {config_file}")
|
||||
|
||||
with open(config_file) as f:
|
||||
config = source_yaml(f) or {}
|
||||
if "inherits" not in config:
|
||||
return config, [platform_name]
|
||||
|
||||
merged, chain = _inherited_yaml(config["inherits"], platforms_dir)
|
||||
# A version names one platform's release, never its parent's: Lakka
|
||||
# read as RetroArch v1.22.2 in its manifest, pack name and site page.
|
||||
# dat_version stays, it is the version of the inherited list itself.
|
||||
merged.pop("version", None)
|
||||
merged.update(
|
||||
{k: v for k, v in config.items() if k not in ("inherits", "overrides")}
|
||||
)
|
||||
if "overrides" in config and "systems" in config["overrides"]:
|
||||
merged.setdefault("systems", {})
|
||||
for sys_id, override in config["overrides"]["systems"].items():
|
||||
if sys_id in merged["systems"]:
|
||||
merged["systems"][sys_id] = {
|
||||
**merged["systems"][sys_id],
|
||||
**override,
|
||||
}
|
||||
else:
|
||||
merged["systems"][sys_id] = override
|
||||
return merged, [platform_name, *chain]
|
||||
|
||||
|
||||
def _cached_platform_yaml(path: str) -> dict:
|
||||
"""A registry or shared-group file, parsed once per real path."""
|
||||
real = os.path.realpath(path)
|
||||
if real not in _shared_yml_cache:
|
||||
with open(path) as f:
|
||||
_shared_yml_cache[real] = source_yaml(f) or {}
|
||||
return _shared_yml_cache[real]
|
||||
|
||||
|
||||
def _merge_registry_cores(config: dict, reg_entry: dict, depth: int) -> None:
|
||||
"""Merge cores (union for lists, override for all_libretro), a
|
||||
parent's only where the platform names none."""
|
||||
reg_cores = reg_entry.get("cores")
|
||||
if reg_cores is None or not (depth == 0 or "cores" not in config):
|
||||
return
|
||||
cfg_cores = config.get("cores")
|
||||
if reg_cores == "all_libretro":
|
||||
config["cores"] = "all_libretro"
|
||||
elif isinstance(reg_cores, list) and isinstance(cfg_cores, list):
|
||||
merged_set = {str(c) for c in cfg_cores} | {str(c) for c in reg_cores}
|
||||
config["cores"] = sorted(merged_set)
|
||||
elif isinstance(reg_cores, list) and cfg_cores is None:
|
||||
config["cores"] = reg_cores
|
||||
|
||||
|
||||
def _apply_shared_groups(config: dict, shared_groups: dict) -> None:
|
||||
"""Add each included shared group's files to the systems naming it."""
|
||||
# A shared group's file joins a system unless the platform already has
|
||||
# it there. Case only makes two names one where the filesystem folds it:
|
||||
# Lakka and RetroPie run on Linux, and np2kai opens 2608_bd.wav beside
|
||||
# System.dat's 2608_BD.WAV.
|
||||
def fold(destination: str) -> str:
|
||||
return destination.lower() if config.get("case_insensitive_fs") else destination
|
||||
|
||||
for system in config.get("systems", {}).values():
|
||||
for group_name in system.get("includes", []):
|
||||
if group_name not in shared_groups:
|
||||
continue
|
||||
existing = {
|
||||
(f.get("name"), f.get("destination", f.get("name")))
|
||||
for f in system.get("files", [])
|
||||
}
|
||||
existing_lower = {
|
||||
fold(f.get("destination", f.get("name", "")))
|
||||
for f in system.get("files", [])
|
||||
}
|
||||
for gf in shared_groups[group_name]:
|
||||
key = (gf.get("name"), gf.get("destination", gf.get("name")))
|
||||
dest_lower = fold(gf.get("destination", gf.get("name", "")))
|
||||
if key not in existing and dest_lower not in existing_lower:
|
||||
# Marked as ours: the platform's own file does not
|
||||
# carry it, and an export must not count it kept.
|
||||
system.setdefault("files", []).append(
|
||||
{**gf, "shared_group": group_name}
|
||||
)
|
||||
existing.add(key)
|
||||
|
||||
|
||||
def _mark_composite_archives(config: dict) -> None:
|
||||
"""Mark every .zip entry as hashed by its members.
|
||||
|
||||
Recalbox hashes a .zip by its members, so a plain md5 never answers one
|
||||
of its archive declarations: the resolver reads the mark per entry.
|
||||
"""
|
||||
config["systems"] = {
|
||||
sys_id: {
|
||||
**system,
|
||||
"files": [
|
||||
{**f, "zip_digest": "composite"}
|
||||
if str(f.get("name", "")).lower().endswith(".zip")
|
||||
else f
|
||||
for f in system.get("files", [])
|
||||
],
|
||||
}
|
||||
for sys_id, system in config.get("systems", {}).items()
|
||||
}
|
||||
|
||||
|
||||
def _tag_platform_systems(config: dict) -> None:
|
||||
"""Each entry carries the system that declares it.
|
||||
|
||||
A hashless name match is narrowed to the maker folder that system names
|
||||
(resolve_local_file). A system that names its own cores (EmuELEC,
|
||||
AmberELEC, KNULLI) also passes them on, so another emulator's tree is
|
||||
foreign to its entries. Fresh dicts, since a YAML anchor can share one
|
||||
entry between systems.
|
||||
"""
|
||||
config["systems"] = {
|
||||
sys_id: {
|
||||
**system,
|
||||
"files": [
|
||||
{
|
||||
**f,
|
||||
"platform_system": sys_id,
|
||||
**(
|
||||
{"platform_cores": list(system["cores"])}
|
||||
if system.get("cores")
|
||||
else {}
|
||||
),
|
||||
}
|
||||
for f in system["files"]
|
||||
],
|
||||
}
|
||||
if isinstance(system, dict) and system.get("files")
|
||||
else system
|
||||
for sys_id, system in config.get("systems", {}).items()
|
||||
}
|
||||
|
||||
|
||||
def _attach_rom_folders(config: dict, platform_name: str, platforms_dir: str) -> None:
|
||||
"""Where the platform's games live, as its rom folders file records it
|
||||
from the OS's own source (platforms/romfolders/<key>.yml, roms_root)."""
|
||||
romfolders = os.path.join(platforms_dir, "romfolders", f"{platform_name}.yml")
|
||||
if not os.path.exists(romfolders):
|
||||
return
|
||||
with open(romfolders) as f:
|
||||
roms_root = (source_yaml(f) or {}).get("roms_root")
|
||||
if isinstance(roms_root, dict):
|
||||
config["_roms_root"] = roms_root
|
||||
with open(romfolders) as f:
|
||||
folders = (source_yaml(f) or {}).get("folders")
|
||||
if isinstance(folders, list):
|
||||
config["_rom_folders"] = [row for row in folders if isinstance(row, dict)]
|
||||
|
||||
|
||||
def load_platform_config(platform_name: str, platforms_dir: str = "platforms") -> dict:
|
||||
"""Load a platform config with inheritance and shared group resolution.
|
||||
|
||||
This is the SINGLE implementation used by generate_pack, generate_readme,
|
||||
verify, and auto_fetch. No other copy should exist.
|
||||
"""
|
||||
cache_key = (platform_name, os.path.realpath(platforms_dir))
|
||||
if cache_key in _platform_config_cache:
|
||||
return _platform_config_cache[cache_key]
|
||||
|
||||
config, chain = _inherited_yaml(platform_name, platforms_dir)
|
||||
|
||||
shared_path = os.path.join(platforms_dir, "_shared.yml")
|
||||
# Merge metadata from _registry.yml. The registry is our curated source,
|
||||
# while the scraped YAML may be incomplete (missing cores, metadata fields).
|
||||
# Registry fields supplement (not replace) the scraped config.
|
||||
registry_path = os.path.join(platforms_dir, "_registry.yml")
|
||||
if os.path.exists(registry_path):
|
||||
reg = _cached_platform_yaml(registry_path)
|
||||
# The platform's own entry first, then its parents' for what it does
|
||||
# not say: RetroPie's status, scraper and install are its own, its
|
||||
# verification mode is RetroArch's.
|
||||
for depth, name in enumerate(chain):
|
||||
reg_entry = reg.get("platforms", {}).get(name, {})
|
||||
_merge_registry_cores(config, reg_entry, depth)
|
||||
|
||||
# Merge all registry fields absent from config (except cores,
|
||||
# handled above with union logic). No hardcoded list: any field
|
||||
# added to the registry is automatically available in the config.
|
||||
for key, val in reg_entry.items():
|
||||
if key != "cores" and key not in config:
|
||||
config[key] = val
|
||||
|
||||
if os.path.exists(shared_path):
|
||||
shared = _cached_platform_yaml(shared_path)
|
||||
_apply_shared_groups(config, shared.get("shared_groups", {}))
|
||||
|
||||
if config.get("zip_digest") == "composite":
|
||||
_mark_composite_archives(config)
|
||||
|
||||
_tag_platform_systems(config)
|
||||
|
||||
# The registry key, which per-platform profile fields (installed_on,
|
||||
# not_bundled_on) name: the display name differs (MiSTer FPGA).
|
||||
config["_key"] = platform_name
|
||||
_attach_rom_folders(config, platform_name, platforms_dir)
|
||||
_platform_config_cache[cache_key] = config
|
||||
return config
|
||||
|
||||
|
||||
def native_layer(config: dict | None) -> dict | None:
|
||||
"""The platform config without what we add to it.
|
||||
|
||||
A shared group's files join the config for the pack, but the platform's
|
||||
file does not carry them: counted kept, they were written into
|
||||
libretro's System.dat (N88EXT0-3.ROM) as if libretro declared them. What
|
||||
a core needs from a group reaches the export through the truth, as an
|
||||
addition the format's gates apply to. A scraper's mirror of an entry
|
||||
under another system (RomM's tg16 firmware under turbografx-cd), and a
|
||||
file our scraper adds from the cores' source (Dolphin's DSP ROMs in
|
||||
RetroArch's config), are not in the platform's file either.
|
||||
"""
|
||||
if config is None:
|
||||
return None
|
||||
systems = {
|
||||
sys_id: {
|
||||
**system,
|
||||
"files": [
|
||||
f for f in system.get("files", [])
|
||||
if not ({"shared_group", "mirror_of", "curated"} & f.keys())
|
||||
],
|
||||
}
|
||||
for sys_id, system in config.get("systems", {}).items()
|
||||
}
|
||||
return {**config, "systems": systems}
|
||||
@@ -0,0 +1,297 @@
|
||||
"""Loading and selecting emulator profiles, and the fields that identify an entry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None
|
||||
|
||||
from core.cli import InputMissing, suggest_names
|
||||
from model.alternatives import derive_member_requirements
|
||||
from model.sources import source_yaml
|
||||
from model.systems import _norm_system_id
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
# The content tests a profile can declare in ``validation:``, each run by
|
||||
# reading the candidate the way the emulator does.
|
||||
CONTENT_CHECKS = frozenset({"romdir", "masked_sha1"})
|
||||
|
||||
|
||||
_emulator_profiles_cache: dict[tuple[str, bool], dict[str, dict]] = {}
|
||||
|
||||
|
||||
class ProfileSelectionError(ValueError):
|
||||
"""A named profile cannot answer for itself."""
|
||||
|
||||
|
||||
def profiles_for_systems(
|
||||
profiles: dict, system_ids: list[str], standalone: bool = False
|
||||
) -> list[str]:
|
||||
"""Profile keys that serve any of the systems, spelled either way.
|
||||
|
||||
Compared on the normalized id: stella2014 writes atari_2600 where every
|
||||
other profile writes atari-2600, and an exact match built two different
|
||||
packs under one file name, the second replacing the first.
|
||||
"""
|
||||
wanted = {_norm_system_id(sid) for sid in system_ids}
|
||||
matching = []
|
||||
for name, profile in sorted(profiles.items()):
|
||||
if profile.get("type") in ("launcher", "alias") or profile.get("role") == "test":
|
||||
continue
|
||||
if standalone and "standalone" not in profile.get("type", "libretro"):
|
||||
continue
|
||||
if wanted & {_norm_system_id(sid) for sid in profile.get("systems", [])}:
|
||||
matching.append(name)
|
||||
return matching
|
||||
|
||||
|
||||
def entry_system_ids(entry: dict, profile: dict) -> list[str]:
|
||||
"""Systems a profile entry serves.
|
||||
|
||||
The entry's own `system:`, else its own `systems:` (a MAME device set
|
||||
the machines of several systems load), else every system of its
|
||||
profile.
|
||||
"""
|
||||
own = entry.get("system")
|
||||
if own:
|
||||
return [str(own)]
|
||||
listed = entry.get("systems") or profile.get("systems") or []
|
||||
return [str(sid) for sid in listed]
|
||||
|
||||
|
||||
def entry_serves_systems(entry: dict, profile: dict, system_ids: list[str]) -> bool:
|
||||
"""Whether a profile entry belongs to one of the systems, spelled either way.
|
||||
|
||||
The entry's own `system:` or `systems:` decides. One without either
|
||||
serves every system of its profile, the rule a platform pack applies to
|
||||
core extras.
|
||||
"""
|
||||
wanted = {_norm_system_id(sid) for sid in system_ids}
|
||||
return bool(wanted & {_norm_system_id(sid) for sid in entry_system_ids(entry, profile)})
|
||||
|
||||
|
||||
def select_emulator_profiles(
|
||||
profile_names: list[str],
|
||||
all_profiles: dict,
|
||||
standalone: bool = False,
|
||||
) -> list[tuple[str, dict]]:
|
||||
"""Resolve named profiles, refusing the ones that answer for no core.
|
||||
|
||||
An alias is the same binary under another name, so naming one selects
|
||||
the profile it is an alias of, said on stderr. A launcher only starts an
|
||||
emulator and has no requirements of its own: naming one is a question
|
||||
about the wrong profile, and the error says so. Raising rather than exiting lets the verifier stop and the
|
||||
builder return empty-handed from one rule.
|
||||
"""
|
||||
selected: list[tuple[str, dict]] = []
|
||||
for name in profile_names:
|
||||
if name not in all_profiles:
|
||||
# A buildbot name (pcfx, advmame) lives in a profile's cores:,
|
||||
# and the spelling hints sent pcfx to two PlayStation cores.
|
||||
claimants = sorted(
|
||||
key for key in upstream_profile_index(all_profiles).get(name, ())
|
||||
if all_profiles[key].get("type") != "launcher" and all_profiles[key].get("role") != "test"
|
||||
)
|
||||
if len(claimants) == 1:
|
||||
name = claimants[0]
|
||||
elif claimants:
|
||||
raise ProfileSelectionError(
|
||||
f"{name} is a core name of {', '.join(claimants)}: "
|
||||
f"use --emulator with one of them"
|
||||
)
|
||||
if name not in all_profiles:
|
||||
available = sorted(
|
||||
key
|
||||
for key, value in all_profiles.items()
|
||||
if value.get("type") != "alias" and value.get("role") != "test"
|
||||
)
|
||||
raise ProfileSelectionError(
|
||||
f"emulator '{name}' not found\n"
|
||||
+ suggest_names([name], available, "--list-emulators")
|
||||
)
|
||||
profile = all_profiles[name]
|
||||
kind = profile.get("type", "libretro")
|
||||
if kind == "alias":
|
||||
# An alias without alias_of is found through the profile whose
|
||||
# cores: names it, as the buildbot reverse index does.
|
||||
target = profile.get("alias_of") or next(
|
||||
(
|
||||
key for key, value in all_profiles.items()
|
||||
if value.get("type") != "alias" and name in (value.get("cores") or [])
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not target or target not in all_profiles:
|
||||
raise ProfileSelectionError(
|
||||
f"{name} is an alias with no profile of its own to name"
|
||||
)
|
||||
# The name a user reads in RetroArch or on the buildbot: the tool
|
||||
# knows the profile, so it says which and carries on.
|
||||
print(f"{name} is {target}: using its profile", file=sys.stderr)
|
||||
name, profile = target, all_profiles[target]
|
||||
kind = profile.get("type", "libretro")
|
||||
if any(key == name for key, _ in selected):
|
||||
continue
|
||||
if kind == "launcher":
|
||||
raise ProfileSelectionError(
|
||||
f"{name} is a launcher: use the emulator it launches"
|
||||
)
|
||||
if standalone and "standalone" not in kind:
|
||||
raise ProfileSelectionError(
|
||||
f"{name} ({kind}) does not support --standalone"
|
||||
)
|
||||
selected.append((name, profile))
|
||||
return selected
|
||||
|
||||
|
||||
PROFILE_BACKUP_SUFFIX = ".old.yml"
|
||||
|
||||
|
||||
def source_yaml_paths(directory: str | Path) -> list[Path]:
|
||||
"""YAML sources in a directory, without the copies the hash merge keeps."""
|
||||
return [
|
||||
path
|
||||
for path in sorted(Path(directory).glob("*.yml"))
|
||||
if not path.name.endswith(PROFILE_BACKUP_SUFFIX)
|
||||
]
|
||||
|
||||
|
||||
def installed_data_refs(platform: str, emulators_dir: str = "") -> frozenset[str]:
|
||||
"""Data directories a platform's own packages install beside the cores.
|
||||
|
||||
The platform layer names trees for its systems (retroarch.yml carries
|
||||
dolphin-sys and ppsspp-assets, and Lakka inherits them), while Lakka's
|
||||
core packages put both into the system directory themselves. A profile
|
||||
records that with installed_on on its data directory reference.
|
||||
"""
|
||||
emulators_dir = emulators_dir or os.path.join(
|
||||
REPO_ROOT, "emulators")
|
||||
return frozenset(
|
||||
str(tree.get("ref", ""))
|
||||
for profile in load_emulator_profiles(emulators_dir, skip_aliases=False).values()
|
||||
for tree in profile.get("data_directories") or []
|
||||
if isinstance(tree, dict) and platform in (tree.get("installed_on") or [])
|
||||
)
|
||||
|
||||
|
||||
def load_emulator_profiles(
|
||||
emulators_dir: str,
|
||||
skip_aliases: bool = True,
|
||||
) -> dict[str, dict]:
|
||||
"""Load all emulator YAML profiles from a directory (cached)."""
|
||||
cache_key = (os.path.realpath(emulators_dir), skip_aliases)
|
||||
if cache_key in _emulator_profiles_cache:
|
||||
return _emulator_profiles_cache[cache_key]
|
||||
if skip_aliases:
|
||||
# A filter over the full set: parsed once, 534 YAML files cost 1.6 s
|
||||
# every time a process asked for both variants.
|
||||
profiles = {
|
||||
name: profile
|
||||
for name, profile in load_emulator_profiles(emulators_dir, False).items()
|
||||
if profile.get("type") != "alias"
|
||||
}
|
||||
_emulator_profiles_cache[cache_key] = profiles
|
||||
return profiles
|
||||
if importlib.util.find_spec("yaml") is None:
|
||||
# Every consumer reads {} as "this repo documents no emulator", which
|
||||
# is what a broken install looks like from the outside: zero coverage,
|
||||
# no gap, nothing to fix.
|
||||
print(
|
||||
"warning: pyyaml is not installed, no emulator profile was loaded",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return {}
|
||||
profiles = {}
|
||||
emu_path = Path(emulators_dir)
|
||||
if not emu_path.is_dir():
|
||||
# Read as "no emulator", a mistyped --emulators-dir built a pack
|
||||
# without any core file marked OK, and sitesources wrote {} over
|
||||
# source-paths.json, both exiting 0.
|
||||
raise InputMissing(f"no emulator profile directory at {emulators_dir}")
|
||||
for f in source_yaml_paths(emu_path):
|
||||
with open(f) as fh:
|
||||
profile = source_yaml(fh) or {}
|
||||
if "emulator" not in profile:
|
||||
continue
|
||||
_normalize_hash_fields(profile)
|
||||
derive_member_requirements(profile)
|
||||
profiles[f.stem] = profile
|
||||
_emulator_profiles_cache[cache_key] = profiles
|
||||
return profiles
|
||||
|
||||
|
||||
_HASH_FIELDS = ("crc32", "md5", "sha1", "sha256")
|
||||
|
||||
|
||||
def _normalize_hash_fields(node: object) -> None:
|
||||
"""Coerce hash values to str in place.
|
||||
|
||||
YAML types unquoted digit-only hashes (e.g. crc32: 70295038) as int,
|
||||
which breaks string comparisons and formatting downstream.
|
||||
"""
|
||||
if isinstance(node, dict):
|
||||
for key, val in node.items():
|
||||
if key in _HASH_FIELDS:
|
||||
if isinstance(val, int):
|
||||
node[key] = str(val)
|
||||
elif isinstance(val, list):
|
||||
node[key] = [str(v) if isinstance(v, int) else v for v in val]
|
||||
else:
|
||||
_normalize_hash_fields(val)
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
_normalize_hash_fields(item)
|
||||
|
||||
|
||||
def unique_emulator_profiles(profiles: dict[str, dict]) -> dict[str, dict]:
|
||||
"""Profiles counting as distinct emulators (aliases and tests excluded)."""
|
||||
return {
|
||||
k: v for k, v in profiles.items() if v.get("type") != "alias" and v.get("role") != "test"
|
||||
}
|
||||
|
||||
|
||||
# What identifies a profile entry's content, carried unchanged wherever the
|
||||
# entry travels (cross-reference report, core extras, second-pass copies).
|
||||
# Each copy once kept its own subset: np2kai's bios.rom lost min_size and
|
||||
# validation on the way and resolved to an IBM PCjr ROM of the same name.
|
||||
PROFILE_IDENTITY_FIELDS = (
|
||||
"sha1", "md5", "sha256", "crc32", "size", "min_size", "max_size",
|
||||
"size_multiple", "validation", *sorted(CONTENT_CHECKS), "aliases", "unsourceable",
|
||||
)
|
||||
|
||||
|
||||
def upstream_profile_index(
|
||||
profiles: dict[str, dict], include_aliases: bool = False
|
||||
) -> dict[str, set[str]]:
|
||||
"""Every name a core is known by upstream -> the profiles that claim it.
|
||||
|
||||
A name can be claimed twice: the buildbot's `pcsx2` is the LRPS2 core,
|
||||
which lrps2.yml lists in `cores:`, and also the key of the standalone
|
||||
pcsx2 profile. A last-wins dict kept one of the two depending on file
|
||||
order, and a RetroArch target filter dropped LRPS2's files. Callers
|
||||
choose: a platform list prefers the exact key, a target filter keeps
|
||||
every claimant.
|
||||
"""
|
||||
index: dict[str, set[str]] = {}
|
||||
for name, profile in profiles.items():
|
||||
if not include_aliases and profile.get("type") == "alias":
|
||||
continue
|
||||
index.setdefault(name, set()).add(name)
|
||||
for core in profile.get("cores") or []:
|
||||
index.setdefault(str(core), set()).add(name)
|
||||
return index
|
||||
|
||||
|
||||
def preferred_profile(index: dict[str, set[str]], name: str) -> str | None:
|
||||
"""The profile a name designates: its own key first, else the first claimant."""
|
||||
claimants = index.get(name)
|
||||
if not claimants:
|
||||
return None
|
||||
return name if name in claimants else sorted(claimants)[0]
|
||||
@@ -0,0 +1,69 @@
|
||||
"""The platform registry and the data directory registry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from core.cli import InputMissing
|
||||
from model.sources import source_yaml
|
||||
|
||||
|
||||
def load_data_dir_registry(platforms_dir: str = "platforms") -> dict:
|
||||
"""Load the data directory registry from _data_dirs.yml."""
|
||||
registry_path = os.path.join(platforms_dir, "_data_dirs.yml")
|
||||
if not os.path.exists(registry_path):
|
||||
return {}
|
||||
with open(registry_path) as f:
|
||||
data = source_yaml(f) or {}
|
||||
return data.get("data_directories", {})
|
||||
|
||||
|
||||
def load_platform_registry(platforms_dir: str = "platforms") -> dict:
|
||||
"""Return the `platforms:` mapping from _registry.yml, empty if absent."""
|
||||
registry_path = os.path.join(platforms_dir, "_registry.yml")
|
||||
if not os.path.exists(registry_path):
|
||||
return {}
|
||||
with open(registry_path) as f:
|
||||
return (source_yaml(f) or {}).get("platforms", {})
|
||||
|
||||
|
||||
def list_registered_platforms(platforms_dir: str = "platforms") -> list[str]:
|
||||
"""List platforms registered in _registry.yml.
|
||||
|
||||
Only registered platforms generate packs and appear in CI.
|
||||
Unregistered YAMLs (e.g., emulatorjs.yml) are base configs for inheritance.
|
||||
|
||||
A missing registry, or a registered platform whose file is gone, raises:
|
||||
left out quietly, verify --all --strict and every --all build passed
|
||||
having checked none of it, and install.py kept serving its last manifest.
|
||||
"""
|
||||
registry_path = os.path.join(platforms_dir, "_registry.yml")
|
||||
if not os.path.exists(registry_path):
|
||||
raise InputMissing(f"no platform registry at {registry_path}")
|
||||
with open(registry_path) as f:
|
||||
registry = source_yaml(f) or {}
|
||||
platforms = []
|
||||
for name, meta in sorted(registry.get("platforms", {}).items()):
|
||||
config_path = os.path.join(platforms_dir, meta.get("config", f"{name}.yml"))
|
||||
if not os.path.exists(config_path):
|
||||
raise FileNotFoundError(
|
||||
f"{name} is registered in {registry_path} but {config_path} does not exist"
|
||||
)
|
||||
platforms.append(name)
|
||||
return platforms
|
||||
|
||||
|
||||
def list_release_pack_platforms(platforms_dir: str = "platforms") -> list[str]:
|
||||
"""Registered platforms a release publishes a ZIP pack for.
|
||||
|
||||
`release_pack: true` in _registry.yml is the whole list: the build of
|
||||
`--all`, the pack checks, the release record and every download table
|
||||
read it. The other platforms keep their install manifest and are served
|
||||
by the installer.
|
||||
"""
|
||||
registry = load_platform_registry(platforms_dir)
|
||||
return [
|
||||
name
|
||||
for name in list_registered_platforms(platforms_dir)
|
||||
if registry.get(name, {}).get("release_pack") is True
|
||||
]
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Parsing the repository's YAML sources, naming the file a syntax error is in."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, TextIO
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None
|
||||
|
||||
from core.cli import SourceUnreadable
|
||||
from model.safeparse import yaml_load
|
||||
|
||||
|
||||
def source_yaml(stream: TextIO) -> Any:
|
||||
"""Parse one of our YAML sources, naming the file a syntax error is in.
|
||||
|
||||
Every profile is loaded whatever the command, so one misindented key in
|
||||
an unrelated profile stopped `verify.py --emulator handy` on a 37-line
|
||||
traceback, the faulty file named only near its end.
|
||||
"""
|
||||
if yaml is None:
|
||||
return yaml_load(stream)
|
||||
try:
|
||||
return yaml_load(stream)
|
||||
except yaml.YAMLError as exc:
|
||||
mark = getattr(exc, "problem_mark", None)
|
||||
where = f"{stream.name}:{mark.line + 1}" if mark else stream.name
|
||||
problem = getattr(exc, "problem", None) or str(exc).splitlines()[0]
|
||||
raise SourceUnreadable(
|
||||
f"{where}: {problem}. Check it with: "
|
||||
"python scripts/validate_schemas.py --source-only"
|
||||
) from None
|
||||
@@ -0,0 +1,340 @@
|
||||
"""System ids: manufacturers, aliases, normalization and the names platforms give them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import re
|
||||
|
||||
from core.cli import suggest_names
|
||||
from model.platforms import native_layer
|
||||
|
||||
|
||||
MANUFACTURER_PREFIXES = (
|
||||
"acorn-",
|
||||
"apple-",
|
||||
"microsoft-",
|
||||
"nintendo-",
|
||||
"sony-",
|
||||
"sega-",
|
||||
"snk-",
|
||||
"panasonic-",
|
||||
"nec-",
|
||||
"epoch-",
|
||||
"mattel-",
|
||||
"fairchild-",
|
||||
"hartung-",
|
||||
"tiger-",
|
||||
"magnavox-",
|
||||
"philips-",
|
||||
"bandai-",
|
||||
"casio-",
|
||||
"coleco-",
|
||||
"commodore-",
|
||||
"sharp-",
|
||||
"sinclair-",
|
||||
"atari-",
|
||||
"sammy-",
|
||||
"gce-",
|
||||
"interton-",
|
||||
"texas-instruments-",
|
||||
"videoton-",
|
||||
"wenquxing-",
|
||||
"aquaplus-",
|
||||
)
|
||||
|
||||
|
||||
def derive_manufacturer(system_id: str, system_data: dict) -> str:
|
||||
"""Derive manufacturer name for a system.
|
||||
|
||||
Priority: explicit manufacturer field > system ID prefix > 'Other'.
|
||||
"""
|
||||
mfr = system_data.get("manufacturer", "")
|
||||
if mfr and mfr not in ("Various", "Other"):
|
||||
return mfr.split("|")[0].strip()
|
||||
s = system_id.lower().replace("_", "-")
|
||||
for prefix in MANUFACTURER_PREFIXES:
|
||||
if s.startswith(prefix):
|
||||
return prefix.rstrip("-").title()
|
||||
return "Other"
|
||||
|
||||
|
||||
# Abbreviations that normalization alone cannot resolve.
|
||||
# Maps platform-specific short names to canonical profile system IDs.
|
||||
SYSTEM_ALIASES: dict[str, str] = {
|
||||
"gmaster": "hartung-game-master",
|
||||
"n64dd": "nintendo-64dd",
|
||||
"neogeo64": "hyper-neogeo64",
|
||||
"psvita": "sony-playstation-vita",
|
||||
# Platform IDs missing the manufacturer-prefix hyphen
|
||||
"atari5200": "atari-5200",
|
||||
"atari7800": "atari-7800",
|
||||
"atarist": "atari-st",
|
||||
"sega32x": "sega-32x",
|
||||
"segastv": "sega-stv",
|
||||
"ti994a": "ti99",
|
||||
# Other spellings of one machine: RomM files the Mega CD as sega-mega-cd
|
||||
# and the disk system as nintendo-fds, which normalize to the ids the
|
||||
# profiles use only through these.
|
||||
"sega-segacd": "sega-megacd",
|
||||
"nes-fds": "nintendo-fds",
|
||||
# One machine, two spellings across platform folders and profiles:
|
||||
# Recalbox's apple2gs, Batocera's astrocade, KNULLI and RetroBat's
|
||||
# astrocde, MiSTer's creativision, Batocera's gamepocketcomputer
|
||||
# folder, BizHawk's Super Game Boy, the FBA 2012 board names.
|
||||
"apple2gs": "apple-iigs",
|
||||
"astrocade": "bally-astrocade",
|
||||
"astrocde": "bally-astrocade",
|
||||
"creativision": "crvision",
|
||||
"gamepocketcomputer": "gamepock",
|
||||
"nintendo-super-game-boy": "nintendo-sgb",
|
||||
"cps1": "capcom-cps1",
|
||||
"cps2": "capcom-cps2",
|
||||
"cps3": "capcom-cps3",
|
||||
"pgm": "igs-pgm",
|
||||
# Rom folder names the setups of platforms/romfolders/ give a machine,
|
||||
# each proven by the source_ref of the folder row that names it: the
|
||||
# short tags of Onion, CrossMix-OS, Koriki and the MinUI family, the
|
||||
# number words of Koriki and plumOS, the region and hack folders of
|
||||
# ES-DE, the MSU-1 folders of the ES family, the arcade cores named as
|
||||
# folders.
|
||||
"a2600": "atari-2600",
|
||||
"atari2600": "atari-2600",
|
||||
"fiftytwohundred": "atari-5200",
|
||||
"seventyeighthundred": "atari-7800",
|
||||
"atarixegs": "xegs",
|
||||
"atarijaguarcd": "atari-jaguarcd",
|
||||
"fc": "nintendo-nes",
|
||||
"nesh": "nintendo-nes",
|
||||
"sfc": "nintendo-snes",
|
||||
"supa": "nintendo-snes",
|
||||
"snesh": "nintendo-snes",
|
||||
"snesna": "nintendo-snes",
|
||||
"snesmsu1": "nintendo-snes",
|
||||
"snes-msu1": "nintendo-snes",
|
||||
"msu1": "nintendo-snes",
|
||||
"vb": "nintendo-virtualboy",
|
||||
"gc": "nintendo-gamecube",
|
||||
"gbh": "nintendo-gb",
|
||||
"gb2players": "nintendo-gb",
|
||||
"gbch": "nintendo-gbc",
|
||||
"gbc2players": "nintendo-gbc",
|
||||
"gbah": "nintendo-gba",
|
||||
"mgba": "nintendo-gba",
|
||||
"poke": "nintendo-pokemon-mini",
|
||||
"pkm": "nintendo-pokemon-mini",
|
||||
"md": "sega-megadrive",
|
||||
"genh": "sega-megadrive",
|
||||
"megadriveh": "sega-megadrive",
|
||||
"megadrivejp": "sega-megadrive",
|
||||
"megadrive-japan": "sega-megadrive",
|
||||
"msumd": "sega-megadrive",
|
||||
"mdmsu": "sega-megadrive",
|
||||
"ms": "sega-mastersystem",
|
||||
"mark3": "sega-mastersystem",
|
||||
"gamegearh": "sega-gamegear",
|
||||
"megacdjp": "sega-megacd",
|
||||
"saturnjp": "sega-saturn",
|
||||
"sega32xjp": "sega-32x",
|
||||
"sega32xna": "sega-32x",
|
||||
"thirtytwox": "sega-32x",
|
||||
"segasgone": "sega-sg1000",
|
||||
"ps": "sony-playstation",
|
||||
"pce": "nec-pc-engine",
|
||||
"tg16cd": "nec-pc-engine-cd",
|
||||
"tg-cd": "nec-pc-engine-cd",
|
||||
"turbografxcd": "nec-pc-engine-cd",
|
||||
"neocd": "snk-neogeo-cd",
|
||||
"ngcd": "snk-neogeo-cd",
|
||||
"neogeocdjp": "snk-neogeo-cd",
|
||||
"supervision": "watara-supervision",
|
||||
"cplus4": "commodore-plus4",
|
||||
"cpet": "commodore-pet",
|
||||
"cpc": "amstrad-cpc",
|
||||
"to8": "thomson-to8",
|
||||
"tic": "tic80",
|
||||
"fba": "arcade",
|
||||
"hbmame": "arcade",
|
||||
"advmame": "arcade",
|
||||
"mame-advmame": "arcade",
|
||||
"mame2000": "arcade",
|
||||
"mame2003": "arcade",
|
||||
"mame2003plus": "arcade",
|
||||
"mame2010": "arcade",
|
||||
"mame-libretro": "arcade",
|
||||
"mame-mame4all": "arcade",
|
||||
"c20": "commodore-vic20",
|
||||
"segamodel3": "sega-model3",
|
||||
"pspminis": "sony-psp",
|
||||
"ndsiware": "nintendo-dsi",
|
||||
"wiiware": "nintendo-wii",
|
||||
"x16": "commanderx16",
|
||||
"zxnext": "sinclair-zx-spectrum-next",
|
||||
"vemulator": "sega-vmu",
|
||||
"ep64-128": "enterprise-64-128",
|
||||
"easyrpg": "rpgmaker",
|
||||
"ggh": "sega-gamegear",
|
||||
"gba2players": "nintendo-gba",
|
||||
"snesmsu": "nintendo-snes",
|
||||
"megadrivemsu": "sega-megadrive",
|
||||
"sgb-msu1": "nintendo-sgb",
|
||||
# Spellings profiles gave a machine the others call by another id:
|
||||
# ares's own system names, dgen and picodrive's sega-genesis beside
|
||||
# sega-megadrive, fbneo's sinclair-spectrum and snk-neogeo-pocket,
|
||||
# emux_sms's sms. muOS names its GBA folder gameboyadvance first, the
|
||||
# folder resolved to ares's game-boy-advance, and an unrecognised GBA
|
||||
# game got no file of the nintendo-gba list.
|
||||
"famicom": "nintendo-nes",
|
||||
"famicom-disk-system": "nintendo-fds",
|
||||
"super-famicom": "nintendo-snes",
|
||||
"game-boy-advance": "nintendo-gba",
|
||||
"neo-geo-pocket": "snk-ngp",
|
||||
"snk-neogeo-pocket": "snk-ngp",
|
||||
"neo-geo-pocket-color": "snk-ngpc",
|
||||
"wonderswan": "bandai-wswan",
|
||||
"wonderswan-color": "bandai-wswanc",
|
||||
"sega-genesis": "sega-megadrive",
|
||||
"genesis": "sega-megadrive",
|
||||
"sinclair-spectrum": "sinclair-zx-spectrum",
|
||||
"sms": "sega-mastersystem",
|
||||
# The platforms' one Neo Geo system: the profiles file the MVS sets,
|
||||
# which every Neo Geo core reads, under snk-neogeo-mvs.
|
||||
"snk-neogeo": "snk-neogeo-mvs",
|
||||
"neogeo": "snk-neogeo-mvs",
|
||||
}
|
||||
|
||||
|
||||
@functools.cache
|
||||
def _norm_system_id(sid: str) -> str:
|
||||
"""Normalize system ID for cross-platform matching.
|
||||
|
||||
Resolves known aliases, then strips manufacturer prefixes and separators
|
||||
so that platform-specific IDs (e.g., "xbox", "nintendo-wiiu") match
|
||||
profile IDs (e.g., "microsoft-xbox", "nintendo-wii-u").
|
||||
|
||||
A function of the string and two constant tables: a manifest run asks it
|
||||
1.7 million times for about 1,100 ids.
|
||||
"""
|
||||
s = sid.lower().replace("_", "-")
|
||||
s = SYSTEM_ALIASES.get(s, s)
|
||||
for prefix in MANUFACTURER_PREFIXES:
|
||||
if s.startswith(prefix):
|
||||
s = s[len(prefix) :]
|
||||
break
|
||||
return s.replace("-", "")
|
||||
|
||||
|
||||
def _name_key(name: str) -> str:
|
||||
"""Letters and digits only, as the installer compares names."""
|
||||
return re.sub(r"[^a-z0-9]", "", name.lower())
|
||||
|
||||
|
||||
def platform_system_names(config: dict, systems: list[str]) -> dict[str, list[str]]:
|
||||
"""Per platform system, the names the platform's own file gives it.
|
||||
|
||||
A Batocera user knows PlayStation as `psx`, the folder under roms/, and
|
||||
the platform YAML records that name as `native_system` on each file it
|
||||
transcribes. Only the platform's own entries count (`native_layer`), a
|
||||
name spelled like the system id adds nothing, and a name the platform
|
||||
gives to two systems, or that reads as another system's id, names
|
||||
neither. The install manifest's `system_names` and the `--system` of
|
||||
generate_pack and verify read this one mapping.
|
||||
"""
|
||||
native = native_layer(config) or {}
|
||||
by_name: dict[str, set[str]] = {}
|
||||
for sys_id, system in native.get("systems", {}).items():
|
||||
if sys_id not in systems:
|
||||
continue
|
||||
for entry in system.get("files", []):
|
||||
name = entry.get("native_system")
|
||||
if isinstance(name, str) and name.strip():
|
||||
by_name.setdefault(name.strip(), set()).add(sys_id)
|
||||
ids = {_name_key(sys_id) for sys_id in systems}
|
||||
out: dict[str, list[str]] = {}
|
||||
for name, owners in by_name.items():
|
||||
if len(owners) != 1 or _name_key(name) in ids:
|
||||
continue
|
||||
out.setdefault(next(iter(owners)), []).append(name)
|
||||
return {sys_id: sorted(names) for sys_id, names in sorted(out.items())}
|
||||
|
||||
|
||||
def select_systems(systems: dict, wanted: list[str]) -> dict:
|
||||
"""The systems a --system list keeps, by id or normalized id."""
|
||||
norm = {_norm_system_id(s) for s in wanted}
|
||||
return {
|
||||
sid: data for sid, data in systems.items()
|
||||
if sid in wanted or _norm_system_id(sid) in norm
|
||||
}
|
||||
|
||||
|
||||
def resolve_system_arg(
|
||||
value: str,
|
||||
systems: list[str],
|
||||
config: dict | None = None,
|
||||
listing: str = "--list-systems",
|
||||
) -> list[str]:
|
||||
"""The system ids a --system value names, or ValueError naming the rest.
|
||||
|
||||
With a platform config, the platform's own names count as well (Batocera's
|
||||
`psx` is sony-playstation), the same mapping the install manifest carries
|
||||
as `system_names`. Without one, only our ids do. A whole value that is a
|
||||
name wins over splitting it on commas: Recalbox names one system
|
||||
`msx1,msx2`. An id wins over another system's native name, and a name
|
||||
nothing else matches falls back to the normalized id (`playstation`).
|
||||
An unknown name is refused, never ignored.
|
||||
"""
|
||||
names = platform_system_names(config, systems) if config else {}
|
||||
exact: dict[str, list[str]] = {}
|
||||
by_key: dict[str, list[str]] = {}
|
||||
for sid in systems:
|
||||
exact.setdefault(sid.lower(), [sid])
|
||||
by_key.setdefault(_name_key(sid), []).append(sid)
|
||||
for sid, aliases in names.items():
|
||||
for alias in aliases:
|
||||
exact.setdefault(alias.lower(), [sid])
|
||||
if _name_key(alias) not in by_key:
|
||||
by_key[_name_key(alias)] = [sid]
|
||||
by_norm: dict[str, list[str]] = {}
|
||||
for sid in systems:
|
||||
by_norm.setdefault(_norm_system_id(sid), []).append(sid)
|
||||
|
||||
value = value.strip()
|
||||
tokens = [value] if value.lower() in exact else value.split(",")
|
||||
chosen: list[str] = []
|
||||
unknown: list[str] = []
|
||||
for token in (t.strip() for t in tokens):
|
||||
if not token:
|
||||
continue
|
||||
keyed = by_key.get(_name_key(token), [])
|
||||
found = (
|
||||
exact.get(token.lower())
|
||||
or (keyed if len(keyed) == 1 else None)
|
||||
or by_norm.get(_norm_system_id(token))
|
||||
)
|
||||
if not found:
|
||||
unknown.append(token)
|
||||
continue
|
||||
chosen += [sid for sid in found if sid not in chosen]
|
||||
if unknown:
|
||||
known = sorted({*systems, *(a for v in names.values() for a in v)})
|
||||
hint = suggest_names(unknown, known, listing, listed=len(systems))
|
||||
raise ValueError(f"unknown system {', '.join(unknown)}. {hint}")
|
||||
if not chosen:
|
||||
raise ValueError("--system names no system")
|
||||
return chosen
|
||||
|
||||
|
||||
def system_index(profiles: dict) -> dict[str, tuple[str, set[str]]]:
|
||||
"""Normalized system id -> (the first spelling met, the emulators).
|
||||
|
||||
One system per normalized id, as --system selects: counted per spelling,
|
||||
nes and nintendo-nes were two systems and the README announced 550
|
||||
where --list-systems printed 513.
|
||||
"""
|
||||
index: dict[str, tuple[str, set[str]]] = {}
|
||||
for name, p in sorted(profiles.items()):
|
||||
if p.get("type") in ("alias", "launcher") or p.get("role") == "test":
|
||||
continue
|
||||
for sys_id in p.get("systems", []):
|
||||
key = _norm_system_id(sys_id)
|
||||
index.setdefault(key, (sys_id, set()))[1].add(name)
|
||||
return index
|
||||
@@ -0,0 +1,280 @@
|
||||
"""Hardware targets: the cores each target of a platform can run."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from core.cli import SourceUnreadable, suggest_names
|
||||
from model.sources import source_yaml
|
||||
|
||||
|
||||
def _target_overrides(platform_name: str, targets_dir: str) -> dict:
|
||||
overrides_file = os.path.join(targets_dir, "_overrides.yml")
|
||||
if not os.path.exists(overrides_file):
|
||||
return {}
|
||||
with open(overrides_file) as f:
|
||||
all_overrides = source_yaml(f) or {}
|
||||
return all_overrides.get(platform_name, {}).get("targets", {})
|
||||
|
||||
|
||||
def _target_alias_index(targets: dict, overrides: dict) -> dict[str, str]:
|
||||
"""Every name a target answers to, mapped to the name its file uses."""
|
||||
alias_index: dict[str, str] = {}
|
||||
for tname in targets:
|
||||
alias_index[tname] = tname
|
||||
for alias in overrides.get(tname, {}).get("aliases", []):
|
||||
alias_index[alias] = tname
|
||||
return alias_index
|
||||
|
||||
|
||||
def platform_files_target(platform: str, target: str, platforms_dir: str = "platforms") -> bool:
|
||||
"""Whether the platform's targets file knows this target, by any alias."""
|
||||
targets_dir = os.path.join(platforms_dir, "targets")
|
||||
target_file = os.path.join(targets_dir, f"{platform}.yml")
|
||||
if not os.path.exists(target_file):
|
||||
return False
|
||||
with open(target_file) as f:
|
||||
targets = (source_yaml(f) or {}).get("targets", {})
|
||||
return target in _target_alias_index(targets, _target_overrides(platform, targets_dir))
|
||||
|
||||
|
||||
def canonical_target_name(
|
||||
platforms: list[str], target: str, platforms_dir: str = "platforms"
|
||||
) -> str:
|
||||
"""The name a target is filed under, whichever alias was typed.
|
||||
|
||||
`switch`, `nx` and `nintendo-switch` named three packs of one target, and
|
||||
--verify-packs looked for a name no build had written. The typed name is
|
||||
kept when no platform knows it or when platforms file it differently.
|
||||
"""
|
||||
targets_dir = os.path.join(platforms_dir, "targets")
|
||||
found: set[str] = set()
|
||||
for platform_name in platforms:
|
||||
target_file = os.path.join(targets_dir, f"{platform_name}.yml")
|
||||
if not os.path.exists(target_file):
|
||||
continue
|
||||
with open(target_file) as f:
|
||||
targets = (source_yaml(f) or {}).get("targets", {})
|
||||
canonical = _target_alias_index(
|
||||
targets, _target_overrides(platform_name, targets_dir)
|
||||
).get(target)
|
||||
if canonical:
|
||||
found.add(canonical)
|
||||
return found.pop() if len(found) == 1 else target
|
||||
|
||||
|
||||
def truth_target_dir(
|
||||
output_dir: str, platforms: list[str], target: str, platforms_dir: str = "platforms"
|
||||
) -> str:
|
||||
"""Where a target-narrowed truth model is written and read.
|
||||
|
||||
Slugged from the name the target is filed under: `nx`, `switch` and
|
||||
`nintendo-switch` wrote three copies of one model, and a run under one
|
||||
alias left the others stale beside it. Called per platform, since two
|
||||
platforms can file one name differently (Lakka builds an image named
|
||||
switch). generate_truth writes here and diff_truth reads here.
|
||||
"""
|
||||
named = canonical_target_name(platforms, target, platforms_dir)
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", named.strip().lower()).strip("-")
|
||||
return os.path.join(output_dir, slug or "target")
|
||||
|
||||
|
||||
def load_target_config(
|
||||
platform_name: str,
|
||||
target: str,
|
||||
platforms_dir: str = "platforms",
|
||||
) -> set[str] | None:
|
||||
"""Load target config and return the set of core names for the given target.
|
||||
|
||||
Resolves aliases from _overrides.yml, applies add_cores/remove_cores.
|
||||
A target whose cores are null runs every core the platform declares and
|
||||
returns None, which filters nothing: the platforms with a single target
|
||||
(RetroBat on Windows, RetroDECK, RomM in the browser) kept a hand list
|
||||
that dropped 98 RetroBat cores and 300 RetroDECK ones.
|
||||
Raises ValueError if target is unknown (with list of available targets).
|
||||
Raises FileNotFoundError if no target file exists for the platform.
|
||||
"""
|
||||
targets_dir = os.path.join(platforms_dir, "targets")
|
||||
target_file = os.path.join(targets_dir, f"{platform_name}.yml")
|
||||
if not os.path.exists(target_file):
|
||||
# The expected state for a platform that ships one build, said as
|
||||
# such: the file path read like a file missing from the repository.
|
||||
with_targets = sorted(
|
||||
Path(f).stem for f in os.listdir(targets_dir)
|
||||
if f.endswith(".yml") and not f.startswith("_")
|
||||
)
|
||||
raise FileNotFoundError(
|
||||
f"{platform_name} has no hardware targets: drop --target "
|
||||
f"(platforms with targets: {', '.join(with_targets)})"
|
||||
)
|
||||
with open(target_file) as f:
|
||||
data = source_yaml(f) or {}
|
||||
|
||||
targets = data.get("targets", {})
|
||||
overrides = _target_overrides(platform_name, targets_dir)
|
||||
alias_index = _target_alias_index(targets, overrides)
|
||||
|
||||
canonical = alias_index.get(target)
|
||||
if canonical is None:
|
||||
# A typo got the 30 targets and 18 aliases in two lines to read
|
||||
# through, where a platform or emulator name gets the closest ones.
|
||||
raise ValueError(
|
||||
f"Unknown target '{target}' for platform '{platform_name}'.\n"
|
||||
# Named as a full command: cross_reference.py and slots.py take
|
||||
# --target but have no --list-targets of their own.
|
||||
+ suggest_names(
|
||||
[target], sorted(alias_index),
|
||||
f"python scripts/verify.py --platform {platform_name} --list-targets", len(targets),
|
||||
)
|
||||
)
|
||||
|
||||
return _target_core_set(targets[canonical] or {}, overrides, canonical, platforms_dir)
|
||||
|
||||
|
||||
def _target_core_set(
|
||||
entry: dict, overrides: dict, target: str, platforms_dir: str
|
||||
) -> set[str] | None:
|
||||
"""A target's cores: what the board builds, overrides applied, and the
|
||||
buildbot cores its RetroArch core downloader installs (`downloads`, a
|
||||
RetroArch targets entry), which a Batocera x86_64 or armv7 board can
|
||||
fetch from its menu."""
|
||||
declared = entry.get("cores")
|
||||
if declared is None:
|
||||
return None
|
||||
cores = apply_target_overrides({str(c) for c in declared}, overrides, target)
|
||||
downloads = entry.get("downloads")
|
||||
if downloads:
|
||||
cores |= load_target_config("retroarch", str(downloads), platforms_dir) or set()
|
||||
return cores
|
||||
|
||||
|
||||
def apply_target_overrides(
|
||||
cores: set[str], overrides: dict, target: str
|
||||
) -> set[str]:
|
||||
"""Cores of one target once the platform's overrides are applied.
|
||||
|
||||
``_default`` applies to every target of the platform, then the target's
|
||||
own entry: a name the scraper reads as a core on every board (a machine
|
||||
variant, a launcher) is written once instead of once per board.
|
||||
"""
|
||||
result = set(cores)
|
||||
for scope in ("_default", target):
|
||||
entry = overrides.get(scope) or {}
|
||||
result |= {str(c) for c in entry.get("add_cores") or []}
|
||||
result -= {str(c) for c in entry.get("remove_cores") or []}
|
||||
return result
|
||||
|
||||
|
||||
def list_available_targets(
|
||||
platform_name: str,
|
||||
platforms_dir: str = "platforms",
|
||||
) -> list[dict]:
|
||||
"""List available targets for a platform with their aliases.
|
||||
|
||||
Returns list of dicts with keys: name, architecture, core_count, aliases.
|
||||
Returns empty list if no target file exists.
|
||||
"""
|
||||
targets_dir = os.path.join(platforms_dir, "targets")
|
||||
target_file = os.path.join(targets_dir, f"{platform_name}.yml")
|
||||
if not os.path.exists(target_file):
|
||||
return []
|
||||
with open(target_file) as f:
|
||||
data = source_yaml(f) or {}
|
||||
|
||||
# The count --target filters on: overrides applied, as load_target_config
|
||||
# applies them. The scraped list counted Batocera's machine variants and
|
||||
# launchers, 198 cores shown for 187 used.
|
||||
overrides = _target_overrides(platform_name, targets_dir)
|
||||
|
||||
result = []
|
||||
for tname, tdata in sorted(data.get("targets", {}).items()):
|
||||
aliases = (overrides.get(tname) or {}).get("aliases", [])
|
||||
# None: the target runs every core the platform declares.
|
||||
found = _target_core_set(tdata or {}, overrides, tname, platforms_dir)
|
||||
count = None if found is None else len(found)
|
||||
result.append(
|
||||
{
|
||||
"name": tname,
|
||||
"architecture": (tdata or {}).get("architecture", ""),
|
||||
"core_count": count,
|
||||
"aliases": aliases,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def target_listing_line(row: dict) -> str:
|
||||
"""One --list-targets row, as verify and generate_pack print it."""
|
||||
aliases = f" (aliases: {', '.join(row['aliases'])})" if row["aliases"] else ""
|
||||
count = "all" if row["core_count"] is None else str(row["core_count"])
|
||||
return f" {row['name']:30s} {row['architecture']:10s} {count:>4s} cores{aliases}"
|
||||
|
||||
|
||||
def build_target_cores_cache(
|
||||
platforms: list[str],
|
||||
target: str,
|
||||
platforms_dir: str,
|
||||
is_all: bool = False,
|
||||
) -> tuple[dict[str, set[str] | None], list[str]]:
|
||||
"""Build target cores cache for a list of platforms.
|
||||
|
||||
Returns (cache dict, list of platforms to keep after skipping failures).
|
||||
A platform without a targets file cannot honour the target and is left
|
||||
out with the others, never run unfiltered, and a target no platform knows
|
||||
is refused: `--all --target swtich` checked BizHawk and MiSTer whole and
|
||||
exited 0, a green run that said nothing about the Switch.
|
||||
"""
|
||||
cache: dict[str, set[str] | None] = {}
|
||||
skip: list[str] = []
|
||||
notes: list[str] = []
|
||||
for p in platforms:
|
||||
try:
|
||||
cache[p] = load_target_config(p, target, platforms_dir)
|
||||
except FileNotFoundError:
|
||||
if not is_all:
|
||||
raise
|
||||
notes.append(f"INFO: Skipping {p}: no hardware targets")
|
||||
skip.append(p)
|
||||
except SourceUnreadable:
|
||||
# A damaged targets file is not a platform without the target.
|
||||
raise
|
||||
except ValueError as e:
|
||||
if is_all:
|
||||
notes.append(f"INFO: Skipping {p}: {e}")
|
||||
skip.append(p)
|
||||
else:
|
||||
raise
|
||||
kept = [p for p in platforms if p not in skip]
|
||||
if is_all and platforms and not kept:
|
||||
# The seventeen per-platform lines buried the one suggestion that
|
||||
# mattered: the refusal names the closest target across them all.
|
||||
raise ValueError(_unknown_target_message(target, platforms, platforms_dir))
|
||||
for note in notes:
|
||||
print(note)
|
||||
return cache, kept
|
||||
|
||||
|
||||
def _unknown_target_message(target: str, platforms: list[str], platforms_dir: str) -> str:
|
||||
"""A target no platform has, with the closest names any of them knows."""
|
||||
import difflib
|
||||
|
||||
targets_dir = os.path.join(platforms_dir, "targets")
|
||||
owners: dict[str, list[str]] = {}
|
||||
for platform in platforms:
|
||||
target_file = os.path.join(targets_dir, f"{platform}.yml")
|
||||
if not os.path.exists(target_file):
|
||||
continue
|
||||
with open(target_file) as f:
|
||||
targets = (source_yaml(f) or {}).get("targets", {})
|
||||
overrides = _target_overrides(platform, targets_dir)
|
||||
for name in _target_alias_index(targets, overrides):
|
||||
owners.setdefault(name, []).append(platform)
|
||||
message = f"unknown target '{target}': no platform has it."
|
||||
close = difflib.get_close_matches(target, sorted(owners), n=3, cutoff=0.6)
|
||||
if close:
|
||||
named = ", ".join(f"{n} ({', '.join(sorted(owners[n]))})" for n in close)
|
||||
return f"{message} Close matches: {named}."
|
||||
return (f"{message} python scripts/verify.py --platform <name> --list-targets "
|
||||
"lists the targets of one platform.")
|
||||
Reference in new issue
Block a user