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

+23 -1
View File
@@ -14,10 +14,11 @@ on:
- "scripts/archive_build.py"
- "scripts/auto_fetch.py"
- "scripts/build_port.py"
- "scripts/common.py"
- "scripts/core/artifacts.py"
- "scripts/core/cli.py"
- "scripts/core/crypto_verify.py"
- "scripts/core/deterministic_zip.py"
- "scripts/core/github.py"
- "scripts/core/hashing.py"
- "scripts/core/paths.py"
- "scripts/core/romdir.py"
@@ -34,9 +35,19 @@ on:
- "scripts/manifestselect.py"
- "scripts/measurement_records.py"
- "scripts/model/alternatives.py"
- "scripts/model/cliargs.py"
- "scripts/model/composition.py"
- "scripts/model/database.py"
- "scripts/model/declarations.py"
- "scripts/model/dumpcatalog.py"
- "scripts/model/largefiles.py"
- "scripts/model/platforms.py"
- "scripts/model/profiles.py"
- "scripts/model/registry.py"
- "scripts/model/safeparse.py"
- "scripts/model/sources.py"
- "scripts/model/systems.py"
- "scripts/model/targets.py"
- "scripts/packextras.py"
- "scripts/packpaths.py"
- "scripts/packreadme.py"
@@ -48,12 +59,23 @@ on:
- "scripts/region.py"
- "scripts/release_record.py"
- "scripts/resolve/__init__.py"
- "scripts/resolve/archives.py"
- "scripts/resolve/categories.py"
- "scripts/resolve/content.py"
- "scripts/resolve/contentlayout.py"
- "scripts/resolve/cores.py"
- "scripts/resolve/datadirs.py"
- "scripts/resolve/directories.py"
- "scripts/resolve/gamedata.py"
- "scripts/resolve/grouping.py"
- "scripts/resolve/launchers.py"
- "scripts/resolve/layout.py"
- "scripts/resolve/localfile.py"
- "scripts/resolve/nativemode.py"
- "scripts/resolve/ownership.py"
- "scripts/resolve/reconcile.py"
- "scripts/resolve/slot.py"
- "scripts/resolve/standalone.py"
- "scripts/resolve/truth.py"
- "scripts/resolve/validation.py"
- "scripts/restore_large_files.py"
+1 -1
View File
@@ -19,7 +19,7 @@ description = "BIOS collection manager for retrogaming platforms"
# install.py is the only entry point a user runs before cloning, and both
# bootstraps accept 3.8, so the floor stays where the bootstraps put it. That
# floor covers install.py and its installer/ source: the build scripts need 3.9
# (common.py, which every build script imports, checks it), and CI runs the
# (scripts/core/cli.py, which every build script imports, checks it), and CI runs the
# test suite on 3.12.
requires-python = ">=3.8"
dependencies = [
+4 -6
View File
@@ -236,11 +236,9 @@ def container_pins(platforms_dir: str, emulators_dir: str) -> dict[str, set[str]
archive md5 is the composite of its members (``zip_digest: composite``,
Bios.cpp:64-68): neither pins the container bytes.
"""
from common import (
list_registered_platforms,
load_emulator_profiles,
load_platform_config,
)
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
pins: dict[str, set[str]] = defaultdict(set)
for platform in list_registered_platforms(platforms_dir):
@@ -269,7 +267,7 @@ def recipe_index(emulators_dir: str, recipes_dir: str) -> dict[MemberList, set[s
Matching on the member list, not the archive name, credits a DAT that
knows the set under another name (``aga.zip`` is MAME's ``isa_aga``).
"""
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
from romset_recipes import collect_recipes, load_dat_recipes
index: dict[MemberList, set[str]] = defaultdict(set)
+7 -10
View File
@@ -30,15 +30,12 @@ import urllib.request
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import (
platform_arg,
require_directory,
list_registered_platforms,
load_database,
load_platform_config,
require_platform,
require_yaml,
)
from model.cliargs import platform_arg, require_platform
from core.cli import require_directory
from model.registry import list_registered_platforms
from model.database import load_database
from model.platforms import load_platform_config
from model.safeparse import require_yaml
yaml = require_yaml()
@@ -701,6 +698,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+2 -2
View File
@@ -776,7 +776,7 @@ def safe_env(names: Sequence[str] = (), add: dict[str, str] | None = None,
def token_env() -> dict[str, str]:
"""The environment of the phases that need GitHub: the push and gh."""
sys.path.insert(0, str(REPO_ROOT / "scripts"))
from common import github_token
from core.github import github_token
env = dict(os.environ)
token = github_token()
@@ -1214,6 +1214,6 @@ def main() -> int:
if __name__ == "__main__":
sys.path.insert(0, str(REPO_ROOT / "scripts"))
from common import run_cli
from core.cli import run_cli
run_cli(main)
+2 -2
View File
@@ -205,7 +205,7 @@ def main() -> int:
parser.add_argument("--json", action="store_true", help="machine-readable report")
args = parser.parse_args()
from common import load_database
from model.database import load_database
root = Path.cwd()
try:
@@ -224,6 +224,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -368,6 +368,6 @@ def main(argv: list[str] | None = None) -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+4 -6
View File
@@ -141,11 +141,9 @@ def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]:
refuses a pack whose name does not spell the platform, so a platform
outside these groups has no pack to copy, whatever its file list.
"""
from common import (
group_identical_platforms,
list_release_pack_platforms,
load_platform_config,
)
from resolve.grouping import group_identical_platforms
from model.registry import list_release_pack_platforms
from model.platforms import load_platform_config
from generate_pack import _name_part, _platform_pack_stem
platforms_dir = str(root / "platforms")
@@ -220,6 +218,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -135,6 +135,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+8 -10
View File
@@ -18,14 +18,12 @@ import argparse
import json
from pathlib import Path
from common import (
compute_hashes,
expand_directory_entries,
list_registered_platforms,
load_database,
load_emulator_profiles,
load_platform_config,
)
from core.hashing import compute_hashes
from resolve.directories import expand_directory_entries
from model.registry import list_registered_platforms
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from cross_reference import FileConsumers
@@ -119,7 +117,7 @@ def main() -> int:
parser.add_argument("--json", action="store_true", help="print the list as JSON")
parser.add_argument("--strict", action="store_true", help="exit 1 while a file is listed")
args = parser.parse_args()
from common import work_from_repo_root
from model.cliargs import work_from_repo_root
work_from_repo_root(args, parser, ["db", "emulators_dir", "platforms_dir", "install_dir"])
@@ -139,6 +137,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+2 -2
View File
@@ -992,7 +992,7 @@ class Campaign:
def local_file(self, entry: dict) -> Path | None:
"""The collection's copy of an entry, by its declared hashes or its name."""
from common import resolve_local_file
from resolve.localfile import resolve_local_file
hint = entry.get("path") if isinstance(entry.get("path"), str) else ""
# The database names files relative to the checkout it describes.
@@ -2110,6 +2110,6 @@ def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], path
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -2
View File
@@ -23,7 +23,8 @@ import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from common import InputMissing, yaml_load
from core.cli import InputMissing
from model.safeparse import yaml_load
log = logging.getLogger(__name__)
@@ -229,6 +230,6 @@ def unanswered(report: dict) -> list[dict]:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+8 -14
View File
@@ -53,18 +53,12 @@ import export_native
import pin_installer
import refresh_data_dirs
import upstream
from common import (
InputMissing,
apply_target_overrides,
list_registered_platforms,
load_emulator_profiles,
load_platform_registry,
require_directory,
suggest_names,
upstream_profile_index,
write_text_atomic,
yaml_load,
)
from core.cli import InputMissing, require_directory, suggest_names
from model.targets import apply_target_overrides
from model.registry import list_registered_platforms, load_platform_registry
from model.profiles import load_emulator_profiles, upstream_profile_index
from core.artifacts import write_text_atomic
from model.safeparse import yaml_load
from exporter import discover_exporters
from resolve.reconcile import build_native_model
from scripts.scraper import game_dat_importer
@@ -709,7 +703,7 @@ def check_targets(
def _declared_cores(platform: str) -> list[str]:
"""The cores and standalone emulators a platform's own file names."""
from common import load_platform_config
from model.platforms import load_platform_config
try:
config = load_platform_config(platform, str(REPO_ROOT / "platforms"))
@@ -1958,6 +1952,6 @@ def unknown_areas_message(unknown: list[str]) -> str:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -2
View File
@@ -32,7 +32,8 @@ from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from check_release_assets import digests_of
from common import list_release_pack_platforms, require_directory
from model.registry import list_release_pack_platforms
from core.cli import require_directory
from model.largefiles import LARGE_FILES_REPO
from release_record import RECORD, load_record
@@ -240,6 +241,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+5 -4
View File
@@ -25,7 +25,8 @@ from collections.abc import Iterable
from typing import NamedTuple
sys.path.insert(0, os.path.dirname(__file__))
from common import composition_tier, load_database
from model.composition import composition_tier
from model.database import load_database
from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths
@@ -250,7 +251,7 @@ def render_notes(
def profile_descriptions(emulators_dir: str = "emulators") -> dict[str, str]:
"""Name -> description, from the first profile that declares the file."""
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
found: dict[str, str] = {}
for profile in load_emulator_profiles(emulators_dir).values():
@@ -263,7 +264,7 @@ def profile_descriptions(emulators_dir: str = "emulators") -> dict[str, str]:
def registry_bundles(registry_path: str = "platforms/_data_dirs.yml") -> dict[str, str]:
"""Asset name -> description for data directories served from the release."""
from common import yaml_load
from model.safeparse import yaml_load
with open(registry_path, encoding="utf-8") as handle:
registry = yaml_load(handle) or {}
@@ -390,6 +391,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -247,6 +247,6 @@ def main() -> int:
if __name__ == "__main__":
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import run_cli
from core.cli import run_cli
run_cli(main)
-5297
View File
File diff suppressed because it is too large. Load diff
+112
View File
@@ -0,0 +1,112 @@
"""Running a command-line entry point: exit status, signals, input errors, name hints."""
from __future__ import annotations
import os
import signal
import sys
from collections.abc import Callable
from pathlib import Path
from core.artifacts import ArtifactDirectoryMissing, ArtifactLockBusy
# Every build script imports this module. verify.py, slots.py, validate_pr.py
# and cross_reference.py started under 3.8 and stopped halfway on a
# str.removeprefix AttributeError, which named no version.
if sys.version_info < (3, 9):
sys.exit(
f"{Path(sys.argv[0]).name} needs Python 3.9 or newer, "
f"this is {sys.version.split()[0]}"
)
def require_directory(path: str, flag: str = "--bios-dir") -> None:
"""Stop on a folder that does not exist.
identity --strict, dedup, auto_fetch, romset_recipes and generate_pack
read a mistyped --bios-dir as an empty collection and passed: 0
conflicts, 0 duplicates, a pack of nothing.
"""
if not os.path.isdir(path):
raise SystemExit(f"ERROR: {flag} {path} is not a directory")
class InputMissing(FileNotFoundError):
"""An input a command was pointed at does not exist. run_cli prints the
message on one line instead of a stack trace."""
class SourceUnreadable(ValueError):
"""A profile or platform file that is not valid YAML. Not an InputMissing:
the callers that skip a platform whose file is absent must not skip one
whose file is damaged. run_cli prints the message on one line."""
# A list this short is printed whole rather than pointed at.
SHORT_LIST = 12
def suggest_names(
typed: list[str],
available: list[str],
listing_flag: str,
listed: int | None = None,
) -> str:
"""The closest known names to what was typed, and how to see them all.
The hints showed the first ten or twenty names of the alphabet behind a
"..." whatever was typed: sony-playstaton listed 3do to apple-iie.
`listed` is how many entries the listing shows when `available` also
holds aliases of them.
"""
import difflib
total = len(available) if listed is None else listed
close = sorted({m for name in typed
for m in difflib.get_close_matches(name, available, n=3, cutoff=0.6)})
if close:
return f"Close matches: {', '.join(close)}. {listing_flag} lists all {total}."
if len(available) <= SHORT_LIST:
return f"Known: {', '.join(available)}."
return f"{listing_flag} lists all {total}."
def _exit_on_signal(signum: int, _frame: object) -> None:
sys.exit(128 + signum)
def run_cli(main: Callable[[], int | None]) -> None:
"""Run a command-line entry point to its exit status.
A reader that stops early (`verify.py --all | head`) closed the pipe
and the next write died on a BrokenPipeError traceback. Output nobody
reads any more ends the run quietly, with the status a shell gives a
writer whose reader left.
SIGTERM (timeout, kill) and SIGHUP (a closed terminal) end the process
without unwinding by default: a pack build left its multi-GB hidden
.partial behind. Raised as SystemExit, they run the cleanup a failed
write runs, and the status stays the one a shell gives the signal.
"""
for name in ("SIGTERM", "SIGHUP"):
if hasattr(signal, name):
signal.signal(getattr(signal, name), _exit_on_signal)
# Redirected, stdout is block-buffered and stderr is not: the --strict
# verdict landed on the first line of the log, before the report it
# closes. Line buffering keeps the two in the order they were written.
# A stream a caller swapped in (a test's StringIO) has nothing to set.
reconfigure = getattr(sys.stdout, "reconfigure", None)
if reconfigure is not None:
reconfigure(line_buffering=True)
try:
code = main()
sys.stdout.flush()
except (InputMissing, SourceUnreadable, ArtifactLockBusy,
ArtifactDirectoryMissing) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)
except BrokenPipeError:
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
sys.exit(141)
sys.exit(code)
+49
View File
@@ -0,0 +1,49 @@
"""The token a run uses for the GitHub API."""
from __future__ import annotations
import functools
import os
@functools.lru_cache(maxsize=1)
def _gh_cli_token() -> str:
"""What `gh auth token` prints, or "" when gh is absent or logged out."""
import logging
import subprocess
log = logging.getLogger(__name__)
try:
proc = subprocess.run(
["gh", "auth", "token"], capture_output=True, text=True,
timeout=10, check=False,
)
except FileNotFoundError:
log.debug("gh is not installed, GitHub API calls go anonymous")
return ""
except (subprocess.TimeoutExpired, OSError) as exc:
log.warning("gh auth token did not answer: %s", exc)
return ""
if proc.returncode != 0:
log.debug("gh auth token: %s", (proc.stderr or "").strip())
return ""
return (proc.stdout or "").strip()
def github_token() -> str:
"""The token for api.github.com: GITHUB_TOKEN, GH_TOKEN, then gh's own.
A maintainer logged in to gh had to export GITHUB_TOKEN by hand before
profile_sync, the scrapers or an online pipeline, which refused the run
or burnt the anonymous quota of 60 calls an hour. The token gh returns
is put in the environment, so the subprocesses a run starts and the
readers of os.environ get it too. RETROBIOS_OFFLINE runs make no API
call and never ask gh.
"""
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or ""
if token or os.environ.get("RETROBIOS_OFFLINE"):
return token
token = _gh_cli_token()
if token:
os.environ["GITHUB_TOKEN"] = token
return token
+12
View File
@@ -4,5 +4,17 @@ from __future__ import annotations
from pathlib import Path
# The repository: scripts/core/ is two levels below it.
REPO_ROOT = Path(__file__).resolve().parents[2]
def sanitize_pack_path(raw: str) -> str:
"""Strip traversal components from a relative destination.
The builder and the coverage report key their region grouping on this
value, so they have to derive it the same way: a destination normalized on
one side only would be looked up under a key the other side never emits.
"""
raw = raw.replace("\\", "/")
return "/".join(p for p in raw.split("/") if p and p not in ("..", "."))
+3 -3
View File
@@ -41,7 +41,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import IO
# The probe tools do not import common.py, which states the 3.9 floor for the
# The probe tools do not import core/cli.py, which states the 3.9 floor for the
# other scripts. Under 3.8 they stopped on a str.removesuffix AttributeError.
if sys.version_info < (3, 9):
sys.exit(
@@ -1522,7 +1522,7 @@ def default_emulator(core_file: Path, library_name: str | None) -> str:
"""The profile whose cores: names the .so, else the library name as a slug."""
stem = core_file.name.split(".")[0].removesuffix("_libretro")
sys.path.insert(0, str(ROOT / "scripts"))
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
owners = sorted(key for key, profile in load_emulator_profiles(str(ROOT / "emulators")).items()
if stem == key or stem in (profile.get("cores") or []))
@@ -1763,6 +1763,6 @@ if __name__ == "__main__":
# repository there is: it imports nothing beside the standard library.
sys.exit(main())
sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import run_cli
from core.cli import run_cli
run_cli(main)
+23 -35
View File
@@ -27,35 +27,22 @@ from typing import TYPE_CHECKING, TypedDict
sys.path.insert(0, os.path.dirname(__file__))
from model.alternatives import set_keys, set_requirements, settle_sets
from common import (
OUTER_ROOTS,
platform_arg,
ProfileSelectionError,
_foreign_tree,
_norm_system_id,
_owner_tokens,
archive_entry,
directory_members,
expand_directory_entries,
get_mame_clone_map,
list_emulator_profiles,
list_registered_platforms,
merged_platform_declared_contents,
load_data_dir_registry,
load_database,
load_emulator_profiles,
load_platform_config,
content_fits,
name_match_size_ok,
parse_md5_list,
require_platform,
require_yaml,
resolve_local_file,
platform_layouts,
system_dir_path,
standalone_set,
select_emulator_profiles,
)
from resolve.layout import OUTER_ROOTS, system_dir_path
from model.cliargs import platform_arg, list_emulator_profiles, require_platform
from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles
from resolve.ownership import _foreign_tree, _owner_tokens
from model.systems import _norm_system_id
from resolve.archives import archive_entry
from resolve.directories import directory_members, expand_directory_entries
from model.database import get_mame_clone_map, load_database
from model.registry import list_registered_platforms, load_data_dir_registry
from model.declarations import merged_platform_declared_contents
from model.platforms import load_platform_config
from resolve.content import content_fits, name_match_size_ok
from core.hashing import parse_md5_list
from model.safeparse import require_yaml
from resolve.localfile import resolve_local_file
from resolve.standalone import platform_layouts, standalone_set
from core.hashing import parse_hash_list
from resolve.launchers import (
LauncherLayer,
@@ -131,7 +118,7 @@ def declared_names(
together: 646 entries whose exact name a platform declares were counted
undeclared, while verify and the site read one flat index.
"""
from common import merged_platform_declarations
from model.declarations import merged_platform_declarations
return merged_platform_declarations(
[
@@ -152,7 +139,7 @@ def folded_declared_slots(
RetroBat's 32X_G_BIOS.BIN is the file BlastEm opens as 32X_G_BIOS.bin,
and the exact-case name test called it undeclared.
"""
from common import platform_declarations
from model.declarations import platform_declarations
slots: set[str] = set()
for platform_name in platforms or list_registered_platforms(
@@ -1652,7 +1639,8 @@ class _PlatformScope:
def _platform_scope(
args: argparse.Namespace, parser: argparse.ArgumentParser, profiles: dict[str, dict],
) -> _PlatformScope:
from common import load_target_config, resolve_platform_cores
from model.targets import load_target_config
from resolve.cores import resolve_platform_cores
try:
target_cores = (
@@ -1717,7 +1705,7 @@ def _launcher_rows(
def main() -> None:
parser = _build_parser()
args = parser.parse_args()
from common import work_from_repo_root
from model.cliargs import work_from_repo_root
work_from_repo_root(args, parser, ["emulators_dir", "platforms_dir", "db"])
if args.list_emulators:
@@ -1770,7 +1758,7 @@ def main() -> None:
# The tree as every platform runs it: a profile some platform runs
# standalone keeps its standalone entries. Laid out as libretro only,
# eka2l1, dolphin and xenia-edge lost 133 files no platform declares.
from common import merged_standalone_set
from resolve.standalone import merged_standalone_set
standalone_cores = merged_standalone_set(
load_platform_config(name, args.platforms_dir)
@@ -1838,6 +1826,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+4 -2
View File
@@ -28,7 +28,9 @@ from collections import defaultdict
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from common import compute_hashes, require_directory, write_text_atomic
from core.hashing import compute_hashes
from core.cli import require_directory
from core.artifacts import write_text_atomic
DEFAULT_BIOS_DIR = "bios"
@@ -416,6 +418,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+6 -11
View File
@@ -16,16 +16,11 @@ import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from common import (
platform_arg,
list_registered_platforms,
load_platform_config,
native_layer,
require_platform,
require_yaml,
truth_target_dir,
yaml_load,
)
from model.cliargs import platform_arg, require_platform
from model.registry import list_registered_platforms
from model.platforms import load_platform_config, native_layer
from model.safeparse import require_yaml, yaml_load
from model.targets import truth_target_dir
from resolve.truth import diff_platform_truth
yaml = require_yaml()
@@ -273,6 +268,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -2
View File
@@ -31,7 +31,8 @@ from dataclasses import dataclass
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from common import compute_hashes, safe_extract_zip
from core.hashing import compute_hashes
from core.ziptools import safe_extract_zip
DEFAULT_API = "https://api.github.com"
REPO = "Abdess/retrobios"
@@ -416,6 +417,6 @@ To check files already in place, use: python install.py --check
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+9 -15
View File
@@ -35,20 +35,14 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from core.artifacts import file_lock, write_bytes_atomic, write_if_changed, write_text_atomic
import yaml
from common import (
InputMissing,
build_zip_contents_index,
platform_arg,
list_registered_platforms,
load_data_dir_registry,
load_database,
load_emulator_profiles,
load_platform_config,
load_platform_registry,
native_layer,
require_platform,
yaml_load,
)
from core.cli import InputMissing
from core.ziptools import build_zip_contents_index
from model.cliargs import platform_arg, require_platform
from model.registry import list_registered_platforms, load_data_dir_registry, load_platform_registry
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config, native_layer
from model.safeparse import yaml_load
from exporter import discover_exporters
from exporter.base_exporter import BaseExporter
from resolve.reconcile import (
@@ -1093,6 +1087,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -7
View File
@@ -15,13 +15,9 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from common import (
contents_members,
holds_required_members,
platform_layouts,
resolve_platform_cores,
standalone_set,
)
from resolve.archives import contents_members, holds_required_members
from resolve.standalone import platform_layouts, standalone_set
from resolve.cores import resolve_platform_cores
from resolve.reconcile import HASH_FIELDS, _hash_values
from slots import _accepted_by_all, _lists_hashes, find_collisions
from resolve.validation import opens_by_name, outside_gap_scope
+2 -1
View File
@@ -20,7 +20,8 @@ from xml.sax.saxutils import quoteattr
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from common import load_emulator_profiles, parse_untrusted_xml
from model.profiles import load_emulator_profiles
from model.safeparse import parse_untrusted_xml
from .base_exporter import BaseExporter
from resolve.reconcile import NativeFile, NativeSystem, Report, by_destination, by_name
+1 -1
View File
@@ -21,7 +21,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
from .base_exporter import BaseExporter
from resolve.reconcile import NativeFile, NativeSystem, Report, search_order
+2 -2
View File
@@ -197,7 +197,7 @@ def fetch_logos() -> None:
def fetch_icons() -> None:
from common import load_database
from model.database import load_database
from sitecollection import _group_by_manufacturer
from siterender import SYSTEM_ICON_BASE, _icon_name
@@ -242,6 +242,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+2 -2
View File
@@ -25,7 +25,7 @@ from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
import upstream
from common import require_directory, suggest_names
from core.cli import require_directory, suggest_names
from profile_sync import collect_citations, ref_role, select_views, split_source_ref
from model.safeparse import yaml_load
@@ -163,6 +163,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -127,6 +127,6 @@ def main() -> int:
if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -102,6 +102,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -3
View File
@@ -19,7 +19,7 @@ import re
from dataclasses import dataclass
from pathlib import Path
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
from region import REGIONS, normalize_declared
from model.safeparse import yaml_load
@@ -247,7 +247,7 @@ def main() -> int:
help="profiles the rules are checked against (default emulators)")
parser.add_argument("--json", action="store_true", help="print the summary as JSON")
args = parser.parse_args()
from common import work_from_repo_root
from model.cliargs import work_from_repo_root
work_from_repo_root(args, parser, ["regions", "extras", "headers", "emulators_dir"])
@@ -271,6 +271,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+9 -12
View File
@@ -21,21 +21,18 @@ from datetime import datetime, timezone
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from common import (
annotate_provenance,
compute_hashes,
DEFAULT_PROVENANCE_DIR,
list_registered_platforms,
load_provenance_snapshots,
from model.dumpcatalog import annotate_provenance, DEFAULT_PROVENANCE_DIR, load_provenance_snapshots
from core.hashing import compute_hashes
from model.registry import list_registered_platforms
from core.artifacts import (
repository_output_lock,
require_yaml,
set_plain_mode,
source_yaml_paths,
variant_base_name,
write_if_changed,
write_text_atomic,
yaml_load,
)
from model.safeparse import require_yaml, yaml_load
from model.profiles import source_yaml_paths
from resolve.localfile import variant_base_name
import retired_files
# Platform and profile aliases are read from YAML: without pyyaml the
@@ -421,7 +418,7 @@ def _preserve_large_file_entries(files: dict, db_path: str) -> int:
would send the installer to the repository for it. A fetched asset is
written back to its registered path.
"""
from common import fetch_large_file
from model.largefiles import fetch_large_file
registered = _load_gitignored_large_files()
if not registered:
@@ -874,6 +871,6 @@ def _collect_all_aliases(
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -120,6 +120,6 @@ def main(argv: list[str] | None = None) -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+4 -7
View File
@@ -43,13 +43,10 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from common import (
load_emulator_profiles,
load_platform_config,
native_layer,
repository_output_lock,
run_cli,
)
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config, native_layer
from core.artifacts import repository_output_lock
from core.cli import run_cli
from region import normalize_declared
from romfolders import (
ProfileResolver,
+1 -1
View File
@@ -698,6 +698,6 @@ def main(argv: list[str] | None = None) -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -130,6 +130,6 @@ def main(argv: list[str] | None = None) -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+60 -57
View File
@@ -39,72 +39,75 @@ from typing import TYPE_CHECKING, TypedDict
sys.path.insert(0, os.path.dirname(__file__))
from model.alternatives import core_file_spares, settle_sets, slot_set_keys
from common import resolve_platform_cores as _platform_cores
from common import (
ROMS_ROOT,
TARGET_KEY,
_core_key,
content_folder_boards,
OUTER_ROOTS,
outer_layout,
from resolve.cores import resolve_platform_cores as _platform_cores
from resolve.layout import ROMS_ROOT, OUTER_ROOTS, outer_layout, core_system_dirs
from resolve.contentlayout import TARGET_KEY, _core_key, content_folder_boards
from model.profiles import (
installed_data_refs,
platform_arg,
require_directory,
target_listing_line,
suggest_names,
system_index,
require_platform,
load_target_config,
archive_entry,
profiles_for_systems,
load_emulator_profiles,
ProfileSelectionError,
entry_serves_systems,
entry_system_ids,
select_emulator_profiles,
upstream_profile_index,
)
from model.cliargs import (
platform_arg,
require_platform,
list_emulator_profiles,
list_platform_system_ids,
print_platform_listing,
list_system_ids,
)
from core.cli import require_directory, suggest_names
from model.targets import (
target_listing_line,
load_target_config,
build_target_cores_cache,
canonical_target_name,
platform_files_target,
list_available_targets,
)
from model.systems import (
system_index,
platform_system_names,
resolve_system_arg,
select_systems,
MANUFACTURER_PREFIXES,
_norm_system_id,
)
from resolve.archives import archive_entry, archive_is_optional
from core.artifacts import (
write_text_atomic,
archive_is_optional,
artifact_lock,
repository_output_lock,
ArtifactLockBusy,
build_target_cores_cache,
build_zip_contents_index,
compute_hashes,
expand_directory_entries,
)
from core.ziptools import build_zip_contents_index
from core.hashing import compute_hashes
from resolve.directories import expand_directory_entries
from resolve.cores import (
filter_systems_by_target,
group_identical_platforms,
list_emulator_profiles,
list_platform_system_ids,
platform_system_names,
resolve_system_arg,
print_platform_listing,
select_systems,
platform_scope_systems,
system_scope_error,
canonical_target_name,
platform_files_target,
list_registered_platforms,
list_release_pack_platforms,
list_system_ids,
load_data_dir_registry,
load_database,
load_emulator_profiles,
load_platform_config,
without_profile_blind,
MANUFACTURER_PREFIXES,
_norm_system_id,
require_yaml,
ProfileSelectionError,
core_system_dirs,
declared_root,
downloadable_on,
downloaded_only_profiles,
list_available_targets,
entry_serves_systems,
entry_system_ids,
platform_layouts,
sanitize_pack_path,
select_emulator_profiles,
standalone_set,
system_core_reach,
upstream_profile_index,
yaml_load,
)
from resolve.grouping import group_identical_platforms
from model.registry import (
list_registered_platforms,
list_release_pack_platforms,
load_data_dir_registry,
)
from model.database import load_database
from model.platforms import load_platform_config
from model.safeparse import require_yaml, yaml_load
from model.declarations import declared_root
from resolve.standalone import platform_layouts, standalone_set
from core.paths import sanitize_pack_path
import packresolve
from refresh_data_dirs import cache_lock, hold_data_dirs
import region as region_mod
@@ -511,7 +514,7 @@ def pack_markers(
) -> tuple[str, ...]:
"""The empty files a pack carries for the systems it is unzipped on,
as named before flattening: the .nomedia of a pack for Android."""
from common import list_available_targets
from model.targets import list_available_targets
names = [t["name"] for t in list_available_targets(platform_name, platforms_dir)]
return (MEDIA_MARKER,) if lands_on_android(names, target_name) else ()
@@ -1118,7 +1121,7 @@ def _plan_platform_pack(
# Build emulator-level validation index from the platform's own
# emulators (same scope as verify.py)
from common import resolve_platform_cores
from resolve.cores import resolve_platform_cores
validation_index = {}
platform_profiles: dict[str, dict] = {}
@@ -2571,7 +2574,7 @@ def _group_systems_by_manufacturer(
bios_dir: str,
) -> dict[str, list[str]]:
"""Group system IDs by manufacturer for --split --group-by manufacturer."""
from common import derive_manufacturer
from model.systems import derive_manufacturer
groups: dict[str, list[str]] = {}
for sid, sys_data in systems.items():
@@ -4177,7 +4180,7 @@ def _run_quick_mode(
if args.list_targets:
if not args.platform:
parser.error("--list-targets requires --platform")
from common import list_available_targets
from model.targets import list_available_targets
targets = list_available_targets(args.platform, args.platforms_dir)
if not targets:
@@ -6903,6 +6906,6 @@ def verify_and_finalize_packs(
return all_ok
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+14 -20
View File
@@ -21,23 +21,17 @@ from pathlib import Path
from types import ModuleType
sys.path.insert(0, os.path.dirname(__file__))
from common import (
InputMissing,
compute_composition,
count_catalog_matched,
declared_root,
github_token,
list_registered_platforms,
load_database,
load_emulator_profiles,
load_platform_config,
load_platform_registry,
repository_output_lock,
resolve_platform_cores,
system_index,
unique_emulator_profiles,
write_if_changed,
)
from core.cli import InputMissing
from model.composition import compute_composition, count_catalog_matched
from model.declarations import declared_root
from core.github import github_token
from model.registry import list_registered_platforms, load_platform_registry
from model.database import load_database
from model.profiles import load_emulator_profiles, unique_emulator_profiles
from model.platforms import load_platform_config
from core.artifacts import repository_output_lock, write_if_changed
from resolve.cores import resolve_platform_cores
from model.systems import system_index
import archive_build
import release_record
from siteguides import PACKAGE_COMMAND, install_command
@@ -607,7 +601,7 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json"
platform_names = list_registered_platforms(platforms_dir)
from common import load_data_dir_registry
from model.registry import load_data_dir_registry
data_registry = load_data_dir_registry(platforms_dir)
@@ -994,7 +988,7 @@ def main() -> None:
import contextlib
from common import load_data_dir_registry
from model.registry import load_data_dir_registry
from refresh_data_dirs import hold_data_dirs
db = load_database(args.db)
@@ -1021,6 +1015,6 @@ def _write(readme: str) -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -85,6 +85,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+32 -33
View File
@@ -45,32 +45,28 @@ from sitecollection import (
_copy_places, _group_by_manufacturer, _profiles_in,
_profiles_on_disk, _slug, collection_paths,
)
from common import (
BUCKET_FOLDERS,
names_manufacturer,
from resolve.ownership import BUCKET_FOLDERS, names_manufacturer
from model.profiles import (
upstream_profile_index,
build_zip_contents_index,
GAME_DATA_TOPS,
compute_composition,
count_catalog_matched,
entry_system_ids,
load_emulator_profiles,
unique_emulator_profiles,
)
from core.ziptools import build_zip_contents_index
from model.composition import GAME_DATA_TOPS, compute_composition, count_catalog_matched
from model.registry import (
list_registered_platforms,
list_release_pack_platforms,
load_platform_registry,
load_database,
load_emulator_profiles,
load_platform_config,
load_provenance_snapshots,
native_layer,
require_directory,
require_yaml,
resolution_is_hash_exact,
resolve_local_file,
resolve_platform_cores,
runs_standalone,
unique_emulator_profiles,
yaml_load,
)
from model.database import load_database
from model.platforms import load_platform_config, native_layer
from model.dumpcatalog import load_provenance_snapshots
from core.cli import require_directory
from model.safeparse import require_yaml, yaml_load
from resolve.localfile import resolution_is_hash_exact, resolve_local_file
from resolve.cores import resolve_platform_cores
from resolve.layout import runs_standalone
from siterender import SECTION_LABELS, WIKI_SRC_DIR
from core.artifacts import ArtifactLockBusy, artifact_lock
from core.artifacts import json_text as _json_text
@@ -314,7 +310,7 @@ def _folders_by_name(manufacturers: dict) -> dict[str, set[tuple[str, str]]]:
nintendo-nes, nes and the NES folder normalize alike, as do
sega-mastersystem and Sega/Master System.
"""
from common import _norm_system_id
from model.systems import _norm_system_id
index: dict[str, set[tuple[str, str]]] = {}
for mfr, consoles in manufacturers.items():
@@ -328,7 +324,7 @@ def _folders_by_name(manufacturers: dict) -> dict[str, set[tuple[str, str]]]:
def _folder_named(sys_id: str, by_name: dict[str, set[tuple[str, str]]]) -> tuple[str, str] | None:
from common import _norm_system_id
from model.systems import _norm_system_id
places = by_name.get(_norm_system_id(sys_id), set())
return next(iter(places)) if len(places) == 1 else None
@@ -1233,7 +1229,8 @@ def build_emulator_gap_report(
The gap analysis page and the published gaps export must not compute this
twice and drift. Both read this one report.
"""
from common import _norm_system_id, merged_platform_declarations
from model.systems import _norm_system_id
from model.declarations import merged_platform_declarations
from cross_reference import cross_reference as run_cross_reference
# Enriched with alias resolution, with each declaration's size and slot:
@@ -1255,7 +1252,8 @@ def build_emulator_gap_report(
for k, v in profiles.items()
if v.get("type") != "alias" and v.get("role") != "test"
}
from common import merged_standalone_set, platform_declarations
from resolve.standalone import merged_standalone_set
from model.declarations import platform_declarations
from resolve.validation import case_folded_slots
# The command line passes these too: without them a RetroBat file named
@@ -1378,7 +1376,7 @@ def _profile_categories(profile: dict) -> dict[tuple[str, str], str]:
def _cross_reference_export_rows(coverages: dict, profiles: dict) -> list[dict]:
from common import resolve_platform_cores
from resolve.cores import resolve_platform_cores
unique = {
key: value
@@ -2061,7 +2059,7 @@ def core_index_items(profiles: dict) -> list[dict]:
included, said once. A name two profiles claim (pcsx2) lists both, the
one a platform list designates first.
"""
from common import preferred_profile, upstream_profile_index
from model.profiles import preferred_profile, upstream_profile_index
published = {name for name, p in profiles.items() if p.get("type") != "alias" and p.get("role") != "test"}
index = upstream_profile_index(profiles)
@@ -5169,7 +5167,7 @@ def _data_member_digests(
whose copy in the tree's local cache has the sha1 the manifest records.
The manifests carry sha1 alone: the MD5 of Dolphin's ApprovedInis.json
found nothing although the pack ships it."""
from common import load_data_dir_registry
from model.registry import load_data_dir_registry
from core.hashing import compute_hashes
if data_registry is None:
@@ -11393,7 +11391,7 @@ def reading_platforms(emu_name: str, profile: dict, name: str,
"""Of the platforms running an emulator (name -> config), those whose
build of it reads the entry: BlastEm's cdbios.bin is read by the
standalone build only, and RetroBat hands that build other names."""
from common import platform_layouts, standalone_set
from resolve.standalone import platform_layouts, standalone_set
from resolve.validation import filter_files_by_mode, unread_on
return {
@@ -12457,7 +12455,7 @@ def _build_emulator_file_index(profiles: dict) -> dict[str, dict]:
the Mega Drive as sega-mega-drive and genesis_plus_gx as sega-megadrive,
and an exact match left the RetroArch page with no emulator for it.
"""
from common import _norm_system_id
from model.systems import _norm_system_id
return {
name: {
@@ -12496,7 +12494,7 @@ def _system_emulators(
an archive does not count: fbneo's boot.bin is read inside bubsys.zip,
and RomM's Dreamcast boot.bin is not that file.
"""
from common import _norm_system_id
from model.systems import _norm_system_id
norm = _norm_system_id(sys_id)
by_id = [name for name, data in (emulator_files or {}).items()
@@ -13044,7 +13042,8 @@ def main() -> None:
# files in the sweep, so the second is refused instead.
import contextlib
from common import load_data_dir_registry, repository_output_lock
from model.registry import load_data_dir_registry
from core.artifacts import repository_output_lock
from refresh_data_dirs import hold_data_dirs
# The coverage pages resolve against data/, held while they are read.
@@ -13131,7 +13130,7 @@ class _SiteRun:
def _load_site_run(args: argparse.Namespace, db: dict, docs: Path, public: Path) -> _SiteRun:
"""The registry, the coverage of every platform and the profiles."""
from common import load_data_dir_registry
from model.registry import load_data_dir_registry
from cross_reference import _build_supplemental_index
registry = _load_registry(args.platforms_dir)
@@ -13624,6 +13623,6 @@ def _generate(args: argparse.Namespace) -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+10 -16
View File
@@ -13,21 +13,15 @@ import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from common import (
build_target_cores_cache,
platform_arg,
list_registered_platforms,
load_data_dir_registry,
load_database,
load_emulator_profiles,
load_platform_config,
require_directory,
require_platform,
require_yaml,
truth_target_dir,
write_text_atomic,
yaml_load,
)
from model.targets import build_target_cores_cache, truth_target_dir
from model.cliargs import platform_arg, require_platform
from model.registry import list_registered_platforms, load_data_dir_registry
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from core.cli import require_directory
from model.safeparse import require_yaml, yaml_load
from core.artifacts import write_text_atomic
from resolve.truth import generate_platform_truth
yaml = require_yaml()
@@ -165,6 +159,6 @@ def main(argv: list[str] | None = None) -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -3
View File
@@ -132,10 +132,10 @@ def main() -> int:
"--strict", action="store_true", help="exit non-zero when any is found"
)
args = parser.parse_args()
from common import work_from_repo_root
from model.cliargs import work_from_repo_root
work_from_repo_root(args, parser, ["bios_dir"])
from common import require_directory
from core.cli import require_directory
require_directory(args.bios_dir)
@@ -166,6 +166,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -81,6 +81,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -3
View File
@@ -14,7 +14,7 @@ import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from common import list_registered_platforms
from model.registry import list_registered_platforms
PLATFORMS_DIR = "platforms"
@@ -27,7 +27,7 @@ def list_platforms() -> list[str]:
def main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False, description="List available platforms")
args = parser.parse_args()
from common import work_from_repo_root
from model.cliargs import work_from_repo_root
work_from_repo_root(args, parser, [])
@@ -46,6 +46,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -516,6 +516,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+5 -3
View File
@@ -25,7 +25,8 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from common import list_registered_platforms, load_platform_config
from model.registry import list_registered_platforms
from model.platforms import load_platform_config
from sitediagrams import OG_SECTIONS, og_card_svg, wrap
ROOT = Path(__file__).resolve().parent.parent
@@ -70,7 +71,8 @@ def system_cards() -> dict[str, tuple[str, str]]:
"""Each manufacturer page's card under og/systems/, titled with the
manufacturer and listing its consoles. Read from the same grouping the
system pages are written from."""
from common import GAME_DATA_TOPS, load_database
from model.composition import GAME_DATA_TOPS
from model.database import load_database
from sitecollection import _group_by_manufacturer, _slug
def lead(manufacturer: str) -> str:
@@ -133,6 +135,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -191,6 +191,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+2 -2
View File
@@ -27,7 +27,7 @@ from dataclasses import dataclass
sys.path.insert(0, os.path.dirname(__file__))
import upstream
from common import require_directory
from core.cli import require_directory
from model.safeparse import yaml_load
from scraper.mame_parser import _MACHINE_MACROS, strip_comments
@@ -173,6 +173,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+2 -1
View File
@@ -19,7 +19,8 @@ from dataclasses import dataclass
import region as region_mod
from resolve import slot as slot_mod
from common import _norm_system_id, sanitize_pack_path
from model.systems import _norm_system_id
from core.paths import sanitize_pack_path
from packextras import (
_kept,
_serving_system_ids,
+2 -2
View File
@@ -20,7 +20,7 @@ import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from common import compute_hashes
from core.hashing import compute_hashes
SYSTEM_MAP = {
"3DO Company, The - 3DO": ("3DO Company", "3DO"),
@@ -553,6 +553,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+140
View File
@@ -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())
+74
View File
@@ -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"
)
+78
View File
@@ -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
+145
View File
@@ -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))
+1 -1
View File
@@ -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:
+258
View File
@@ -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}
+297
View File
@@ -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]
+69
View File
@@ -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
]
+34
View File
@@ -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
+340
View File
@@ -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
+280
View File
@@ -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.")
+8 -11
View File
@@ -62,17 +62,14 @@ import autorun
import campaign
import measurement_records as mr
from autorun import now_iso
from common import (
_norm_system_id,
load_emulator_profiles,
load_platform_config,
load_target_config,
platform_arg,
require_platform,
resolve_platform_cores,
run_cli,
runs_standalone,
)
from model.systems import _norm_system_id
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from model.targets import load_target_config
from model.cliargs import platform_arg, require_platform
from resolve.cores import resolve_platform_cores
from core.cli import run_cli
from resolve.layout import runs_standalone
from resolve.validation import filter_files_by_mode
from core.ziptools import safe_extract_zip
+17 -14
View File
@@ -10,18 +10,21 @@ from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from common import PROFILE_IDENTITY_FIELDS, _norm_system_id, entry_system_ids
from model.profiles import PROFILE_IDENTITY_FIELDS, entry_system_ids
from model.systems import _norm_system_id
from model.alternatives import core_file_spares, required_only_spares, set_fields
from common import archive_members, contents_members, holds_required_members
from common import declared_root, expand_platform_declared_names, platform_declarations
from common import load_emulator_profiles
from common import resolution_is_hash_exact
from common import resolve_local_file
from common import resolve_platform_cores
from common import core_system_dirs, platform_layouts, system_dir_path
from common import standalone_set as platform_standalone_set
from common import OUTER_ROOTS, outer_layout, sanitize_pack_path
from common import declares_shape, shape_fits, size_fits
from resolve.archives import archive_members, contents_members, holds_required_members
from model.declarations import declared_root, expand_platform_declared_names, platform_declarations
from model.profiles import load_emulator_profiles
from resolve.localfile import resolution_is_hash_exact
from resolve.localfile import resolve_local_file
from resolve.cores import resolve_platform_cores
from resolve.layout import core_system_dirs, system_dir_path
from resolve.standalone import platform_layouts
from resolve.standalone import standalone_set as platform_standalone_set
from resolve.layout import OUTER_ROOTS, outer_layout
from core.paths import sanitize_pack_path
from resolve.content import declares_shape, shape_fits, size_fits
from resolve.validation import deliverable, read_from_save_dir, read_from_system_dir
from packpaths import libretro_systems, save_destination, save_layout
from region import FILE_GROUP
@@ -201,7 +204,7 @@ def _map_emulator_to_slug(
sys_to_slug: dict[str, str],
) -> str:
"""Map an emulator to a destination slug for slug-based platforms."""
from common import _norm_system_id
from model.systems import _norm_system_id
emu_systems = set(profile.get("systems", []))
# Direct match
@@ -1278,7 +1281,7 @@ class ExtraPlacement:
"""
def __init__(self, config: dict, base_dest: str, profiles: dict) -> None:
from common import _norm_system_id
from model.systems import _norm_system_id
self.prefix = _detect_extras_prefix(config, base_dest)
self.slug_based, self.sys_to_slug = _detect_slug_structure(config)
@@ -2366,7 +2369,7 @@ def emulator_required_spares(
is a member like a loose file: Kronos reads kronos/stvbios.zip, else
stvbios.zip. The pack and verify --emulator both read this."""
from model.alternatives import groups_of, rank_in, required_groups
from common import archive_entry
from resolve.archives import archive_entry
from packpaths import _archive_destination, _resolve_destination
reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__)
+1 -1
View File
@@ -9,7 +9,7 @@ from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass
from common import sanitize_pack_path
from core.paths import sanitize_pack_path
from resolve.validation import read_from_save_dir
+3 -6
View File
@@ -15,12 +15,9 @@ from pathlib import Path
from model.largefiles import fetch_large_file
from core.hashing import cut_md5_owner
from common import (
declared_hash_verdict,
resolution_is_hash_exact,
resolve_local_file,
sanitize_pack_path,
)
from resolve.content import declared_hash_verdict
from resolve.localfile import resolution_is_hash_exact, resolve_local_file
from core.paths import sanitize_pack_path
from resolve.validation import inner_rom_check
# CLI-wide network policy. Public helpers can override it explicitly, while
# every CLI mode inherits --offline (including large-file release fallback).
+6 -6
View File
@@ -22,11 +22,11 @@ import functools
import hashlib
import zlib
import sys
from common import filter_systems_by_target
from resolve.cores import filter_systems_by_target
from core.hashing import md5_composite_of, parse_md5_list
import io
from common import load_emulator_profiles
from common import load_platform_config
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
import os
from packextras import platform_region_groups
from packpaths import _flat
@@ -36,8 +36,8 @@ import slots
from packresolve import resolve_declaration, resolve_file
from resolve.categories import BIOS, EntryCategories
from resolve.gamedata import without_game_data
from common import resolve_platform_cores
from common import sanitize_pack_path
from resolve.cores import resolve_platform_cores
from core.paths import sanitize_pack_path
import zipfile
from collections.abc import Callable, Mapping
@@ -442,7 +442,7 @@ def _repo_satisfies_declaration(
packed) from data coverage gaps (no repo file matches the upstream
declaration): only the former is a pack generation error.
"""
from common import md5_composite
from core.hashing import md5_composite
files_db = db.get("files", {})
by_md5 = db.get("indexes", {}).get("by_md5", {})
+1 -1
View File
@@ -77,6 +77,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+25 -28
View File
@@ -69,15 +69,15 @@ if sys.version_info < (3, 9):
sys.exit(f"pipeline.py needs Python 3.9 or newer, this is {sys.version.split()[0]}")
sys.path.insert(0, str(Path(__file__).parent))
from common import (
from core.artifacts import (
ArtifactLockBusy,
artifact_lock,
github_token,
hold_artifact_lock,
hold_repository_outputs,
load_data_dir_registry,
publish_hold,
)
from core.github import github_token
from model.registry import load_data_dir_registry
from refresh_data_dirs import hold_data_dirs
from packpaths import MEDIA_MARKER
@@ -335,7 +335,8 @@ def _match_key(label: str) -> set[str]:
def release_pack_keys(platforms_dir: str = "platforms") -> set[str]:
"""Comparable identities of the platforms --all builds a pack for: their
registry ids and display names, normalized as _match_key does."""
from common import list_release_pack_platforms, load_platform_config
from model.registry import list_release_pack_platforms
from model.platforms import load_platform_config
keys: set[str] = set()
for name in list_release_pack_platforms(platforms_dir):
@@ -455,7 +456,8 @@ def _tree_members(
) -> dict[str, int]:
"""Archive path -> size of every file the platform's data trees can add."""
import generate_pack
from common import load_emulator_profiles, load_platform_config
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packpaths import _flat
config = load_platform_config(platform, platforms_dir)
@@ -579,15 +581,15 @@ def check_emulator_packs(
import generate_pack
import packresolve
import verify
from common import (
from model.profiles import (
ProfileSelectionError,
_norm_system_id,
build_zip_contents_index,
load_database,
load_emulator_profiles,
profiles_for_systems,
select_emulator_profiles,
)
from model.systems import _norm_system_id
from core.ziptools import build_zip_contents_index
from model.database import load_database
print(f"\n--- {step_title(STEP_LABELS['consistency'])}, emulator packs ---")
db = load_database(db_path)
@@ -700,7 +702,7 @@ def narrowed_variants(
*full*, regions, targets and systems are sampled (_matrix_coverage).
"""
import region as region_mod
from common import list_available_targets
from model.targets import list_available_targets
regions = sorted({
r for entry in region_mod.platform_region_index(config, profiles).values()
@@ -751,15 +753,13 @@ def check_narrowed_packs(
import generate_pack
import packresolve
import verify
from common import (
build_zip_contents_index,
group_identical_platforms,
list_registered_platforms,
load_database,
load_emulator_profiles,
load_platform_config,
load_target_config,
)
from core.ziptools import build_zip_contents_index
from resolve.grouping import group_identical_platforms
from model.registry import list_registered_platforms
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from model.targets import load_target_config
print(f"\n--- {step_title(STEP_LABELS['consistency'])}, narrowed packs ---")
db = load_database(db_path)
@@ -862,14 +862,11 @@ def check_split_packs(
"""
import generate_pack
import packresolve
from common import (
build_zip_contents_index,
group_identical_platforms,
list_registered_platforms,
load_data_dir_registry,
load_database,
load_emulator_profiles,
)
from core.ziptools import build_zip_contents_index
from resolve.grouping import group_identical_platforms
from model.registry import list_registered_platforms, load_data_dir_registry
from model.database import load_database
from model.profiles import load_emulator_profiles
print(f"\n--- {step_title(STEP_LABELS['consistency'])}, split packs ---")
db = load_database(db_path)
@@ -1690,6 +1687,6 @@ def _hold_outputs(args: argparse.Namespace) -> contextlib.ExitStack:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -120,6 +120,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+11 -14
View File
@@ -34,16 +34,13 @@ sys.path.insert(0, os.path.dirname(__file__))
import upstream
import version_basis
from common import (
_norm_system_id,
github_token,
list_registered_platforms,
load_emulator_profiles,
load_platform_config,
resolve_platform_cores,
suggest_names,
system_index,
)
from model.systems import _norm_system_id, system_index
from core.github import github_token
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from resolve.cores import resolve_platform_cores
from core.cli import suggest_names
from core.hashing import parse_hash_list
from sourceref import ( # re-exported for callers and tests
_ANNOTATION_RE as _ANNOTATION_RE,
@@ -5866,14 +5863,14 @@ def _refresh_source_paths(args: argparse.Namespace) -> None:
"""
if not _WRITTEN or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"):
return
import common
from model.profiles import _emulator_profiles_cache
import sitesources
from common import write_if_changed
from core.artifacts import write_if_changed
# The run loaded the profiles before writing them, and the loader caches
# by directory: read again, the record described the pins just replaced
# (linapple, then ten profiles in one advance).
common._emulator_profiles_cache.clear()
_emulator_profiles_cache.clear()
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
held, unread = sitesources.build_source_paths(
profiles, [sitesources.TREE_CACHE], fetch=True
@@ -5999,6 +5996,6 @@ def _print_elided(
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+6 -9
View File
@@ -27,13 +27,10 @@ import zipfile
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from common import (
DEFAULT_PROVENANCE_DIR,
load_database,
load_emulator_profiles,
load_provenance_snapshots,
write_if_changed,
)
from model.dumpcatalog import DEFAULT_PROVENANCE_DIR, load_provenance_snapshots
from model.database import load_database
from model.profiles import load_emulator_profiles
from core.artifacts import write_if_changed
HASH_FIELDS = ("sha1", "md5", "sha256")
@@ -406,7 +403,7 @@ def main() -> int:
"(the pipeline writes derivable.json)",
)
args = parser.parse_args()
from common import work_from_repo_root
from model.cliargs import work_from_repo_root
work_from_repo_root(args, parser, ["db", "provenance_dir", "emulators_dir", "write_derivable"])
if args.write_derivable and not args.derive:
@@ -478,6 +475,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+6 -3
View File
@@ -27,7 +27,10 @@ import zipfile
from collections.abc import Callable, Iterator
from pathlib import Path
from core.artifacts import file_lock as _file_lock, set_plain_mode
from common import InputMissing, github_token, platform_arg, require_platform, suggest_names, yaml_load
from core.cli import InputMissing, suggest_names
from core.github import github_token
from model.cliargs import platform_arg, require_platform
from model.safeparse import yaml_load
try:
import yaml
@@ -648,7 +651,7 @@ def refresh_all(
)
if any(results.values()):
# A cache the resolver indexed in this process has changed under it.
from common import forget_data_dir_index
from resolve.datadirs import forget_data_dir_index
forget_data_dir_index()
return results
@@ -725,6 +728,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+2 -2
View File
@@ -478,7 +478,7 @@ def _github_token_env() -> dict[str, str]:
emudeck and retropie target scrapers hit the GitHub API. Without a token
the unauthenticated rate limit (60/h) is burnt within a few platforms.
"""
from common import github_token
from core.github import github_token
env = os.environ.copy()
token = github_token()
@@ -716,6 +716,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+1 -1
View File
@@ -208,7 +208,7 @@ def platform_region_index(
region, so the Genesis Plus GX and PicoDrive tags never counted and
`--region us` kept both CD BIOSes in the RetroArch pack.
"""
from common import resolve_platform_cores
from resolve.cores import resolve_platform_cores
cores = resolve_platform_cores(config, profiles, target_cores=target_cores)
return build_region_index({n: profiles[n] for n in cores if n in profiles})
+5 -3
View File
@@ -19,7 +19,9 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import region
from common import load_database, load_emulator_profiles, resolve_local_file
from model.database import load_database
from model.profiles import load_emulator_profiles
from resolve.localfile import resolve_local_file
# No-Intro filename tokens: full English territory names.
NOINTRO = {
@@ -201,7 +203,7 @@ def main() -> int:
)
parser.add_argument("--json", action="store_true", help="Machine-readable output")
args = parser.parse_args()
from common import work_from_repo_root
from model.cliargs import work_from_repo_root
work_from_repo_root(args, parser, ["db", "emulators_dir"])
@@ -217,6 +219,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+6 -5
View File
@@ -36,7 +36,7 @@ import urllib.request
from collections.abc import Callable, Iterable
from pathlib import Path
# The probe tools do not import common.py, which states the 3.9 floor for the
# The probe tools do not import core/cli.py, which states the 3.9 floor for the
# other scripts. Under 3.8 they stopped on a str.removesuffix AttributeError.
if sys.version_info < (3, 9):
sys.exit(
@@ -292,7 +292,8 @@ def pack_files(emulator: str, region: str, work: Path) -> dict[str, Path]:
def local_resolver() -> Callable[[dict], Path | None]:
from common import load_database, resolve_local_file
from model.database import load_database
from resolve.localfile import resolve_local_file
db = load_database(str(ROOT / "database.json"))
@@ -328,7 +329,7 @@ def probe_when_idle(argv: list[str], max_wait: float,
def run(args: argparse.Namespace) -> int:
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
profile = load_emulator_profiles(str(ROOT / "emulators"))[args.emulator]
entries = region_entries(profile, args.system)
@@ -372,7 +373,7 @@ def collect(root: Path = ROOT, stored_records: list | None = None) -> list[dict]
"""Every region outcome the records under measurements/ hold. A game
listed under several systems (sega-megacd and mega-cd) is judged under
the one whose profile ran it."""
from common import load_emulator_profiles
from model.profiles import load_emulator_profiles
from measurement_records import live, read_records
content: dict[str, list[tuple[str, dict]]] = {}
@@ -427,6 +428,6 @@ def main(argv: list[str] | None = None) -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+5 -5
View File
@@ -34,14 +34,14 @@ from collections.abc import Callable
from pathlib import Path
import release_record
from common import (
from model.registry import (
list_registered_platforms,
list_release_pack_platforms,
load_platform_config,
load_platform_registry,
require_directory,
write_text_atomic,
)
from model.platforms import load_platform_config
from core.cli import require_directory
from core.artifacts import write_text_atomic
from siteguides import install_command
REPO = "Abdess/retrobios"
@@ -330,6 +330,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+3 -7
View File
@@ -23,12 +23,8 @@ import zipfile
from pathlib import Path
import split_pack
from common import (
ArtifactLockBusy,
artifact_lock,
list_release_pack_platforms,
write_text_atomic,
)
from core.artifacts import ArtifactLockBusy, artifact_lock, write_text_atomic
from model.registry import list_release_pack_platforms
RECORD = "release.json"
# The record's format, which release.schema.json pins: a reader holding the
@@ -245,6 +241,6 @@ def main() -> int:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
+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
+3 -2
View File
@@ -25,7 +25,8 @@ import tempfile
sys.path.insert(0, os.path.dirname(__file__))
from core.artifacts import set_plain_mode
from common import copy_file_atomic, load_database
from core.artifacts import copy_file_atomic
from model.database import load_database
def gitignored_paths(gitignore: str) -> set[str]:
@@ -153,6 +154,6 @@ def main() -> None:
if __name__ == "__main__":
from common import run_cli
from core.cli import run_cli
run_cli(main)
Loaded 100 of 281 files, more files were not shown because too many files have changed in this diff. Show more