diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index d424e55f2..0912677ea 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -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" diff --git a/pyproject.toml b/pyproject.toml index c85d808b9..d6e676902 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 = [ diff --git a/scripts/archive_build.py b/scripts/archive_build.py index 04cb2ec14..33a72922f 100644 --- a/scripts/archive_build.py +++ b/scripts/archive_build.py @@ -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) diff --git a/scripts/auto_fetch.py b/scripts/auto_fetch.py index f0b36657f..8cf9c7d44 100644 --- a/scripts/auto_fetch.py +++ b/scripts/auto_fetch.py @@ -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) diff --git a/scripts/autorun.py b/scripts/autorun.py index 537838224..573f62b20 100644 --- a/scripts/autorun.py +++ b/scripts/autorun.py @@ -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) diff --git a/scripts/bios_integrity.py b/scripts/bios_integrity.py index 91fdd4cb8..fa4f01704 100644 --- a/scripts/bios_integrity.py +++ b/scripts/bios_integrity.py @@ -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) diff --git a/scripts/build_installer.py b/scripts/build_installer.py index 6f893e297..bbf8a43ad 100644 --- a/scripts/build_installer.py +++ b/scripts/build_installer.py @@ -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) diff --git a/scripts/build_port.py b/scripts/build_port.py index 3952dc1f6..692cd12cc 100644 --- a/scripts/build_port.py +++ b/scripts/build_port.py @@ -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) diff --git a/scripts/build_pypi.py b/scripts/build_pypi.py index 61f1f0b1d..e4fc3b4a1 100644 --- a/scripts/build_pypi.py +++ b/scripts/build_pypi.py @@ -135,6 +135,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/bundled_only.py b/scripts/bundled_only.py index 46d860d6a..73961641a 100644 --- a/scripts/bundled_only.py +++ b/scripts/bundled_only.py @@ -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) diff --git a/scripts/campaign.py b/scripts/campaign.py index a6de23888..e7b12f03b 100644 --- a/scripts/campaign.py +++ b/scripts/campaign.py @@ -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) diff --git a/scripts/check_buildbot_system.py b/scripts/check_buildbot_system.py index c6bada126..a3e1a3380 100644 --- a/scripts/check_buildbot_system.py +++ b/scripts/check_buildbot_system.py @@ -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) diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index bc2a92678..c7d52beb3 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -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) diff --git a/scripts/check_release.py b/scripts/check_release.py index 15957af05..c1e7f04ca 100644 --- a/scripts/check_release.py +++ b/scripts/check_release.py @@ -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) diff --git a/scripts/check_release_assets.py b/scripts/check_release_assets.py index 8222f42b4..deb65886f 100644 --- a/scripts/check_release_assets.py +++ b/scripts/check_release_assets.py @@ -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) diff --git a/scripts/cleanup_disk.py b/scripts/cleanup_disk.py index e2afcce13..b0689d935 100644 --- a/scripts/cleanup_disk.py +++ b/scripts/cleanup_disk.py @@ -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) diff --git a/scripts/common.py b/scripts/common.py deleted file mode 100644 index d9e32e2a5..000000000 --- a/scripts/common.py +++ /dev/null @@ -1,5297 +0,0 @@ -"""Shared utilities for retrobios scripts. - -Single source of truth for platform config loading, hash computation, -and file resolution - eliminates DRY violations across scripts. -""" - -from __future__ import annotations - -from collections.abc import Callable, Collection, Iterable, Iterator, Mapping -from collections import Counter -import dataclasses -from dataclasses import dataclass - -import argparse -import filecmp -import hashlib -import importlib.util -import functools -import json -import os -import re -import signal -import sys -import zipfile -from pathlib import Path -from typing import TYPE_CHECKING, Any, TextIO, TypedDict - -from model.alternatives import derive_member_requirements - -if TYPE_CHECKING: - from typing_extensions import Unpack - -# Re-exported so the existing call sites keep working while the -# modules above become the place to import from. -from model.safeparse import ( - parse_untrusted_xml as parse_untrusted_xml, - require_yaml as require_yaml, - yaml_load as yaml_load, - _pick_yaml_loader as _pick_yaml_loader, - _YAML_LOADER as _YAML_LOADER, -) -from core.hashing import ( - compute_hashes as compute_hashes, - md5sum as md5sum, - md5_composite as md5_composite, - parse_md5_list as parse_md5_list, - cut_md5_owner as cut_md5_owner, - _ALL_ALGORITHMS as _ALL_ALGORITHMS, - _md5_composite_cache as _md5_composite_cache, -) -from core.ziptools import ( - check_inside_zip as check_inside_zip, - build_zip_contents_index as build_zip_contents_index, - MAX_ZIP_MEMBERS as MAX_ZIP_MEMBERS, - MAX_ZIP_MEMBER_SIZE as MAX_ZIP_MEMBER_SIZE, - MAX_ZIP_TOTAL_SIZE as MAX_ZIP_TOTAL_SIZE, - MAX_ZIP_COMPRESSION_RATIO as MAX_ZIP_COMPRESSION_RATIO, - safe_extract_zip as safe_extract_zip, - _zip_contents_cache as _zip_contents_cache, - _BOUNDED_RATIO_METHODS as _BOUNDED_RATIO_METHODS, - zip_member_crcs as zip_member_crcs, - zip_member_names as zip_member_names, -) -from core.artifacts import ( - write_if_changed as write_if_changed, - write_text_atomic as write_text_atomic, - copy_file_atomic as copy_file_atomic, - plain_file_mode as plain_file_mode, - set_plain_mode as set_plain_mode, - ArtifactDirectoryMissing as ArtifactDirectoryMissing, - ArtifactLockBusy as ArtifactLockBusy, - artifact_lock as artifact_lock, - hold_artifact_lock as hold_artifact_lock, - hold_repository_outputs as hold_repository_outputs, - publish_hold as publish_hold, - repository_output_lock as repository_output_lock, - _TIMESTAMP_PATTERNS as _TIMESTAMP_PATTERNS, - _strip_timestamps as _strip_timestamps, -) -from model.largefiles import ( - LARGE_FILES_RELEASE as LARGE_FILES_RELEASE, - LARGE_FILES_REPO as LARGE_FILES_REPO, - LARGE_FILES_CACHE as LARGE_FILES_CACHE, - fetch_large_file as fetch_large_file, -) -from model.dumpcatalog import ( - DEFAULT_PROVENANCE_DIR as DEFAULT_PROVENANCE_DIR, - load_provenance_snapshots as load_provenance_snapshots, - build_provenance_index as build_provenance_index, - annotate_provenance as annotate_provenance, - write_provenance_snapshot as write_provenance_snapshot, -) - -# 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]}" - ) - - -try: - import yaml -except ImportError: - yaml = None - - - - - - - - -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 DatabaseUnreadable(InputMissing): - """The database a command was pointed at does not exist or is not JSON.""" - - -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.""" - - -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 - - -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 - - - -# One slot: the dict it was built from, its size then, and the folded view. -# Keyed by id() alone, a database freed and replaced by another at the same -# address got the old index back, and the case-insensitive step answered from -# a collection that no longer existed. -_casefold_index_cache: list[tuple[dict, int, dict[str, list[str]]]] = [] - - -def _casefold_name_index(by_name: dict) -> dict[str, list[str]]: - """Build (and cache) a casefolded view of the by_name index.""" - if _casefold_index_cache: - source, size, cached = _casefold_index_cache[0] - if source is by_name and size == len(by_name): - return cached - folded: dict[str, list[str]] = {} - for name, sha1s in by_name.items(): - folded.setdefault(name.casefold(), []).extend(sha1s) - _casefold_index_cache[:] = [(by_name, len(by_name), folded)] - return folded - - -# bios/Other/ and bios/Arcade/ 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// 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 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 - - -# 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"}) - - -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)) - - - - -_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/.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} - - -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 - ] - - -# A list this short is printed whole rather than pointed at. -SHORT_LIST = 12 - - -@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 - - -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 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 = Path(__file__).resolve().parent.parent - 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 _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}" - - -HASH_EXACT_RESOLUTION_STATUSES = frozenset( - { - "sha1_exact", - "sha256_exact", - "crc32_exact", - "md5_exact", - "md5_composite_exact", - "zip_exact", - "data_dir_hash_exact", - } -) - - -def resolution_is_hash_exact(status: str) -> bool: - """Whether *status* proves content identity with a declared hash.""" - return status in HASH_EXACT_RESOLUTION_STATUSES - - -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" - - -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() - - -def _resolve_agnostic( - file_entry: dict, files_db: dict, has_strong_hash: bool -) -> tuple[str, str] | None: - """Any file of the right shape under the declared prefix. - - Some cores accept whatever filename sits in their BIOS directory, so the - shape (a size or a size range) is all that identifies a candidate. A - declared hash outranks that, and stops this step being reached. - """ - if not file_entry.get("agnostic") or has_strong_hash: - return None - prefix = file_entry.get("agnostic_path_prefix", "") - if not prefix: - return None - for entry in files_db.values(): - path = entry.get("path", "") - if not path.startswith(prefix): - continue - if os.path.exists(path) and shape_fits(file_entry, path, entry.get("size", 0)): - return path, "agnostic_fallback" - return None - - -_VARIANT_SUFFIX = re.compile(r"\.[0-9a-f]{8}$") - - -def variant_base_name(name: str) -> str: - """The name a .variants/ copy stands in for: naomi2.zip.da79eca4 -> naomi2.zip. - - Only an eight-hex-digit suffix is a variant tag. A variant stored under - its plain name (.variants/aes.zip) already is that name. - """ - return _VARIANT_SUFFIX.sub("", name) - - -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// 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// 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])) - - -def _rank_tail_candidates( - candidates: list[str], start: int, tail: str, files_db: dict, owners: set[str], - asker: frozenset[str] = frozenset(), -) -> list[str]: - """Order the files a destination tail designates, the likeliest first. - - A tail found in another emulator's tree is that emulator's asset, not - evidence about this entry, whatever its length. A full tail claimed - twice goes to the file whose path carries the least on top of the - destination, then to the owner's own copy (super3's Games.xml was served - to Supermodel-Dojo by index order alone), then to any copy outside - another emulator's tree (upstream PCSX2 took EmuCoreX's GameIndex.yaml - over the system directory's). - """ - def path_of(sha1: str) -> str: - return files_db.get(sha1, {}).get("path", "") - - # Another emulator's tree answers that emulator's entry, at any tail - # length when a profile asks: lrps2 names no hash for - # pcsx2/resources/GameIndex.yaml, and the only full-tail copy was ARMSX2's, - # which then counted as path proof and replaced the GameIndex RetroArch - # pins on every desktop target. A platform's own declaration has no - # asker, and the tree whose path is its destination still answers it. - if start or asker: - # The database keeps one path per content. When that path does not - # end with the tail, the tail was indexed from an identical copy - # elsewhere, and the recorded path says nothing about whose tree it - # sits in: PCSX2x6's RedumpDatabase.yaml has EmuCoreX's bytes. - candidates = [ - h for h in candidates - if not path_of(h).endswith("/" + tail) - or not _foreign_tree(path_of(h), owners if start else set(asker)) - ] - if len(candidates) < 2: - return candidates - depth = len(tail.split("/")) - return sorted( - candidates, - key=lambda h: ( - len(path_of(h).split("/")) - depth, - not owners & _affinity_tokens(path_of(h).rsplit("/", 1)[0]), - _foreign_tree(path_of(h), owners), - ), - ) - - -# 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//) 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] - - -def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str]: - """Same-named candidates, the likeliest first. - - A name step without a tie-break took whichever path sorted first: the - TheXTech coin.ogg for Syobon Action, a Hurrican sound for ARMSX2, the - 1 MB CM-32L PCM ROM for ScummVM's 512 KB MT32_PCM.ROM. A size the entry - declares orders the candidates first (ordering rejects nothing, so an - unvalidated size keeps its informative status). Then the destination's - directories and the profile that asks name where its own copy lives. The - order is otherwise kept. - """ - if len(paths) < 2: - return paths - hint = dest_hint or file_entry.get("path") or file_entry.get("destination") or "" - wanted = _affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "") - owners = _owner_tokens(file_entry) - sized = declares_shape(file_entry) - - def score(path: str) -> tuple[int, bool, bool, bool, int]: - fits = 0 - if sized and os.path.exists(path): - fits = int(shape_fits(file_entry, path)) - tokens = _affinity_tokens(path.rsplit("/", 1)[0]) - # The owner's own copy ranks above any shared tree segment: NetherSX2's - # shaders/common/ beat armsx2's own fxaa.fx on two directory tokens. - # Another emulator's own tree ranks below everything else. - # A game's folder under Game Engines/ holds that game's data: for a - # name-only match, a neutral copy goes first. hypseus-singe, - # flycast-dojo, lindbergh-loader and vvvvvv took C-Dogs' 98-line - # gamecontrollerdb.txt by index order. - return ( - fits, bool(owners & tokens), not _foreign_tree(path, owners | wanted), - not _engine_tree(path, owners | wanted), len(wanted & tokens), - ) - - return sorted(paths, key=score, reverse=True) - - -_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) - - -Resolution = tuple[str, str] - - -@dataclass(frozen=True) -class _Lookup: - """One entry as resolve_local_file reads it: its names and declared hashes.""" - - file_entry: dict - db: dict - dest_hint: str - name: str - zipped_file: str | None - names_to_try: list[str] - own_names: list[str] - md5_list: list[str] - sha1_candidates: list[str] - sha256_candidates: list[str] - crc_candidates: dict[str, None] - declared_size: Any - files_db: dict - by_name: dict - by_path_suffix: dict - composite_only: bool - - @property - def has_strong_hash(self) -> bool: - return bool( - self.sha1_candidates or self.sha256_candidates or self.md5_list or self.crc_candidates - ) - - -def _lookup_names(name: str, aliases: list, dest_hint: str) -> tuple[list[str], list[str]]: - """The names an entry answers to, and the part of them that is its own.""" - names_to_try = [name] + [a for a in aliases if a != name] - - # When name contains a path separator (e.g. "res/tilemap.bin"), also - # try the basename since by_name indexes filenames without directories - if "/" in name: - name_base = name.rsplit("/", 1)[-1] - if name_base and name_base not in names_to_try: - names_to_try.append(name_base) - - # When dest_hint contains a path, also try its basename as a name - # (handles emulator profiles where name: is descriptive and path: is - # the actual filename, e.g. name: "MDA font ROM", path: "mda.rom") - own_names = list(names_to_try) - if dest_hint: - hint_base = dest_hint.rsplit("/", 1)[-1] if "/" in dest_hint else dest_hint - if hint_base and hint_base not in names_to_try: - names_to_try.append(hint_base) - return names_to_try, own_names - - -def _lookup( - file_entry: dict, db: dict, dest_hint: str, md5_list: list[str], *, composite_only: bool -) -> _Lookup: - """Read the names and every declared hash of an entry once.""" - sha1 = file_entry.get("sha1") - name = file_entry.get("name", "") - names_to_try, own_names = _lookup_names(name, file_entry.get("aliases", []), dest_hint) - sha1_candidates = [ - str(value).strip().lower() - for value in (sha1 if isinstance(sha1, list) else [sha1] if sha1 else []) - if str(value).strip() - ] - sha256_raw = file_entry.get("sha256") - sha256_values = sha256_raw if isinstance(sha256_raw, list) else [sha256_raw] - sha256_candidates = [ - candidate.strip().lower() - for value in sha256_values - if value - for candidate in str(value).split(",") - if len(candidate.strip()) == 64 - ] - # One value, a list, or a comma-separated string, like the other hashes. - crc_values = file_entry.get("crc32") or [] - # Kept in the order declared, which is the order a lookup tries them. - crc_candidates = dict.fromkeys( - candidate.strip().lower().removeprefix("0x") - for value in (crc_values if isinstance(crc_values, list) else [crc_values]) - for candidate in str(value).split(",") - if candidate.strip() - ) - indexes = db.get("indexes", {}) - return _Lookup( - file_entry=file_entry, - db=db, - dest_hint=dest_hint, - name=name, - zipped_file=file_entry.get("zipped_file"), - names_to_try=names_to_try, - own_names=own_names, - md5_list=md5_list, - sha1_candidates=sha1_candidates, - sha256_candidates=sha256_candidates, - crc_candidates=crc_candidates, - declared_size=file_entry.get("size"), - files_db=db.get("files", {}), - by_name=indexes.get("by_name", {}), - by_path_suffix=indexes.get("by_path_suffix", {}), - composite_only=composite_only, - ) - - -def _record_match_status(q: _Lookup, match_sha1: str) -> str | None: - """Return hash evidence when a DB record satisfies every declaration.""" - entry = q.files_db.get(match_sha1) - if not entry: - return None - statuses: list[str] = [] - if q.sha1_candidates: - if match_sha1.lower() not in q.sha1_candidates: - return None - statuses.append("sha1_exact") - if q.sha256_candidates: - if str(entry.get("sha256", "")).lower() not in q.sha256_candidates: - return None - statuses.append("sha256_exact") - # With zipped_file the MD5 identifies the member, not the container. - if q.md5_list and not q.zipped_file: - actual_md5 = str(entry.get("md5", "")).lower() - if actual_md5 not in q.md5_list: - return None - statuses.append("md5_exact") - if q.crc_candidates: - if str(entry.get("crc32", "")).lower() not in q.crc_candidates: - return None - if q.declared_size is not None: - allowed_sizes = ( - q.declared_size if isinstance(q.declared_size, list) else [q.declared_size] - ) - if entry.get("size") not in allowed_sizes: - return None - statuses.append("crc32_exact") - return statuses[0] if statuses else None - - -def _held_record(q: _Lookup, match_sha1: str) -> Resolution | None: - """The record's path and evidence, when it satisfies the entry and is on disk.""" - path = q.files_db[match_sha1]["path"] - status = _record_match_status(q, match_sha1) - if status and os.path.exists(path): - return path, status - return None - - -def _by_sha1(q: _Lookup) -> Resolution | None: - """SHA1 exact match (accept list-valued sha1 from profiles).""" - for cand in q.sha1_candidates: - if cand in q.files_db: - found = _held_record(q, cand) - if found: - return found - return None - - -def _by_sha256(q: _Lookup) -> Resolution | None: - """SHA256 exact match, through the by_sha256 index.""" - if not q.sha256_candidates: - return None - by_sha256 = q.db.get("indexes", {}).get("by_sha256", {}) - for cand in q.sha256_candidates: - match = by_sha256.get(cand) - if match and match in q.files_db: - found = _held_record(q, match) - if found: - return found - return None - - -def _by_crc32(q: _Lookup) -> Resolution | None: - """CRC32 lookup, only when no stronger hash is declared.""" - if ( - not q.crc_candidates - or q.zipped_file - or q.md5_list - or q.sha1_candidates - or q.sha256_candidates - ): - return None - by_crc32 = q.db.get("indexes", {}).get("by_crc32", {}) - crc_matches: list[Resolution] = [] - for crc in q.crc_candidates: - match = by_crc32.get(crc) - if match and match in q.files_db: - found = _held_record(q, match) - if found: - crc_matches.append(found) - # A primary copy over a .variants/ one, as everywhere else. - for path, status in crc_matches: - if "/.variants/" not in path: - return path, status - if crc_matches: - return crc_matches[0] - return None - - -def _md5_hits(q: _Lookup) -> Iterator[tuple[str, str, str]]: - """Each held record a declared md5 names: path, evidence, md5 asked. - - Skipped for zipped_file: the md5 is the inner ROM's, not the container's. - """ - if not q.md5_list or q.zipped_file or q.composite_only: - return - by_md5 = q.db.get("indexes", {}).get("by_md5", {}) - for md5_candidate in q.md5_list: - sha1_match = by_md5.get(md5_candidate) - if sha1_match and sha1_match in q.files_db: - found = _held_record(q, sha1_match) - if found: - yield found[0], found[1], md5_candidate - - -def _named_or_variant(names: frozenset[str], candidate_path: str) -> bool: - """Whether a path's file name is one of these names, or a variant of one.""" - bn = os.path.basename(candidate_path) - if bn in names: - return True - # .variants/ pattern: filename like "neogeo.zip.fc398ab4" - return any(bn.startswith(n + ".") for n in names) - - -def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> list[str]: - """The records a destination tail names, ranked, ambiguity read.""" - candidates = _rank_tail_candidates( - q.by_path_suffix.get(tail, []), start, tail, q.files_db, owners, - frozenset(_owner_tokens(q.file_entry)), - ) - raw = q.by_path_suffix.get(tail, []) - if start and len(raw) > 1: - # Ambiguity is read before the foreign trees are set aside: - # PCSX2x6's bin/resources/GameIndex.yaml met four copies - # under resources/GameIndex.yaml, three in other emulators' - # trees, and the fourth (PCSX2's console database, not - # PCSX2x6's arcade one) passed for proof. Only the asker's own - # tree still answers a tail several files share. - candidates = [ - h for h in candidates - if _own_tree(q.files_db.get(h, {}).get("path", ""), owners) - ] - return candidates - - -def _tail_match(q: _Lookup, candidates: list[str]) -> Resolution | None: - """The first candidate of a tail on disk that the entry accepts.""" - for match_sha1 in candidates: - if match_sha1 not in q.files_db: - continue - path = q.files_db[match_sha1]["path"] - if not os.path.exists(path): - continue - if not q.has_strong_hash: - # A path names the file, the size the code checks still - # bounds it, as on the name step: ZEsarUX's 48 KB - # cpc6128.rom is not cap32's 32 KB one at the same tail. - if not name_match_size_ok( - q.file_entry, q.files_db[match_sha1].get("size") - ) or not adler32_fits(q.file_entry, path, q.db) or not content_fits( - q.file_entry, path - ): - continue - return path, "path_exact" - status = _record_match_status(q, match_sha1) - if status: - return path, status - return None - - -def _by_path_suffix(q: _Lookup) -> tuple[Resolution | None, bool]: - """The file at the destination's tail, and whether the indexed one is absent.""" - own_file_absent = False - if not (q.dest_hint and q.by_path_suffix): - return None, own_file_absent - # A destination is written from the emulator's point of view - # ("pcsx2/resources/GameIndex.yaml") and the index from the repo's - # layout, so the two meet on a tail rather than on the whole string. - # Longest tail first, and never down to the bare filename: that is the - # weaker step below, and five files answer to GameIndex.yaml. - # Two kinds of ambiguity appear once every tail is indexed. A - # shortened tail can be claimed by several emulators shipping the same - # asset tree, and it then proves nothing: skip it. The full tail can be - # claimed twice as well, one storing it at the root of its own - # directory and one nested deeper. There the file whose path carries - # the least on top of the destination is the one that IS the - # destination. - # The descent drops at most one leading segment. A destination and the - # tree differ by the wrapper directory at most. Beyond that the tail - # stops describing this file and starts describing whichever emulator - # happens to store the same asset tree. - hint_parts = q.dest_hint.split("/") - # The asking profile and the destination's own directories both name - # whose tree a copy may come from. - owners = _owner_tokens(q.file_entry) | _affinity_tokens("/".join(hint_parts[:-1])) - for start in range(min(2, len(hint_parts) - 1)): - candidates = _tail_candidates(q, start, "/".join(hint_parts[start:]), owners) - if start and len(candidates) > 1: - continue - # The index names the file this destination designates. Not on - # disk, it is a release asset the checkout does not hold, and no - # other file of that name is it. - if not start and candidates and not any( - os.path.exists(q.files_db.get(h, {}).get("path", "")) - for h in candidates - ): - own_file_absent = True - found = _tail_match(q, candidates) - if found: - return found, own_file_absent - return None, own_file_absent - - -def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution | None: - """The same tail in a data directory, for a platform's hashless entry.""" - # by_path_suffix indexes bios/ - # only, so AmberELEC's Machines/MSX - Arabic/config.ini fell through to - # the name step and got msx-emu's ColecoVision config.ini, while - # data/bluemsx held blueMSX's own at that very path. A platform - # declaration is resolved without a hint, and its destination is that - # path. The descent and the ambiguity rule are those of the bios/ tails. - # A profile's entry is not asked here: it names its owner, the name step - # sends it to its data directories when another emulator's copy answers, - # and a dump it declares outranks the free one its tree bundles at the - # same path (Dolphin's dsp_coef.bin over Sys/GC's). - tail_hint = q.dest_hint or str(q.file_entry.get("destination") or "") - if ( - tail_hint - and data_dir_registry - and not q.has_strong_hash - and not _owner_tokens(q.file_entry) - ): - hit = _data_dir_tail(tail_hint, data_dir_registry, q.file_entry, q.db) - if hit: - return hit, "path_exact" - return None - - -def _name_size_ok(q: _Lookup, match_sha1: str) -> bool: - """Whether a record found by name has the shape the entry's code checks.""" - record = q.files_db.get(match_sha1, {}) - return name_match_size_ok(q.file_entry, record.get("size")) and adler32_fits( - q.file_entry, record.get("path", ""), q.db - ) and content_fits(q.file_entry, record.get("path", "")) - - -def _exact_name_candidates(q: _Lookup) -> list[str]: - """The held files answering to the entry's names, exact casing.""" - candidates: list[str] = [] - # The entry's own names first, the destination's basename only when - # none of them answers. melonDS Nightly's dsi_nand.bin is read at - # dsi/nand.bin: with the DSi image absent from the checkout, the - # basename let the Wii nand.bin outrank the entry's own DSi variant. - # A name whose held file no declaration proves, while declarations - # of that name prove another dump beside it, means that dump: the - # DSi devkit boot ROMs filed as dsi_bios7.bin went to RetroBat. - by_proven_name = q.db.get("indexes", {}).get("by_proven_name", {}) - for tier in (q.own_names, q.names_to_try[len(q.own_names):]): - for try_name in tier: - for match_sha1 in ( - by_proven_name.get(try_name) or q.by_name.get(try_name, []) - ): - if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): - path = q.files_db[match_sha1]["path"] - if os.path.exists(path) and path not in candidates: - candidates.append(path) - if candidates: - break - return candidates - - -def _add_variant_primaries(q: _Lookup, candidates: list[str]) -> None: - """Add the primaries that variants answering the exact casing stand in for.""" - # Only variants answer the exact casing, but the primary they - # stand in for may be stored under another one: x1 asked for - # IPLROM.X1 and got Recalbox's second md5 while iplrom.x1, the - # dump every platform pins, sat in the same directory. A primary - # counts here only in a variant's own directory and under its own - # file name: an alias (iplrom.x1t names a font in System.dat) or - # another machine's font.rom is not that file. - homes = {p.split("/.variants/", 1)[0] for p in candidates} - folded = _casefold_name_index(q.by_name) - for try_name in q.names_to_try: - wanted = try_name.rsplit("/", 1)[-1].casefold() - for match_sha1 in folded.get(try_name.casefold(), []): - path = q.files_db.get(match_sha1, {}).get("path", "") - if ( - "/.variants/" not in path - and os.path.dirname(path) in homes - and os.path.basename(path).casefold() == wanted - and _name_size_ok(q, match_sha1) - and os.path.exists(path) - and path not in candidates - ): - candidates.append(path) - - -def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str]) -> None: - """Add the held files answering to the entry's names in another casing.""" - # Case-insensitive fallback: upstream platforms disagree on - # casing (VEC_MineStorm.vec vs VEC_Minestorm.vec). Two casings - # can name two contents (FONT.ROM and font.rom), so this only - # runs when no casing matches exactly, or when only another - # emulator's tree does: xm6typeg got XM6 Utility's synthesized - # SCSIINROM.DAT while the X68000 dump sat as scsiinrom.dat. - # Another casing in another emulator's tree proves nothing: - # reminiscence's music module reunion took skyline's - # zoneinfo/Indian/Reunion. - folded = _casefold_name_index(q.by_name) - for try_name in q.names_to_try: - for match_sha1 in folded.get(try_name.casefold(), []): - if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): - path = q.files_db[match_sha1]["path"] - if _foreign_tree(path, owners): - continue - if os.path.exists(path) and path not in candidates: - candidates.append(path) - - -def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> list[str]: - """The candidates filed under the system's maker, or its shadowed aliases.""" - candidates = [p for p in candidates if not other_maker(p, makers, q.db)] - if candidates: - return candidates - # The name belongs to another maker's file here. An emulator - # of this system may still read it as an alias of one of its - # own files, an alias by_name leaves out because a primary - # already carries the name: QUASI88 reads DISK.ROM as - # n88sub.rom. - shadowed = q.db.get("indexes", {}).get("by_shadowed_alias", {}) - for try_name in q.own_names: - for match_sha1 in shadowed.get(try_name, []): - path = q.files_db.get(match_sha1, {}).get("path", "") - if ( - _maker_folder(path, str(q.db.get("bios_dir") or "bios")) - in makers - and _name_size_ok(q, match_sha1) - and os.path.exists(path) - and path not in candidates - ): - candidates.append(path) - return candidates - - -def _choose_by_name( - q: _Lookup, - candidates: list[str], - owners: set[str], - exact_foreign: bool, - data_dir_registry: dict | None, -) -> Resolution | None: - """The best of the files a name step found, or the data directory's own.""" - if q.zipped_file: - candidates = [p for p in candidates if ".zip" in os.path.basename(p)] - members = q.file_entry.get("members") or contents_members(q.file_entry) - if members or (len(candidates) > 1 and q.name.casefold().endswith(".zip")): - # Another emulator's own copy takes no part in the ranking: - # Demul's naomi.zip holds more NAOMI BIOS rows than any MAME - # set and broke the superset the MAME cores were served. - candidates = [ - p for p in candidates if not _foreign_tree(p, owners) - ] or candidates - if members: - candidates = _holding_members(candidates, members) - elif len(candidates) > 1 and q.name.casefold().endswith(".zip"): - candidates = _covering_archives(candidates) - candidates = _by_affinity(candidates, q.file_entry, q.dest_hint) - best = candidates[0] if candidates else "" - # A copy outside another emulator's tree comes first: the - # affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served - # upstream PCSX2 the patches.zip of ARMSX2. - candidates = [ - p for p in candidates if not _foreign_tree(p, owners) - ] or candidates - primary = [p for p in candidates if "/.variants/" not in p] - if not (primary or candidates): - return None - chosen = primary[0] if primary else candidates[0] - # The best of them is another emulator's own copy, served or - # set aside: the name says nothing about this profile's file, - # and a data directory it reads may hold it. Dolphin got - # Dolphin-MMJR's codehandler.bin while data/dolphin-sys held - # its own, and blueMSX got the 16 KB RS232.ROM once msx-emu's - # 8 KB copy was set aside, while data/bluemsx held its own, - # and MSX2P.ROM of another dump once only msx-emu answered - # the exact casing. - if data_dir_registry and (exact_foreign or _foreign_tree(best, owners)): - hit, _mismatch = _resolve_in_data_dirs( - q.names_to_try, data_dir_registry, - functools.partial( - declared_hash_verdict, - has_strong_hash=False, - sha1_candidates=set(), - sha256_candidates=set(), - md5_list=[], - crc_candidates=set(), - zipped_file=q.zipped_file, - declared_size=q.declared_size, - file_entry=q.file_entry, - db=q.db, - ), - ) - if hit: - return hit - return chosen, "name_exact" - - -def _by_name( - q: _Lookup, makers: frozenset[str], data_dir_registry: dict | None -) -> tuple[Resolution | None, bool]: - """Any file with that name or alias (existence check). - - The second value says the name proved nothing, which makes the entry - unsourceable for the steps after this one. - """ - candidates = _exact_name_candidates(q) - if candidates and all("/.variants/" in p for p in candidates): - _add_variant_primaries(q, candidates) - owners = _owner_tokens(q.file_entry) - # Only another emulator's tree answers the exact casing: what it - # holds there says nothing about this entry's file. - exact_foreign = bool(candidates) and all( - _foreign_tree(p, owners) for p in candidates - ) - if not candidates or exact_foreign: - _add_casefold_candidates(q, candidates, owners) - # A platform entry names no profile, but a system that lists its - # cores says whose files it asks for. A name only another emulator's - # tree answers is no evidence, and the data directories hold those - # emulators' trees too: EmuELEC's VVVVVV data.zip was served xrick's - # archive of the same name, then xrick's data directory copy. - core_owners = { - token - for core in q.file_entry.get("platform_cores") or () - for token in _affinity_tokens(str(core)) - } - if ( - not owners - and core_owners - and candidates - and all(_foreign_tree(p, core_owners) for p in candidates) - ): - return None, True - if makers and candidates: - candidates = _same_maker(q, candidates, makers) - if not candidates: - return None, False - return _choose_by_name(q, candidates, owners, exact_foreign, data_dir_registry), False - - -def _named_candidates(q: _Lookup, makers: frozenset[str]) -> list[tuple[str, str, int | None]]: - """Every held file of the entry's names: path, md5, size.""" - named: list[tuple[str, str, int | None]] = [] - seen_paths = set() - for try_name in q.names_to_try: - for match_sha1 in q.by_name.get(try_name, []): - if match_sha1 in q.files_db: - entry = q.files_db[match_sha1] - path = entry["path"] - if os.path.exists(path) and path not in seen_paths: - seen_paths.add(path) - named.append( - (path, entry.get("md5", ""), entry.get("size")) - ) - - if q.zipped_file: - named = [c for c in named if ".zip" in os.path.basename(c[0])] - # Another maker's file is no mismatch of this one, it is another file. - named = [c for c in named if not other_maker(c[0], makers, q.db)] - # A size the emulator itself verifies settles a name collision, so a - # candidate that fits is preferred over one that does not: "ROM" answers - # both an Apple IIgs image and a Macintosh one. It ranks rather than - # excludes, because a present file of the wrong size is reported as - # present and untested, and dropping it would report it as absent. - sized = [ - c for c in named - if name_match_size_ok(q.file_entry, c[2]) and content_fits(q.file_entry, c[0]) - ] - if sized: - named = sized - return named - - -def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution | None: - """A named file whose md5, or archive composite, is a declared one. - - Sorts *named* in place for a composite-only entry, as the steps after - this one read it. - """ - md5_set = set(q.md5_list) - if not md5_set or q.sha1_candidates or q.sha256_candidates or q.crc_candidates: - return None - if q.composite_only: - named.sort(key=lambda c: "/.variants/" in c[0]) - for path, db_md5, _size in named: - if ".zip" in os.path.basename(path): - try: - composite = md5_composite(path).lower() - # A zipped_file md5 is the member's: one member of - # another name has the same composite, and Batocera - # looks the member up by name. - if composite in md5_set and ( - not q.zipped_file - or check_inside_zip(path, q.zipped_file, composite) == "ok" - ): - return path, "md5_composite_exact" - except (zipfile.BadZipFile, OSError) as exc: - _warn_unreadable_archive(path, exc) - if db_md5.lower() in md5_set and not q.composite_only: - return path, "md5_exact" - return None - - -def _zipped_named( - q: _Lookup, named: list[tuple[str, str, int | None]], zipped_file: str -) -> Resolution | None: - """When zipped_file is set, only accept candidates that contain it.""" - valid = [] - for path, m, size in named: - try: - with zipfile.ZipFile(path) as zf: - inner_names = {n.casefold() for n in zf.namelist()} - if zipped_file.casefold() in inner_names: - valid.append((path, m, size)) - except (zipfile.BadZipFile, OSError) as exc: - _warn_unreadable_archive(path, exc) - # The archive whose member carries the declared md5 is the one: - # neogeo.zip is held twice, each with its own sfix.sfix, and the - # first by name was returned as a mismatch while the other matched. - for path, _m, _size in sorted(valid, key=lambda c: "/.variants/" in c[0]): - if any(check_inside_zip(path, zipped_file, md5) == "ok" for md5 in q.md5_list): - return path, "zip_exact" - if valid: - primary = [c[0] for c in valid if "/.variants/" not in c[0]] - return (primary[0] if primary else valid[0][0]), "hash_mismatch" - # No candidate contains the zipped_file: fall through to step 5 - return None - - -def _ranked_mismatch(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution: - """The named file the entry would take, reported as a hash mismatch.""" - ordered = _by_affinity([c[0] for c in named], q.file_entry, q.dest_hint) - primary = [c for c in ordered if "/.variants/" not in c] - return (primary[0] if primary else ordered[0]), "hash_mismatch" - - -def _by_zip_contents(q: _Lookup, zip_contents: dict | None) -> Resolution | None: - """zipped_file content match via pre-built index. - - Last resort: matches inner ROM MD5 across ALL ZIPs in the repo, so only - used when name-based resolution failed entirely. - """ - if not ( - q.zipped_file - and q.md5_list - and zip_contents - and not (q.sha1_candidates or q.sha256_candidates or q.crc_candidates) - ): - return None - for md5_candidate in q.md5_list: - if md5_candidate in zip_contents: - zip_sha1 = zip_contents[md5_candidate] - if zip_sha1 in q.files_db: - path = q.files_db[zip_sha1]["path"] - if os.path.exists(path): - return path, "zip_exact" - return None - - -def _by_mame_clone( - q: _Lookup, zip_contents: dict | None, depth: int, data_dir_registry: dict | None -) -> Resolution | None: - """If a file was deduped, resolve via canonical.""" - clone_map = get_mame_clone_map(q.db.get("bios_dir")) - canonical = clone_map.get(q.name) - if not canonical or canonical == q.name: - return None - canonical_entry = { - field: q.file_entry[field] - for field in ( - "size", "min_size", "max_size", "size_multiple", "validation", - *sorted(CONTENT_CHECKS), - ) - if field in q.file_entry - } - canonical_entry["name"] = canonical - result = resolve_local_file( - canonical_entry, - q.db, - zip_contents, - q.dest_hint, - _depth=depth + 1, - data_dir_registry=data_dir_registry, - ) - if result[0] and result[1] != "hash_mismatch": - return result[0], "mame_clone" - return None - - -def _in_data_dirs(q: _Lookup, data_dir_registry: dict) -> tuple[Resolution | None, str | None]: - """Data directory fallback: scan data/ caches for matching filename.""" - verdict = functools.partial( - declared_hash_verdict, - has_strong_hash=q.has_strong_hash, - sha1_candidates=q.sha1_candidates, - sha256_candidates=q.sha256_candidates, - md5_list=q.md5_list, - crc_candidates=set(q.crc_candidates), - zipped_file=q.zipped_file, - declared_size=q.declared_size, - file_entry=q.file_entry, - db=q.db, - ) - return _resolve_in_data_dirs(q.names_to_try, data_dir_registry, verdict) - - -def _resolve_layout( - file_entry: dict, - db: dict, - zip_contents: dict | None, - dest_hint: str, - *, - depth: int, - data_dir_registry: dict | None, -) -> tuple[str | None, str]: - """Resolve an entry whose launcher moves it, at both destinations.""" - layout = file_entry.get("layout_path") - plain = {k: v for k, v in file_entry.items() if k != "layout_path"} - # A destination outside the BIOS tree says nothing of the collection: - # EmuELEC's roms/mame/konamigv.zip is not bios/Arcade/MAME's set. - outside = file_entry.get("unprefixed") or file_entry.get("root") - answers = [ - resolve_local_file( - plain, db, zip_contents, dest_hint=hint, _depth=depth, - data_dir_registry=data_dir_registry, - ) - for hint in ((str(layout),) if outside else (dest_hint, str(layout))) - ] - for found in answers: - if found[0] is not None and ( - resolution_is_hash_exact(found[1]) or found[1] == "path_exact" - ): - return found - for found in answers: - if found[0] is not None and found[1] not in ("not_found", "hash_mismatch"): - return found - return next((found for found in answers if found[0] is not None), answers[0]) - - -def _entry_hint(file_entry: dict, dest_hint: str) -> str: - """The destination tail the collection indexes the entry under.""" - # A platform that hands each core a system directory of its own (MinUI's - # Bios//) writes that folder in front of the core's path. The tail - # the collection indexes is the core's path alone. - system_dir = file_entry.get("system_dir") - if system_dir and dest_hint.startswith(f"{system_dir}/"): - dest_hint = dest_hint[len(system_dir) + 1:] - return dest_hint - - -def _name_as_hint(name: str, dest_hint: str) -> str: - """A name written with its directory is the destination when no path is given.""" - # gam4980/E.BIN resolved by its basename took another model's OS - # in verify --emulator and the emulator pack, while the platform pack, - # which passes the destination, served the GAM4980's. - if not dest_hint and "/" in name.strip("/"): - return name - return dest_hint - - -def resolve_local_file( - file_entry: dict, - db: dict, - zip_contents: dict | None = None, - dest_hint: str = "", - _depth: int = 0, - data_dir_registry: dict | None = None, -) -> tuple[str | None, str]: - """Resolve a BIOS file to its local path using database.json. - - Single source of truth for file resolution, used by both verify.py - and generate_pack.py. Does NOT handle storage tiers (external/user_provided) - or release assets - callers handle those. - - dest_hint: optional destination path (e.g., "GC/USA/IPL.bin") used to - disambiguate when multiple files share the same name. Matched against - the by_path_suffix index built from the repo's directory structure. - - Returns ``(local_path, status)``. Statuses describe the evidence used: - ``sha1_exact``, ``sha256_exact``, ``crc32_exact``, ``md5_exact``, - ``md5_composite_exact``, ``zip_exact``, ``path_exact``, ``name_exact``, - ``hash_mismatch`` or ``not_found`` (plus documented fallback statuses). - - A path or filename is never allowed to override a declared strong hash. - """ - dest_hint = _entry_hint(file_entry, dest_hint) - # A launcher that moves the layout (EmuDeck links azahar's sysdata to - # bios/azahar/keys) changes where the file goes, not the tail the - # collection indexes it under. Both are asked, and the stronger proof - # wins: a content or path match over a name, the destination on a tie. - layout = file_entry.get("layout_path") - if layout and layout != dest_hint: - return _resolve_layout( - file_entry, db, zip_contents, dest_hint, - depth=_depth, data_dir_registry=data_dir_registry, - ) - md5_list = parse_md5_list(file_entry.get("md5")) - by_md5 = db.get("indexes", {}).get("by_md5", {}) - # A value cut short stands for the one held md5 it starts, and only - # then (cut_md5_owner): the dump it names is still name-guarded below. - cut_owners = { - cut: owner for cut in md5_list - if len(cut) < 32 and (owner := cut_md5_owner(cut, by_md5)) - } - # A frontend that hashes an archive by its members (Recalbox) never reads - # the container's own md5: neocd.bin's md5 is also the composite of a - # one-member neocdz.zip, and the raw ROM shipped under the archive's name. - composite_only = file_entry.get("zip_digest") == "composite" - q = _lookup( - file_entry, db, _name_as_hint(file_entry.get("name", ""), dest_hint), - [cut_owners.get(value, value) for value in md5_list], - composite_only=composite_only, - ) - has_strong_hash = q.has_strong_hash - # Guard of step 2: only accept if the found file's name matches the - # requested name (or is a .variants/ derivative). Prevents - # cross-contamination when an unrelated file happens to share the same - # MD5 in the index. - _md5_name_ok = functools.partial(_named_or_variant, frozenset(q.names_to_try)) - - found = ( - # 1. SHA1 exact match (accept list-valued sha1 from profiles) - _by_sha1(q) - # 1b. SHA256 exact match (profiles hashed from sources that publish - # sha256, e.g. MesenCE). A full sha256 is a strong identifier. - or _by_sha256(q) - # 1c. CRC32 lookup, only when no stronger hash is declared. A declared - # size confirms it when available. A handful of emulators validate CRC32 - # alone, so those entries retain the same (weaker) evidence as the core. - or _by_crc32(q) - # 2. MD5 direct lookup (skip for zipped_file: md5 is inner ROM, not container) - # A full md5 as declared is a strong identifier: trusted without - # name guard. One completed from a cut value still needs the name - # check to avoid cross-contamination. - or next( - ( - (path, status) - for path, status, md5_candidate in _md5_hits(q) - if md5_candidate not in cut_owners.values() or _md5_name_ok(path) - ), - None, - ) - ) - if found: - return found - - # 2b. Path suffix lookup is useful for same-named regional files, but it - # is identity evidence only when no content hash was declared. A stale - # or incorrect destination can therefore never mask a hash mismatch. - found, own_file_absent = _by_path_suffix(q) - # 2c. The same tail in a data directory. - found = found or _by_data_dir_tail(q, data_dir_registry) - if found: - return found - - # 3. No MD5 = any file with that name or alias (existence check) - # An entry the profile documents as unsourceable is one the collection - # cannot hold: a font that only exists inside a paid package, cheat codes - # written per title. A file answering to its name is therefore a homonym - # from another system, not a stale dump of the same file - kanji.rom names - # an FPseNG font, an openMSX one and a 3DO ROM. Content still decides: the - # hash and path steps above run first, so collecting the real bytes makes - # the entry resolve. - unsourceable = bool(file_entry.get("unsourceable")) or own_file_absent - # A platform's own hashless entry whose system names a maker takes no copy - # filed under another maker: AmberELEC's nec-pc-88 DISK.ROM, which QUASI88 - # reads as the 2 KB PC-88 disk ROM, got the 16 KB MSX one by name. - makers: frozenset[str] = frozenset() if has_strong_hash else system_makers(file_entry, db) - - if not has_strong_hash and not unsourceable: - found, unsourceable = _by_name(q, makers, data_dir_registry) - if found: - return found - - # 4. Name + alias fallback with md5_composite + direct MD5 per candidate - named = _named_candidates(q, makers) - if named: - found = _named_md5_match(q, named) - if q.zipped_file: - found = found or _zipped_named(q, named, q.zipped_file) - elif not unsourceable: - found = found or _ranked_mismatch(q, named) - if found: - return found - - # 5. zipped_file content match via pre-built index (last resort: - # matches inner ROM MD5 across ALL ZIPs in the repo, so only use - # when name-based resolution failed entirely) - found = _by_zip_contents(q, zip_contents) - - # MAME clone fallback: if a file was deduped, resolve via canonical. The - # clone name is a name step like the others: an unsourceable entry skips - # it, and the size the code checks travels with it (dedup only merges - # identical bytes, so the canonical copy has the clone's size). - if _depth < 3 and not has_strong_hash and not unsourceable: - found = found or _by_mame_clone(q, zip_contents, _depth, data_dir_registry) - if found: - return found - - # Data directory fallback: scan data/ caches for matching filename - data_dir_mismatch: str | None = None - # Without a hash the cache walk matches on filename alone, which is the - # step an unsourceable entry has to skip: hiscore.dat names one file per - # driver set, so FBNeo's copy would answer for MAME's. - if data_dir_registry and (has_strong_hash or not unsourceable): - found, data_dir_mismatch = _in_data_dirs(q, data_dir_registry) - if found: - return found - - if data_dir_mismatch and not unsourceable: - return data_dir_mismatch, "hash_mismatch" - - return _resolve_agnostic(file_entry, q.files_db, has_strong_hash) or (None, "not_found") - - -_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( - os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "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 - - - - - -_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( - os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "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" - } - - -# 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" - ) - - -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 - - -_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 - - -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//) 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 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(Path(__file__).resolve().parent.parent / "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(Path(__file__).resolve().parent.parent / "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 _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 _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 - - -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)] - - -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(Path(__file__).resolve().parent.parent / "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/.json: the BIOS and device sets each game set - loads, from the -listxml of the version the profile pins.""" - path = Path(__file__).resolve().parent.parent / "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 - # /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 - - -# 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] - - -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(Path(__file__).resolve().parent.parent / "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) - } - - -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 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}" - - -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)) - - -# Validation and mode filtering: extracted to validation.py for SoC. -# Re-exported below for backward compatibility. - - - -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 ("..", ".")) - - - - -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 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 - - -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()) - - -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 --list-targets " - "lists the targets of one platform.") - - -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) diff --git a/scripts/core/cli.py b/scripts/core/cli.py new file mode 100644 index 000000000..adf4daa30 --- /dev/null +++ b/scripts/core/cli.py @@ -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) diff --git a/scripts/core/github.py b/scripts/core/github.py new file mode 100644 index 000000000..62c6ab13f --- /dev/null +++ b/scripts/core/github.py @@ -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 diff --git a/scripts/core/paths.py b/scripts/core/paths.py index 81c3af536..89d91c4eb 100644 --- a/scripts/core/paths.py +++ b/scripts/core/paths.py @@ -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 ("..", ".")) diff --git a/scripts/core_probe.py b/scripts/core_probe.py index 64c1dea6c..c2764164c 100644 --- a/scripts/core_probe.py +++ b/scripts/core_probe.py @@ -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) diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index 486f8d1a9..87cfb7038 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -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) diff --git a/scripts/dedup.py b/scripts/dedup.py index de3c83264..a03fe77da 100644 --- a/scripts/dedup.py +++ b/scripts/dedup.py @@ -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) diff --git a/scripts/diff_truth.py b/scripts/diff_truth.py index 173c2d193..f95217931 100644 --- a/scripts/diff_truth.py +++ b/scripts/diff_truth.py @@ -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) diff --git a/scripts/download.py b/scripts/download.py index a6234b659..cb8b7404e 100644 --- a/scripts/download.py +++ b/scripts/download.py @@ -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) diff --git a/scripts/export_native.py b/scripts/export_native.py index 200452c88..f022454ab 100644 --- a/scripts/export_native.py +++ b/scripts/export_native.py @@ -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) diff --git a/scripts/exporter/doubled.py b/scripts/exporter/doubled.py index 76952b214..30d857160 100644 --- a/scripts/exporter/doubled.py +++ b/scripts/exporter/doubled.py @@ -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 diff --git a/scripts/exporter/recalbox_exporter.py b/scripts/exporter/recalbox_exporter.py index 902b244b7..8fceb1350 100644 --- a/scripts/exporter/recalbox_exporter.py +++ b/scripts/exporter/recalbox_exporter.py @@ -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 diff --git a/scripts/exporter/retropie_exporter.py b/scripts/exporter/retropie_exporter.py index 2e89667ba..641138392 100644 --- a/scripts/exporter/retropie_exporter.py +++ b/scripts/exporter/retropie_exporter.py @@ -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 diff --git a/scripts/fetch_site_images.py b/scripts/fetch_site_images.py index 64496b7f1..360830dec 100644 --- a/scripts/fetch_site_images.py +++ b/scripts/fetch_site_images.py @@ -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) diff --git a/scripts/fileless_audit.py b/scripts/fileless_audit.py index edb2567a7..e165da60b 100644 --- a/scripts/fileless_audit.py +++ b/scripts/fileless_audit.py @@ -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) diff --git a/scripts/find_embedded.py b/scripts/find_embedded.py index 562370efe..5b4367ab3 100644 --- a/scripts/find_embedded.py +++ b/scripts/find_embedded.py @@ -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) diff --git a/scripts/find_pinned_revision.py b/scripts/find_pinned_revision.py index 5aac2ee2c..3c877db26 100644 --- a/scripts/find_pinned_revision.py +++ b/scripts/find_pinned_revision.py @@ -102,6 +102,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/game_rules.py b/scripts/game_rules.py index 1d12e38e7..f42565fd4 100644 --- a/scripts/game_rules.py +++ b/scripts/game_rules.py @@ -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) diff --git a/scripts/generate_db.py b/scripts/generate_db.py index 2d1f1d88c..f705debb8 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -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) diff --git a/scripts/generate_event_schema.py b/scripts/generate_event_schema.py index 5c209c12e..c33bbc832 100644 --- a/scripts/generate_event_schema.py +++ b/scripts/generate_event_schema.py @@ -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) diff --git a/scripts/generate_games_index.py b/scripts/generate_games_index.py index 10fd227f2..9ccd486a5 100644 --- a/scripts/generate_games_index.py +++ b/scripts/generate_games_index.py @@ -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, diff --git a/scripts/generate_installer_doc.py b/scripts/generate_installer_doc.py index 9e2816d19..6dfc9417d 100644 --- a/scripts/generate_installer_doc.py +++ b/scripts/generate_installer_doc.py @@ -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) diff --git a/scripts/generate_launcher_index.py b/scripts/generate_launcher_index.py index bf49c08fd..2046362c1 100644 --- a/scripts/generate_launcher_index.py +++ b/scripts/generate_launcher_index.py @@ -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) diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index f037f3217..a7409396b 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -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) diff --git a/scripts/generate_readme.py b/scripts/generate_readme.py index 7c3a9f9e1..23f107e75 100644 --- a/scripts/generate_readme.py +++ b/scripts/generate_readme.py @@ -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) diff --git a/scripts/generate_report_excerpt.py b/scripts/generate_report_excerpt.py index 57de15202..fdceda826 100644 --- a/scripts/generate_report_excerpt.py +++ b/scripts/generate_report_excerpt.py @@ -85,6 +85,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/generate_site.py b/scripts/generate_site.py index c00ae2ebe..4a5152aea 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -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) diff --git a/scripts/generate_truth.py b/scripts/generate_truth.py index 1245e56c2..e82abb654 100644 --- a/scripts/generate_truth.py +++ b/scripts/generate_truth.py @@ -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) diff --git a/scripts/identity.py b/scripts/identity.py index e801c8262..c2894fd2e 100644 --- a/scripts/identity.py +++ b/scripts/identity.py @@ -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) diff --git a/scripts/indexnow.py b/scripts/indexnow.py index 0ac638617..e41130f31 100644 --- a/scripts/indexnow.py +++ b/scripts/indexnow.py @@ -81,6 +81,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/list_platforms.py b/scripts/list_platforms.py index e4ec3232a..4d31a0ca3 100644 --- a/scripts/list_platforms.py +++ b/scripts/list_platforms.py @@ -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) diff --git a/scripts/make_demo.py b/scripts/make_demo.py index 4b9411834..d243673c7 100644 --- a/scripts/make_demo.py +++ b/scripts/make_demo.py @@ -516,6 +516,6 @@ def main() -> None: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/make_og_cards.py b/scripts/make_og_cards.py index 9f4e20c7f..ac95e3d99 100644 --- a/scripts/make_og_cards.py +++ b/scripts/make_og_cards.py @@ -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) diff --git a/scripts/make_site_icons.py b/scripts/make_site_icons.py index bc58499f1..f045664b1 100644 --- a/scripts/make_site_icons.py +++ b/scripts/make_site_icons.py @@ -191,6 +191,6 @@ def main() -> None: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/mame_ref_audit.py b/scripts/mame_ref_audit.py index 8c718f51a..9e4621758 100644 --- a/scripts/mame_ref_audit.py +++ b/scripts/mame_ref_audit.py @@ -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) diff --git a/scripts/manifestselect.py b/scripts/manifestselect.py index e489f2953..8e8a5c481 100644 --- a/scripts/manifestselect.py +++ b/scripts/manifestselect.py @@ -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, diff --git a/scripts/migrate.py b/scripts/migrate.py index 52c62c0d3..344958837 100644 --- a/scripts/migrate.py +++ b/scripts/migrate.py @@ -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) diff --git a/scripts/model/cliargs.py b/scripts/model/cliargs.py new file mode 100644 index 000000000..957b6d841 --- /dev/null +++ b/scripts/model/cliargs.py @@ -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()) diff --git a/scripts/model/composition.py b/scripts/model/composition.py new file mode 100644 index 000000000..52c6fe0f9 --- /dev/null +++ b/scripts/model/composition.py @@ -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" + ) diff --git a/scripts/model/database.py b/scripts/model/database.py new file mode 100644 index 000000000..e1c00e6a6 --- /dev/null +++ b/scripts/model/database.py @@ -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 diff --git a/scripts/model/declarations.py b/scripts/model/declarations.py new file mode 100644 index 000000000..2da8f9ed1 --- /dev/null +++ b/scripts/model/declarations.py @@ -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)) diff --git a/scripts/model/largefiles.py b/scripts/model/largefiles.py index 6bc3c6784..105dbeb2c 100644 --- a/scripts/model/largefiles.py +++ b/scripts/model/largefiles.py @@ -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: diff --git a/scripts/model/platforms.py b/scripts/model/platforms.py new file mode 100644 index 000000000..4a0ca13b7 --- /dev/null +++ b/scripts/model/platforms.py @@ -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/.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} diff --git a/scripts/model/profiles.py b/scripts/model/profiles.py new file mode 100644 index 000000000..e804daae2 --- /dev/null +++ b/scripts/model/profiles.py @@ -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] diff --git a/scripts/model/registry.py b/scripts/model/registry.py new file mode 100644 index 000000000..707cb9220 --- /dev/null +++ b/scripts/model/registry.py @@ -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 + ] diff --git a/scripts/model/sources.py b/scripts/model/sources.py new file mode 100644 index 000000000..f36acc5b4 --- /dev/null +++ b/scripts/model/sources.py @@ -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 diff --git a/scripts/model/systems.py b/scripts/model/systems.py new file mode 100644 index 000000000..8c27a8b54 --- /dev/null +++ b/scripts/model/systems.py @@ -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 diff --git a/scripts/model/targets.py b/scripts/model/targets.py new file mode 100644 index 000000000..76bc4cef0 --- /dev/null +++ b/scripts/model/targets.py @@ -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 --list-targets " + "lists the targets of one platform.") diff --git a/scripts/pack_probe.py b/scripts/pack_probe.py index 2594e8aac..4a9228956 100644 --- a/scripts/pack_probe.py +++ b/scripts/pack_probe.py @@ -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 diff --git a/scripts/packextras.py b/scripts/packextras.py index d797b4526..49be8ebed 100644 --- a/scripts/packextras.py +++ b/scripts/packextras.py @@ -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__) diff --git a/scripts/packpaths.py b/scripts/packpaths.py index 2514d16fc..f24869441 100644 --- a/scripts/packpaths.py +++ b/scripts/packpaths.py @@ -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 diff --git a/scripts/packresolve.py b/scripts/packresolve.py index 2307a36e4..493b60b55 100644 --- a/scripts/packresolve.py +++ b/scripts/packresolve.py @@ -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). diff --git a/scripts/packverify.py b/scripts/packverify.py index 39b5ebfcf..6bab7cec8 100644 --- a/scripts/packverify.py +++ b/scripts/packverify.py @@ -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", {}) diff --git a/scripts/pin_installer.py b/scripts/pin_installer.py index 07e366cf0..29ee4ac4e 100644 --- a/scripts/pin_installer.py +++ b/scripts/pin_installer.py @@ -77,6 +77,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 0b6e01074..e4d71468d 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -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) diff --git a/scripts/pr_checks.py b/scripts/pr_checks.py index 7e8ba5ce5..a40d5dc8f 100644 --- a/scripts/pr_checks.py +++ b/scripts/pr_checks.py @@ -120,6 +120,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/profile_sync.py b/scripts/profile_sync.py index f268b8824..a094f3416 100644 --- a/scripts/profile_sync.py +++ b/scripts/profile_sync.py @@ -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) diff --git a/scripts/provenance_report.py b/scripts/provenance_report.py index 1857de953..6c94c9d4a 100644 --- a/scripts/provenance_report.py +++ b/scripts/provenance_report.py @@ -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) diff --git a/scripts/refresh_data_dirs.py b/scripts/refresh_data_dirs.py index c5bac6971..147f9f1da 100644 --- a/scripts/refresh_data_dirs.py +++ b/scripts/refresh_data_dirs.py @@ -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) diff --git a/scripts/refresh_stale.py b/scripts/refresh_stale.py index 96bc37319..b381bebef 100755 --- a/scripts/refresh_stale.py +++ b/scripts/refresh_stale.py @@ -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) diff --git a/scripts/region.py b/scripts/region.py index 1e1c93b1e..b826b00af 100644 --- a/scripts/region.py +++ b/scripts/region.py @@ -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}) diff --git a/scripts/region_audit.py b/scripts/region_audit.py index ab147cfa4..909edcac8 100644 --- a/scripts/region_audit.py +++ b/scripts/region_audit.py @@ -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) diff --git a/scripts/region_check.py b/scripts/region_check.py index 51f8be5b3..365cdea84 100644 --- a/scripts/region_check.py +++ b/scripts/region_check.py @@ -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) diff --git a/scripts/release_notes.py b/scripts/release_notes.py index d0541f49f..1926dfff0 100644 --- a/scripts/release_notes.py +++ b/scripts/release_notes.py @@ -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) diff --git a/scripts/release_record.py b/scripts/release_record.py index c36b1a920..ffbce252c 100644 --- a/scripts/release_record.py +++ b/scripts/release_record.py @@ -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) diff --git a/scripts/resolve/archives.py b/scripts/resolve/archives.py new file mode 100644 index 000000000..382d335a9 --- /dev/null +++ b/scripts/resolve/archives.py @@ -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//) 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) diff --git a/scripts/resolve/categories.py b/scripts/resolve/categories.py index fd0b72c2f..1f2516447 100644 --- a/scripts/resolve/categories.py +++ b/scripts/resolve/categories.py @@ -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 diff --git a/scripts/resolve/content.py b/scripts/resolve/content.py new file mode 100644 index 000000000..d43d1287e --- /dev/null +++ b/scripts/resolve/content.py @@ -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" diff --git a/scripts/resolve/contentlayout.py b/scripts/resolve/contentlayout.py new file mode 100644 index 000000000..b9178ab1a --- /dev/null +++ b/scripts/resolve/contentlayout.py @@ -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/.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 + # /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 diff --git a/scripts/resolve/cores.py b/scripts/resolve/cores.py new file mode 100644 index 000000000..f4d27140a --- /dev/null +++ b/scripts/resolve/cores.py @@ -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}" diff --git a/scripts/resolve/datadirs.py b/scripts/resolve/datadirs.py new file mode 100644 index 000000000..553bef061 --- /dev/null +++ b/scripts/resolve/datadirs.py @@ -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() diff --git a/scripts/resolve/directories.py b/scripts/resolve/directories.py new file mode 100644 index 000000000..38a24b0f1 --- /dev/null +++ b/scripts/resolve/directories.py @@ -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 diff --git a/scripts/resolve/gamedata.py b/scripts/resolve/gamedata.py index 837f1d88e..5adb4d796 100644 --- a/scripts/resolve/gamedata.py +++ b/scripts/resolve/gamedata.py @@ -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 diff --git a/scripts/resolve/grouping.py b/scripts/resolve/grouping.py new file mode 100644 index 000000000..645858115 --- /dev/null +++ b/scripts/resolve/grouping.py @@ -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 diff --git a/scripts/resolve/launchers.py b/scripts/resolve/launchers.py index 16276b428..6d929eb84 100644 --- a/scripts/resolve/launchers.py +++ b/scripts/resolve/launchers.py @@ -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("/") diff --git a/scripts/resolve/layout.py b/scripts/resolve/layout.py new file mode 100644 index 000000000..b7d53fcf6 --- /dev/null +++ b/scripts/resolve/layout.py @@ -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//) 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 _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 diff --git a/scripts/resolve/localfile.py b/scripts/resolve/localfile.py new file mode 100644 index 000000000..78e7f2a48 --- /dev/null +++ b/scripts/resolve/localfile.py @@ -0,0 +1,1121 @@ +"""resolve_local_file and its stages: from a declared entry to a file of the collection.""" + +from __future__ import annotations + +import functools +import os +import re +import zipfile +from collections.abc import Iterator +from dataclasses import dataclass +from typing import Any + +from core.hashing import cut_md5_owner, md5_composite, parse_md5_list +from core.ziptools import check_inside_zip +from model.database import get_mame_clone_map +from model.profiles import CONTENT_CHECKS +from resolve.archives import ( + _covering_archives, + _holding_members, + _warn_unreadable_archive, + contents_members, +) +from resolve.content import ( + adler32_fits, + content_fits, + declared_hash_verdict, + declares_shape, + name_match_size_ok, + shape_fits, +) +from resolve.datadirs import _data_dir_tail, _resolve_in_data_dirs +from resolve.ownership import ( + _affinity_tokens, + _engine_tree, + _foreign_tree, + _maker_folder, + _own_tree, + _owner_tokens, + other_maker, + system_makers, +) + + +# One slot: the dict it was built from, its size then, and the folded view. +# Keyed by id() alone, a database freed and replaced by another at the same +# address got the old index back, and the case-insensitive step answered from +# a collection that no longer existed. +_casefold_index_cache: list[tuple[dict, int, dict[str, list[str]]]] = [] + + +def _casefold_name_index(by_name: dict) -> dict[str, list[str]]: + """Build (and cache) a casefolded view of the by_name index.""" + if _casefold_index_cache: + source, size, cached = _casefold_index_cache[0] + if source is by_name and size == len(by_name): + return cached + folded: dict[str, list[str]] = {} + for name, sha1s in by_name.items(): + folded.setdefault(name.casefold(), []).extend(sha1s) + _casefold_index_cache[:] = [(by_name, len(by_name), folded)] + return folded + + +HASH_EXACT_RESOLUTION_STATUSES = frozenset( + { + "sha1_exact", + "sha256_exact", + "crc32_exact", + "md5_exact", + "md5_composite_exact", + "zip_exact", + "data_dir_hash_exact", + } +) + + +def resolution_is_hash_exact(status: str) -> bool: + """Whether *status* proves content identity with a declared hash.""" + return status in HASH_EXACT_RESOLUTION_STATUSES + + +def _resolve_agnostic( + file_entry: dict, files_db: dict, has_strong_hash: bool +) -> tuple[str, str] | None: + """Any file of the right shape under the declared prefix. + + Some cores accept whatever filename sits in their BIOS directory, so the + shape (a size or a size range) is all that identifies a candidate. A + declared hash outranks that, and stops this step being reached. + """ + if not file_entry.get("agnostic") or has_strong_hash: + return None + prefix = file_entry.get("agnostic_path_prefix", "") + if not prefix: + return None + for entry in files_db.values(): + path = entry.get("path", "") + if not path.startswith(prefix): + continue + if os.path.exists(path) and shape_fits(file_entry, path, entry.get("size", 0)): + return path, "agnostic_fallback" + return None + + +_VARIANT_SUFFIX = re.compile(r"\.[0-9a-f]{8}$") + + +def variant_base_name(name: str) -> str: + """The name a .variants/ copy stands in for: naomi2.zip.da79eca4 -> naomi2.zip. + + Only an eight-hex-digit suffix is a variant tag. A variant stored under + its plain name (.variants/aes.zip) already is that name. + """ + return _VARIANT_SUFFIX.sub("", name) + + +def _rank_tail_candidates( + candidates: list[str], start: int, tail: str, files_db: dict, owners: set[str], + asker: frozenset[str] = frozenset(), +) -> list[str]: + """Order the files a destination tail designates, the likeliest first. + + A tail found in another emulator's tree is that emulator's asset, not + evidence about this entry, whatever its length. A full tail claimed + twice goes to the file whose path carries the least on top of the + destination, then to the owner's own copy (super3's Games.xml was served + to Supermodel-Dojo by index order alone), then to any copy outside + another emulator's tree (upstream PCSX2 took EmuCoreX's GameIndex.yaml + over the system directory's). + """ + def path_of(sha1: str) -> str: + return files_db.get(sha1, {}).get("path", "") + + # Another emulator's tree answers that emulator's entry, at any tail + # length when a profile asks: lrps2 names no hash for + # pcsx2/resources/GameIndex.yaml, and the only full-tail copy was ARMSX2's, + # which then counted as path proof and replaced the GameIndex RetroArch + # pins on every desktop target. A platform's own declaration has no + # asker, and the tree whose path is its destination still answers it. + if start or asker: + # The database keeps one path per content. When that path does not + # end with the tail, the tail was indexed from an identical copy + # elsewhere, and the recorded path says nothing about whose tree it + # sits in: PCSX2x6's RedumpDatabase.yaml has EmuCoreX's bytes. + candidates = [ + h for h in candidates + if not path_of(h).endswith("/" + tail) + or not _foreign_tree(path_of(h), owners if start else set(asker)) + ] + if len(candidates) < 2: + return candidates + depth = len(tail.split("/")) + return sorted( + candidates, + key=lambda h: ( + len(path_of(h).split("/")) - depth, + not owners & _affinity_tokens(path_of(h).rsplit("/", 1)[0]), + _foreign_tree(path_of(h), owners), + ), + ) + + +def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str]: + """Same-named candidates, the likeliest first. + + A name step without a tie-break took whichever path sorted first: the + TheXTech coin.ogg for Syobon Action, a Hurrican sound for ARMSX2, the + 1 MB CM-32L PCM ROM for ScummVM's 512 KB MT32_PCM.ROM. A size the entry + declares orders the candidates first (ordering rejects nothing, so an + unvalidated size keeps its informative status). Then the destination's + directories and the profile that asks name where its own copy lives. The + order is otherwise kept. + """ + if len(paths) < 2: + return paths + hint = dest_hint or file_entry.get("path") or file_entry.get("destination") or "" + wanted = _affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "") + owners = _owner_tokens(file_entry) + sized = declares_shape(file_entry) + + def score(path: str) -> tuple[int, bool, bool, bool, int]: + fits = 0 + if sized and os.path.exists(path): + fits = int(shape_fits(file_entry, path)) + tokens = _affinity_tokens(path.rsplit("/", 1)[0]) + # The owner's own copy ranks above any shared tree segment: NetherSX2's + # shaders/common/ beat armsx2's own fxaa.fx on two directory tokens. + # Another emulator's own tree ranks below everything else. + # A game's folder under Game Engines/ holds that game's data: for a + # name-only match, a neutral copy goes first. hypseus-singe, + # flycast-dojo, lindbergh-loader and vvvvvv took C-Dogs' 98-line + # gamecontrollerdb.txt by index order. + return ( + fits, bool(owners & tokens), not _foreign_tree(path, owners | wanted), + not _engine_tree(path, owners | wanted), len(wanted & tokens), + ) + + return sorted(paths, key=score, reverse=True) + + +Resolution = tuple[str, str] + + +@dataclass(frozen=True) +class _Lookup: + """One entry as resolve_local_file reads it: its names and declared hashes.""" + + file_entry: dict + db: dict + dest_hint: str + name: str + zipped_file: str | None + names_to_try: list[str] + own_names: list[str] + md5_list: list[str] + sha1_candidates: list[str] + sha256_candidates: list[str] + crc_candidates: dict[str, None] + declared_size: Any + files_db: dict + by_name: dict + by_path_suffix: dict + composite_only: bool + + @property + def has_strong_hash(self) -> bool: + return bool( + self.sha1_candidates or self.sha256_candidates or self.md5_list or self.crc_candidates + ) + + +def _lookup_names(name: str, aliases: list, dest_hint: str) -> tuple[list[str], list[str]]: + """The names an entry answers to, and the part of them that is its own.""" + names_to_try = [name] + [a for a in aliases if a != name] + + # When name contains a path separator (e.g. "res/tilemap.bin"), also + # try the basename since by_name indexes filenames without directories + if "/" in name: + name_base = name.rsplit("/", 1)[-1] + if name_base and name_base not in names_to_try: + names_to_try.append(name_base) + + # When dest_hint contains a path, also try its basename as a name + # (handles emulator profiles where name: is descriptive and path: is + # the actual filename, e.g. name: "MDA font ROM", path: "mda.rom") + own_names = list(names_to_try) + if dest_hint: + hint_base = dest_hint.rsplit("/", 1)[-1] if "/" in dest_hint else dest_hint + if hint_base and hint_base not in names_to_try: + names_to_try.append(hint_base) + return names_to_try, own_names + + +def _lookup( + file_entry: dict, db: dict, dest_hint: str, md5_list: list[str], *, composite_only: bool +) -> _Lookup: + """Read the names and every declared hash of an entry once.""" + sha1 = file_entry.get("sha1") + name = file_entry.get("name", "") + names_to_try, own_names = _lookup_names(name, file_entry.get("aliases", []), dest_hint) + sha1_candidates = [ + str(value).strip().lower() + for value in (sha1 if isinstance(sha1, list) else [sha1] if sha1 else []) + if str(value).strip() + ] + sha256_raw = file_entry.get("sha256") + sha256_values = sha256_raw if isinstance(sha256_raw, list) else [sha256_raw] + sha256_candidates = [ + candidate.strip().lower() + for value in sha256_values + if value + for candidate in str(value).split(",") + if len(candidate.strip()) == 64 + ] + # One value, a list, or a comma-separated string, like the other hashes. + crc_values = file_entry.get("crc32") or [] + # Kept in the order declared, which is the order a lookup tries them. + crc_candidates = dict.fromkeys( + candidate.strip().lower().removeprefix("0x") + for value in (crc_values if isinstance(crc_values, list) else [crc_values]) + for candidate in str(value).split(",") + if candidate.strip() + ) + indexes = db.get("indexes", {}) + return _Lookup( + file_entry=file_entry, + db=db, + dest_hint=dest_hint, + name=name, + zipped_file=file_entry.get("zipped_file"), + names_to_try=names_to_try, + own_names=own_names, + md5_list=md5_list, + sha1_candidates=sha1_candidates, + sha256_candidates=sha256_candidates, + crc_candidates=crc_candidates, + declared_size=file_entry.get("size"), + files_db=db.get("files", {}), + by_name=indexes.get("by_name", {}), + by_path_suffix=indexes.get("by_path_suffix", {}), + composite_only=composite_only, + ) + + +def _record_match_status(q: _Lookup, match_sha1: str) -> str | None: + """Return hash evidence when a DB record satisfies every declaration.""" + entry = q.files_db.get(match_sha1) + if not entry: + return None + statuses: list[str] = [] + if q.sha1_candidates: + if match_sha1.lower() not in q.sha1_candidates: + return None + statuses.append("sha1_exact") + if q.sha256_candidates: + if str(entry.get("sha256", "")).lower() not in q.sha256_candidates: + return None + statuses.append("sha256_exact") + # With zipped_file the MD5 identifies the member, not the container. + if q.md5_list and not q.zipped_file: + actual_md5 = str(entry.get("md5", "")).lower() + if actual_md5 not in q.md5_list: + return None + statuses.append("md5_exact") + if q.crc_candidates: + if str(entry.get("crc32", "")).lower() not in q.crc_candidates: + return None + if q.declared_size is not None: + allowed_sizes = ( + q.declared_size if isinstance(q.declared_size, list) else [q.declared_size] + ) + if entry.get("size") not in allowed_sizes: + return None + statuses.append("crc32_exact") + return statuses[0] if statuses else None + + +def _held_record(q: _Lookup, match_sha1: str) -> Resolution | None: + """The record's path and evidence, when it satisfies the entry and is on disk.""" + path = q.files_db[match_sha1]["path"] + status = _record_match_status(q, match_sha1) + if status and os.path.exists(path): + return path, status + return None + + +def _by_sha1(q: _Lookup) -> Resolution | None: + """SHA1 exact match (accept list-valued sha1 from profiles).""" + for cand in q.sha1_candidates: + if cand in q.files_db: + found = _held_record(q, cand) + if found: + return found + return None + + +def _by_sha256(q: _Lookup) -> Resolution | None: + """SHA256 exact match, through the by_sha256 index.""" + if not q.sha256_candidates: + return None + by_sha256 = q.db.get("indexes", {}).get("by_sha256", {}) + for cand in q.sha256_candidates: + match = by_sha256.get(cand) + if match and match in q.files_db: + found = _held_record(q, match) + if found: + return found + return None + + +def _by_crc32(q: _Lookup) -> Resolution | None: + """CRC32 lookup, only when no stronger hash is declared.""" + if ( + not q.crc_candidates + or q.zipped_file + or q.md5_list + or q.sha1_candidates + or q.sha256_candidates + ): + return None + by_crc32 = q.db.get("indexes", {}).get("by_crc32", {}) + crc_matches: list[Resolution] = [] + for crc in q.crc_candidates: + match = by_crc32.get(crc) + if match and match in q.files_db: + found = _held_record(q, match) + if found: + crc_matches.append(found) + # A primary copy over a .variants/ one, as everywhere else. + for path, status in crc_matches: + if "/.variants/" not in path: + return path, status + if crc_matches: + return crc_matches[0] + return None + + +def _md5_hits(q: _Lookup) -> Iterator[tuple[str, str, str]]: + """Each held record a declared md5 names: path, evidence, md5 asked. + + Skipped for zipped_file: the md5 is the inner ROM's, not the container's. + """ + if not q.md5_list or q.zipped_file or q.composite_only: + return + by_md5 = q.db.get("indexes", {}).get("by_md5", {}) + for md5_candidate in q.md5_list: + sha1_match = by_md5.get(md5_candidate) + if sha1_match and sha1_match in q.files_db: + found = _held_record(q, sha1_match) + if found: + yield found[0], found[1], md5_candidate + + +def _named_or_variant(names: frozenset[str], candidate_path: str) -> bool: + """Whether a path's file name is one of these names, or a variant of one.""" + bn = os.path.basename(candidate_path) + if bn in names: + return True + # .variants/ pattern: filename like "neogeo.zip.fc398ab4" + return any(bn.startswith(n + ".") for n in names) + + +def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> list[str]: + """The records a destination tail names, ranked, ambiguity read.""" + candidates = _rank_tail_candidates( + q.by_path_suffix.get(tail, []), start, tail, q.files_db, owners, + frozenset(_owner_tokens(q.file_entry)), + ) + raw = q.by_path_suffix.get(tail, []) + if start and len(raw) > 1: + # Ambiguity is read before the foreign trees are set aside: + # PCSX2x6's bin/resources/GameIndex.yaml met four copies + # under resources/GameIndex.yaml, three in other emulators' + # trees, and the fourth (PCSX2's console database, not + # PCSX2x6's arcade one) passed for proof. Only the asker's own + # tree still answers a tail several files share. + candidates = [ + h for h in candidates + if _own_tree(q.files_db.get(h, {}).get("path", ""), owners) + ] + return candidates + + +def _tail_match(q: _Lookup, candidates: list[str]) -> Resolution | None: + """The first candidate of a tail on disk that the entry accepts.""" + for match_sha1 in candidates: + if match_sha1 not in q.files_db: + continue + path = q.files_db[match_sha1]["path"] + if not os.path.exists(path): + continue + if not q.has_strong_hash: + # A path names the file, the size the code checks still + # bounds it, as on the name step: ZEsarUX's 48 KB + # cpc6128.rom is not cap32's 32 KB one at the same tail. + if not name_match_size_ok( + q.file_entry, q.files_db[match_sha1].get("size") + ) or not adler32_fits(q.file_entry, path, q.db) or not content_fits( + q.file_entry, path + ): + continue + return path, "path_exact" + status = _record_match_status(q, match_sha1) + if status: + return path, status + return None + + +def _by_path_suffix(q: _Lookup) -> tuple[Resolution | None, bool]: + """The file at the destination's tail, and whether the indexed one is absent.""" + own_file_absent = False + if not (q.dest_hint and q.by_path_suffix): + return None, own_file_absent + # A destination is written from the emulator's point of view + # ("pcsx2/resources/GameIndex.yaml") and the index from the repo's + # layout, so the two meet on a tail rather than on the whole string. + # Longest tail first, and never down to the bare filename: that is the + # weaker step below, and five files answer to GameIndex.yaml. + # Two kinds of ambiguity appear once every tail is indexed. A + # shortened tail can be claimed by several emulators shipping the same + # asset tree, and it then proves nothing: skip it. The full tail can be + # claimed twice as well, one storing it at the root of its own + # directory and one nested deeper. There the file whose path carries + # the least on top of the destination is the one that IS the + # destination. + # The descent drops at most one leading segment. A destination and the + # tree differ by the wrapper directory at most. Beyond that the tail + # stops describing this file and starts describing whichever emulator + # happens to store the same asset tree. + hint_parts = q.dest_hint.split("/") + # The asking profile and the destination's own directories both name + # whose tree a copy may come from. + owners = _owner_tokens(q.file_entry) | _affinity_tokens("/".join(hint_parts[:-1])) + for start in range(min(2, len(hint_parts) - 1)): + candidates = _tail_candidates(q, start, "/".join(hint_parts[start:]), owners) + if start and len(candidates) > 1: + continue + # The index names the file this destination designates. Not on + # disk, it is a release asset the checkout does not hold, and no + # other file of that name is it. + if not start and candidates and not any( + os.path.exists(q.files_db.get(h, {}).get("path", "")) + for h in candidates + ): + own_file_absent = True + found = _tail_match(q, candidates) + if found: + return found, own_file_absent + return None, own_file_absent + + +def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution | None: + """The same tail in a data directory, for a platform's hashless entry.""" + # by_path_suffix indexes bios/ + # only, so AmberELEC's Machines/MSX - Arabic/config.ini fell through to + # the name step and got msx-emu's ColecoVision config.ini, while + # data/bluemsx held blueMSX's own at that very path. A platform + # declaration is resolved without a hint, and its destination is that + # path. The descent and the ambiguity rule are those of the bios/ tails. + # A profile's entry is not asked here: it names its owner, the name step + # sends it to its data directories when another emulator's copy answers, + # and a dump it declares outranks the free one its tree bundles at the + # same path (Dolphin's dsp_coef.bin over Sys/GC's). + tail_hint = q.dest_hint or str(q.file_entry.get("destination") or "") + if ( + tail_hint + and data_dir_registry + and not q.has_strong_hash + and not _owner_tokens(q.file_entry) + ): + hit = _data_dir_tail(tail_hint, data_dir_registry, q.file_entry, q.db) + if hit: + return hit, "path_exact" + return None + + +def _name_size_ok(q: _Lookup, match_sha1: str) -> bool: + """Whether a record found by name has the shape the entry's code checks.""" + record = q.files_db.get(match_sha1, {}) + return name_match_size_ok(q.file_entry, record.get("size")) and adler32_fits( + q.file_entry, record.get("path", ""), q.db + ) and content_fits(q.file_entry, record.get("path", "")) + + +def _exact_name_candidates(q: _Lookup) -> list[str]: + """The held files answering to the entry's names, exact casing.""" + candidates: list[str] = [] + # The entry's own names first, the destination's basename only when + # none of them answers. melonDS Nightly's dsi_nand.bin is read at + # dsi/nand.bin: with the DSi image absent from the checkout, the + # basename let the Wii nand.bin outrank the entry's own DSi variant. + # A name whose held file no declaration proves, while declarations + # of that name prove another dump beside it, means that dump: the + # DSi devkit boot ROMs filed as dsi_bios7.bin went to RetroBat. + by_proven_name = q.db.get("indexes", {}).get("by_proven_name", {}) + for tier in (q.own_names, q.names_to_try[len(q.own_names):]): + for try_name in tier: + for match_sha1 in ( + by_proven_name.get(try_name) or q.by_name.get(try_name, []) + ): + if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + path = q.files_db[match_sha1]["path"] + if os.path.exists(path) and path not in candidates: + candidates.append(path) + if candidates: + break + return candidates + + +def _add_variant_primaries(q: _Lookup, candidates: list[str]) -> None: + """Add the primaries that variants answering the exact casing stand in for.""" + # Only variants answer the exact casing, but the primary they + # stand in for may be stored under another one: x1 asked for + # IPLROM.X1 and got Recalbox's second md5 while iplrom.x1, the + # dump every platform pins, sat in the same directory. A primary + # counts here only in a variant's own directory and under its own + # file name: an alias (iplrom.x1t names a font in System.dat) or + # another machine's font.rom is not that file. + homes = {p.split("/.variants/", 1)[0] for p in candidates} + folded = _casefold_name_index(q.by_name) + for try_name in q.names_to_try: + wanted = try_name.rsplit("/", 1)[-1].casefold() + for match_sha1 in folded.get(try_name.casefold(), []): + path = q.files_db.get(match_sha1, {}).get("path", "") + if ( + "/.variants/" not in path + and os.path.dirname(path) in homes + and os.path.basename(path).casefold() == wanted + and _name_size_ok(q, match_sha1) + and os.path.exists(path) + and path not in candidates + ): + candidates.append(path) + + +def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str]) -> None: + """Add the held files answering to the entry's names in another casing.""" + # Case-insensitive fallback: upstream platforms disagree on + # casing (VEC_MineStorm.vec vs VEC_Minestorm.vec). Two casings + # can name two contents (FONT.ROM and font.rom), so this only + # runs when no casing matches exactly, or when only another + # emulator's tree does: xm6typeg got XM6 Utility's synthesized + # SCSIINROM.DAT while the X68000 dump sat as scsiinrom.dat. + # Another casing in another emulator's tree proves nothing: + # reminiscence's music module reunion took skyline's + # zoneinfo/Indian/Reunion. + folded = _casefold_name_index(q.by_name) + for try_name in q.names_to_try: + for match_sha1 in folded.get(try_name.casefold(), []): + if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + path = q.files_db[match_sha1]["path"] + if _foreign_tree(path, owners): + continue + if os.path.exists(path) and path not in candidates: + candidates.append(path) + + +def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> list[str]: + """The candidates filed under the system's maker, or its shadowed aliases.""" + candidates = [p for p in candidates if not other_maker(p, makers, q.db)] + if candidates: + return candidates + # The name belongs to another maker's file here. An emulator + # of this system may still read it as an alias of one of its + # own files, an alias by_name leaves out because a primary + # already carries the name: QUASI88 reads DISK.ROM as + # n88sub.rom. + shadowed = q.db.get("indexes", {}).get("by_shadowed_alias", {}) + for try_name in q.own_names: + for match_sha1 in shadowed.get(try_name, []): + path = q.files_db.get(match_sha1, {}).get("path", "") + if ( + _maker_folder(path, str(q.db.get("bios_dir") or "bios")) + in makers + and _name_size_ok(q, match_sha1) + and os.path.exists(path) + and path not in candidates + ): + candidates.append(path) + return candidates + + +def _choose_by_name( + q: _Lookup, + candidates: list[str], + owners: set[str], + exact_foreign: bool, + data_dir_registry: dict | None, +) -> Resolution | None: + """The best of the files a name step found, or the data directory's own.""" + if q.zipped_file: + candidates = [p for p in candidates if ".zip" in os.path.basename(p)] + members = q.file_entry.get("members") or contents_members(q.file_entry) + if members or (len(candidates) > 1 and q.name.casefold().endswith(".zip")): + # Another emulator's own copy takes no part in the ranking: + # Demul's naomi.zip holds more NAOMI BIOS rows than any MAME + # set and broke the superset the MAME cores were served. + candidates = [ + p for p in candidates if not _foreign_tree(p, owners) + ] or candidates + if members: + candidates = _holding_members(candidates, members) + elif len(candidates) > 1 and q.name.casefold().endswith(".zip"): + candidates = _covering_archives(candidates) + candidates = _by_affinity(candidates, q.file_entry, q.dest_hint) + best = candidates[0] if candidates else "" + # A copy outside another emulator's tree comes first: the + # affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served + # upstream PCSX2 the patches.zip of ARMSX2. + candidates = [ + p for p in candidates if not _foreign_tree(p, owners) + ] or candidates + primary = [p for p in candidates if "/.variants/" not in p] + if not (primary or candidates): + return None + chosen = primary[0] if primary else candidates[0] + # The best of them is another emulator's own copy, served or + # set aside: the name says nothing about this profile's file, + # and a data directory it reads may hold it. Dolphin got + # Dolphin-MMJR's codehandler.bin while data/dolphin-sys held + # its own, and blueMSX got the 16 KB RS232.ROM once msx-emu's + # 8 KB copy was set aside, while data/bluemsx held its own, + # and MSX2P.ROM of another dump once only msx-emu answered + # the exact casing. + if data_dir_registry and (exact_foreign or _foreign_tree(best, owners)): + hit, _mismatch = _resolve_in_data_dirs( + q.names_to_try, data_dir_registry, + functools.partial( + declared_hash_verdict, + has_strong_hash=False, + sha1_candidates=set(), + sha256_candidates=set(), + md5_list=[], + crc_candidates=set(), + zipped_file=q.zipped_file, + declared_size=q.declared_size, + file_entry=q.file_entry, + db=q.db, + ), + ) + if hit: + return hit + return chosen, "name_exact" + + +def _by_name( + q: _Lookup, makers: frozenset[str], data_dir_registry: dict | None +) -> tuple[Resolution | None, bool]: + """Any file with that name or alias (existence check). + + The second value says the name proved nothing, which makes the entry + unsourceable for the steps after this one. + """ + candidates = _exact_name_candidates(q) + if candidates and all("/.variants/" in p for p in candidates): + _add_variant_primaries(q, candidates) + owners = _owner_tokens(q.file_entry) + # Only another emulator's tree answers the exact casing: what it + # holds there says nothing about this entry's file. + exact_foreign = bool(candidates) and all( + _foreign_tree(p, owners) for p in candidates + ) + if not candidates or exact_foreign: + _add_casefold_candidates(q, candidates, owners) + # A platform entry names no profile, but a system that lists its + # cores says whose files it asks for. A name only another emulator's + # tree answers is no evidence, and the data directories hold those + # emulators' trees too: EmuELEC's VVVVVV data.zip was served xrick's + # archive of the same name, then xrick's data directory copy. + core_owners = { + token + for core in q.file_entry.get("platform_cores") or () + for token in _affinity_tokens(str(core)) + } + if ( + not owners + and core_owners + and candidates + and all(_foreign_tree(p, core_owners) for p in candidates) + ): + return None, True + if makers and candidates: + candidates = _same_maker(q, candidates, makers) + if not candidates: + return None, False + return _choose_by_name(q, candidates, owners, exact_foreign, data_dir_registry), False + + +def _named_candidates(q: _Lookup, makers: frozenset[str]) -> list[tuple[str, str, int | None]]: + """Every held file of the entry's names: path, md5, size.""" + named: list[tuple[str, str, int | None]] = [] + seen_paths = set() + for try_name in q.names_to_try: + for match_sha1 in q.by_name.get(try_name, []): + if match_sha1 in q.files_db: + entry = q.files_db[match_sha1] + path = entry["path"] + if os.path.exists(path) and path not in seen_paths: + seen_paths.add(path) + named.append( + (path, entry.get("md5", ""), entry.get("size")) + ) + + if q.zipped_file: + named = [c for c in named if ".zip" in os.path.basename(c[0])] + # Another maker's file is no mismatch of this one, it is another file. + named = [c for c in named if not other_maker(c[0], makers, q.db)] + # A size the emulator itself verifies settles a name collision, so a + # candidate that fits is preferred over one that does not: "ROM" answers + # both an Apple IIgs image and a Macintosh one. It ranks rather than + # excludes, because a present file of the wrong size is reported as + # present and untested, and dropping it would report it as absent. + sized = [ + c for c in named + if name_match_size_ok(q.file_entry, c[2]) and content_fits(q.file_entry, c[0]) + ] + if sized: + named = sized + return named + + +def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution | None: + """A named file whose md5, or archive composite, is a declared one. + + Sorts *named* in place for a composite-only entry, as the steps after + this one read it. + """ + md5_set = set(q.md5_list) + if not md5_set or q.sha1_candidates or q.sha256_candidates or q.crc_candidates: + return None + if q.composite_only: + named.sort(key=lambda c: "/.variants/" in c[0]) + for path, db_md5, _size in named: + if ".zip" in os.path.basename(path): + try: + composite = md5_composite(path).lower() + # A zipped_file md5 is the member's: one member of + # another name has the same composite, and Batocera + # looks the member up by name. + if composite in md5_set and ( + not q.zipped_file + or check_inside_zip(path, q.zipped_file, composite) == "ok" + ): + return path, "md5_composite_exact" + except (zipfile.BadZipFile, OSError) as exc: + _warn_unreadable_archive(path, exc) + if db_md5.lower() in md5_set and not q.composite_only: + return path, "md5_exact" + return None + + +def _zipped_named( + q: _Lookup, named: list[tuple[str, str, int | None]], zipped_file: str +) -> Resolution | None: + """When zipped_file is set, only accept candidates that contain it.""" + valid = [] + for path, m, size in named: + try: + with zipfile.ZipFile(path) as zf: + inner_names = {n.casefold() for n in zf.namelist()} + if zipped_file.casefold() in inner_names: + valid.append((path, m, size)) + except (zipfile.BadZipFile, OSError) as exc: + _warn_unreadable_archive(path, exc) + # The archive whose member carries the declared md5 is the one: + # neogeo.zip is held twice, each with its own sfix.sfix, and the + # first by name was returned as a mismatch while the other matched. + for path, _m, _size in sorted(valid, key=lambda c: "/.variants/" in c[0]): + if any(check_inside_zip(path, zipped_file, md5) == "ok" for md5 in q.md5_list): + return path, "zip_exact" + if valid: + primary = [c[0] for c in valid if "/.variants/" not in c[0]] + return (primary[0] if primary else valid[0][0]), "hash_mismatch" + # No candidate contains the zipped_file: fall through to step 5 + return None + + +def _ranked_mismatch(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution: + """The named file the entry would take, reported as a hash mismatch.""" + ordered = _by_affinity([c[0] for c in named], q.file_entry, q.dest_hint) + primary = [c for c in ordered if "/.variants/" not in c] + return (primary[0] if primary else ordered[0]), "hash_mismatch" + + +def _by_zip_contents(q: _Lookup, zip_contents: dict | None) -> Resolution | None: + """zipped_file content match via pre-built index. + + Last resort: matches inner ROM MD5 across ALL ZIPs in the repo, so only + used when name-based resolution failed entirely. + """ + if not ( + q.zipped_file + and q.md5_list + and zip_contents + and not (q.sha1_candidates or q.sha256_candidates or q.crc_candidates) + ): + return None + for md5_candidate in q.md5_list: + if md5_candidate in zip_contents: + zip_sha1 = zip_contents[md5_candidate] + if zip_sha1 in q.files_db: + path = q.files_db[zip_sha1]["path"] + if os.path.exists(path): + return path, "zip_exact" + return None + + +def _by_mame_clone( + q: _Lookup, zip_contents: dict | None, depth: int, data_dir_registry: dict | None +) -> Resolution | None: + """If a file was deduped, resolve via canonical.""" + clone_map = get_mame_clone_map(q.db.get("bios_dir")) + canonical = clone_map.get(q.name) + if not canonical or canonical == q.name: + return None + canonical_entry = { + field: q.file_entry[field] + for field in ( + "size", "min_size", "max_size", "size_multiple", "validation", + *sorted(CONTENT_CHECKS), + ) + if field in q.file_entry + } + canonical_entry["name"] = canonical + result = resolve_local_file( + canonical_entry, + q.db, + zip_contents, + q.dest_hint, + _depth=depth + 1, + data_dir_registry=data_dir_registry, + ) + if result[0] and result[1] != "hash_mismatch": + return result[0], "mame_clone" + return None + + +def _in_data_dirs(q: _Lookup, data_dir_registry: dict) -> tuple[Resolution | None, str | None]: + """Data directory fallback: scan data/ caches for matching filename.""" + verdict = functools.partial( + declared_hash_verdict, + has_strong_hash=q.has_strong_hash, + sha1_candidates=q.sha1_candidates, + sha256_candidates=q.sha256_candidates, + md5_list=q.md5_list, + crc_candidates=set(q.crc_candidates), + zipped_file=q.zipped_file, + declared_size=q.declared_size, + file_entry=q.file_entry, + db=q.db, + ) + return _resolve_in_data_dirs(q.names_to_try, data_dir_registry, verdict) + + +def _resolve_layout( + file_entry: dict, + db: dict, + zip_contents: dict | None, + dest_hint: str, + *, + depth: int, + data_dir_registry: dict | None, +) -> tuple[str | None, str]: + """Resolve an entry whose launcher moves it, at both destinations.""" + layout = file_entry.get("layout_path") + plain = {k: v for k, v in file_entry.items() if k != "layout_path"} + # A destination outside the BIOS tree says nothing of the collection: + # EmuELEC's roms/mame/konamigv.zip is not bios/Arcade/MAME's set. + outside = file_entry.get("unprefixed") or file_entry.get("root") + answers = [ + resolve_local_file( + plain, db, zip_contents, dest_hint=hint, _depth=depth, + data_dir_registry=data_dir_registry, + ) + for hint in ((str(layout),) if outside else (dest_hint, str(layout))) + ] + for found in answers: + if found[0] is not None and ( + resolution_is_hash_exact(found[1]) or found[1] == "path_exact" + ): + return found + for found in answers: + if found[0] is not None and found[1] not in ("not_found", "hash_mismatch"): + return found + return next((found for found in answers if found[0] is not None), answers[0]) + + +def _entry_hint(file_entry: dict, dest_hint: str) -> str: + """The destination tail the collection indexes the entry under.""" + # A platform that hands each core a system directory of its own (MinUI's + # Bios//) writes that folder in front of the core's path. The tail + # the collection indexes is the core's path alone. + system_dir = file_entry.get("system_dir") + if system_dir and dest_hint.startswith(f"{system_dir}/"): + dest_hint = dest_hint[len(system_dir) + 1:] + return dest_hint + + +def _name_as_hint(name: str, dest_hint: str) -> str: + """A name written with its directory is the destination when no path is given.""" + # gam4980/E.BIN resolved by its basename took another model's OS + # in verify --emulator and the emulator pack, while the platform pack, + # which passes the destination, served the GAM4980's. + if not dest_hint and "/" in name.strip("/"): + return name + return dest_hint + + +def resolve_local_file( + file_entry: dict, + db: dict, + zip_contents: dict | None = None, + dest_hint: str = "", + _depth: int = 0, + data_dir_registry: dict | None = None, +) -> tuple[str | None, str]: + """Resolve a BIOS file to its local path using database.json. + + Single source of truth for file resolution, used by both verify.py + and generate_pack.py. Does NOT handle storage tiers (external/user_provided) + or release assets - callers handle those. + + dest_hint: optional destination path (e.g., "GC/USA/IPL.bin") used to + disambiguate when multiple files share the same name. Matched against + the by_path_suffix index built from the repo's directory structure. + + Returns ``(local_path, status)``. Statuses describe the evidence used: + ``sha1_exact``, ``sha256_exact``, ``crc32_exact``, ``md5_exact``, + ``md5_composite_exact``, ``zip_exact``, ``path_exact``, ``name_exact``, + ``hash_mismatch`` or ``not_found`` (plus documented fallback statuses). + + A path or filename is never allowed to override a declared strong hash. + """ + dest_hint = _entry_hint(file_entry, dest_hint) + # A launcher that moves the layout (EmuDeck links azahar's sysdata to + # bios/azahar/keys) changes where the file goes, not the tail the + # collection indexes it under. Both are asked, and the stronger proof + # wins: a content or path match over a name, the destination on a tie. + layout = file_entry.get("layout_path") + if layout and layout != dest_hint: + return _resolve_layout( + file_entry, db, zip_contents, dest_hint, + depth=_depth, data_dir_registry=data_dir_registry, + ) + md5_list = parse_md5_list(file_entry.get("md5")) + by_md5 = db.get("indexes", {}).get("by_md5", {}) + # A value cut short stands for the one held md5 it starts, and only + # then (cut_md5_owner): the dump it names is still name-guarded below. + cut_owners = { + cut: owner for cut in md5_list + if len(cut) < 32 and (owner := cut_md5_owner(cut, by_md5)) + } + # A frontend that hashes an archive by its members (Recalbox) never reads + # the container's own md5: neocd.bin's md5 is also the composite of a + # one-member neocdz.zip, and the raw ROM shipped under the archive's name. + composite_only = file_entry.get("zip_digest") == "composite" + q = _lookup( + file_entry, db, _name_as_hint(file_entry.get("name", ""), dest_hint), + [cut_owners.get(value, value) for value in md5_list], + composite_only=composite_only, + ) + has_strong_hash = q.has_strong_hash + # Guard of step 2: only accept if the found file's name matches the + # requested name (or is a .variants/ derivative). Prevents + # cross-contamination when an unrelated file happens to share the same + # MD5 in the index. + _md5_name_ok = functools.partial(_named_or_variant, frozenset(q.names_to_try)) + + found = ( + # 1. SHA1 exact match (accept list-valued sha1 from profiles) + _by_sha1(q) + # 1b. SHA256 exact match (profiles hashed from sources that publish + # sha256, e.g. MesenCE). A full sha256 is a strong identifier. + or _by_sha256(q) + # 1c. CRC32 lookup, only when no stronger hash is declared. A declared + # size confirms it when available. A handful of emulators validate CRC32 + # alone, so those entries retain the same (weaker) evidence as the core. + or _by_crc32(q) + # 2. MD5 direct lookup (skip for zipped_file: md5 is inner ROM, not container) + # A full md5 as declared is a strong identifier: trusted without + # name guard. One completed from a cut value still needs the name + # check to avoid cross-contamination. + or next( + ( + (path, status) + for path, status, md5_candidate in _md5_hits(q) + if md5_candidate not in cut_owners.values() or _md5_name_ok(path) + ), + None, + ) + ) + if found: + return found + + # 2b. Path suffix lookup is useful for same-named regional files, but it + # is identity evidence only when no content hash was declared. A stale + # or incorrect destination can therefore never mask a hash mismatch. + found, own_file_absent = _by_path_suffix(q) + # 2c. The same tail in a data directory. + found = found or _by_data_dir_tail(q, data_dir_registry) + if found: + return found + + # 3. No MD5 = any file with that name or alias (existence check) + # An entry the profile documents as unsourceable is one the collection + # cannot hold: a font that only exists inside a paid package, cheat codes + # written per title. A file answering to its name is therefore a homonym + # from another system, not a stale dump of the same file - kanji.rom names + # an FPseNG font, an openMSX one and a 3DO ROM. Content still decides: the + # hash and path steps above run first, so collecting the real bytes makes + # the entry resolve. + unsourceable = bool(file_entry.get("unsourceable")) or own_file_absent + # A platform's own hashless entry whose system names a maker takes no copy + # filed under another maker: AmberELEC's nec-pc-88 DISK.ROM, which QUASI88 + # reads as the 2 KB PC-88 disk ROM, got the 16 KB MSX one by name. + makers: frozenset[str] = frozenset() if has_strong_hash else system_makers(file_entry, db) + + if not has_strong_hash and not unsourceable: + found, unsourceable = _by_name(q, makers, data_dir_registry) + if found: + return found + + # 4. Name + alias fallback with md5_composite + direct MD5 per candidate + named = _named_candidates(q, makers) + if named: + found = _named_md5_match(q, named) + if q.zipped_file: + found = found or _zipped_named(q, named, q.zipped_file) + elif not unsourceable: + found = found or _ranked_mismatch(q, named) + if found: + return found + + # 5. zipped_file content match via pre-built index (last resort: + # matches inner ROM MD5 across ALL ZIPs in the repo, so only use + # when name-based resolution failed entirely) + found = _by_zip_contents(q, zip_contents) + + # MAME clone fallback: if a file was deduped, resolve via canonical. The + # clone name is a name step like the others: an unsourceable entry skips + # it, and the size the code checks travels with it (dedup only merges + # identical bytes, so the canonical copy has the clone's size). + if _depth < 3 and not has_strong_hash and not unsourceable: + found = found or _by_mame_clone(q, zip_contents, _depth, data_dir_registry) + if found: + return found + + # Data directory fallback: scan data/ caches for matching filename + data_dir_mismatch: str | None = None + # Without a hash the cache walk matches on filename alone, which is the + # step an unsourceable entry has to skip: hiscore.dat names one file per + # driver set, so FBNeo's copy would answer for MAME's. + if data_dir_registry and (has_strong_hash or not unsourceable): + found, data_dir_mismatch = _in_data_dirs(q, data_dir_registry) + if found: + return found + + if data_dir_mismatch and not unsourceable: + return data_dir_mismatch, "hash_mismatch" + + return _resolve_agnostic(file_entry, q.files_db, has_strong_hash) or (None, "not_found") diff --git a/scripts/resolve/ownership.py b/scripts/resolve/ownership.py new file mode 100644 index 000000000..0ec3505db --- /dev/null +++ b/scripts/resolve/ownership.py @@ -0,0 +1,127 @@ +"""Which emulator, engine or manufacturer a path of the collection belongs to.""" + +from __future__ import annotations + +import re + + +# bios/Other/ and bios/Arcade/ 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// 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// 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// 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])) diff --git a/scripts/resolve/reconcile.py b/scripts/resolve/reconcile.py index b5a401cac..73f405917 100644 --- a/scripts/resolve/reconcile.py +++ b/scripts/resolve/reconcile.py @@ -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() diff --git a/scripts/resolve/slot.py b/scripts/resolve/slot.py index 1fafb3761..7007e6248 100644 --- a/scripts/resolve/slot.py +++ b/scripts/resolve/slot.py @@ -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}) diff --git a/scripts/resolve/standalone.py b/scripts/resolve/standalone.py new file mode 100644 index 000000000..e8f2104d3 --- /dev/null +++ b/scripts/resolve/standalone.py @@ -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)] diff --git a/scripts/resolve/truth.py b/scripts/resolve/truth.py index fba53300c..eed1018fe 100644 --- a/scripts/resolve/truth.py +++ b/scripts/resolve/truth.py @@ -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 ( diff --git a/scripts/resolve/validation.py b/scripts/resolve/validation.py index a11f14a99..3e4a3134d 100644 --- a/scripts/resolve/validation.py +++ b/scripts/resolve/validation.py @@ -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 diff --git a/scripts/restore_large_files.py b/scripts/restore_large_files.py index e08da8a2e..61d9c2277 100644 --- a/scripts/restore_large_files.py +++ b/scripts/restore_large_files.py @@ -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) diff --git a/scripts/retired_files.py b/scripts/retired_files.py index f9f1d3da1..877215e83 100644 --- a/scripts/retired_files.py +++ b/scripts/retired_files.py @@ -25,7 +25,8 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) -from common import run_cli, write_if_changed +from core.cli import run_cli +from core.artifacts import write_if_changed REPO_ROOT = Path(__file__).resolve().parents[1] RETIRED_FILE = REPO_ROOT / "retired.json" diff --git a/scripts/romfolders.py b/scripts/romfolders.py index a80da0507..2e29b70d7 100644 --- a/scripts/romfolders.py +++ b/scripts/romfolders.py @@ -5,7 +5,7 @@ about its game folders, read at a pinned revision: the roms root relative to the BIOS folder, each folder with the system name the OS gives it, the extensions it lists and the core it starts by default. Those files hold the OS's facts only. Which repository system a folder is, and which profile its -core is, is decided here, through the one alias table in common.py +core is, is decided here, through the one alias table in model/systems.py (`SYSTEM_ALIASES`, `_norm_system_id`) and the profiles' `cores:` lists, so a change to either reaches every setup without a rescrape. """ @@ -16,15 +16,10 @@ import re from dataclasses import dataclass, field from pathlib import Path -from common import ( - _norm_system_id, - list_registered_platforms, - load_emulator_profiles, - load_platform_config, - native_layer, - preferred_profile, - upstream_profile_index, -) +from model.systems import _norm_system_id +from model.registry import list_registered_platforms +from model.profiles import load_emulator_profiles, preferred_profile, upstream_profile_index +from model.platforms import load_platform_config, native_layer from model.safeparse import yaml_load ROMFOLDERS_DIR = Path("platforms") / "romfolders" diff --git a/scripts/romset_recipes.py b/scripts/romset_recipes.py index 079b0d424..820a59d9c 100644 --- a/scripts/romset_recipes.py +++ b/scripts/romset_recipes.py @@ -52,13 +52,11 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -from common import ( - require_directory, - load_database, - load_emulator_profiles, - load_platform_config, - list_registered_platforms, -) +from core.cli import require_directory +from model.database import load_database +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from model.registry import list_registered_platforms from torrentzip import build_torrentzip, is_torrentzip ARCHIVES_FILE = Path(__file__).resolve().parent.parent / "recipes" / "archives.json" @@ -722,6 +720,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/run_tests.py b/scripts/run_tests.py index ad574c8ed..8a7c72a43 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -187,6 +187,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/scraper/_hash_merge.py b/scripts/scraper/_hash_merge.py index 4ce66daba..d3394edad 100644 --- a/scripts/scraper/_hash_merge.py +++ b/scripts/scraper/_hash_merge.py @@ -15,7 +15,9 @@ from pathlib import Path from typing import Any -from common import PROFILE_BACKUP_SUFFIX, write_text_atomic, yaml_load +from model.profiles import PROFILE_BACKUP_SUFFIX +from core.artifacts import write_text_atomic +from model.safeparse import yaml_load _MAME_RELEASE_RE = re.compile(r"^0\.\d+") diff --git a/scripts/scraper/arcade_parent_importer.py b/scripts/scraper/arcade_parent_importer.py index 4abd4c1b9..3749ba359 100644 --- a/scripts/scraper/arcade_parent_importer.py +++ b/scripts/scraper/arcade_parent_importer.py @@ -51,7 +51,8 @@ from pathlib import Path from typing import IO from core.artifacts import write_if_changed -from ..common import load_emulator_profiles, run_cli +from model.profiles import load_emulator_profiles +from core.cli import run_cli from .romset_dat_importer import ( LISTXML_CHUNK, MAME_LISTXML_URL, diff --git a/scripts/scraper/base_scraper.py b/scripts/scraper/base_scraper.py index e81a2515e..b08032863 100644 --- a/scripts/scraper/base_scraper.py +++ b/scripts/scraper/base_scraper.py @@ -17,7 +17,9 @@ from dataclasses import dataclass, field from pathlib import Path from typing import Callable, NoReturn, Protocol -from common import github_token, write_text_atomic, yaml_load +from core.github import github_token +from core.artifacts import write_text_atomic +from model.safeparse import yaml_load @dataclass diff --git a/scripts/scraper/batocera_scraper.py b/scripts/scraper/batocera_scraper.py index 7072295c6..d70c73f31 100644 --- a/scripts/scraper/batocera_scraper.py +++ b/scripts/scraper/batocera_scraper.py @@ -18,7 +18,8 @@ from collections.abc import Callable from pathlib import Path -from common import load_target_config, yaml_load +from model.targets import load_target_config +from model.safeparse import yaml_load from core.hashing import cut_md5_owner from model.safeparse import yaml_load_upstream diff --git a/scripts/scraper/dat_pack_importer.py b/scripts/scraper/dat_pack_importer.py index d89699da4..ba6faf8ed 100644 --- a/scripts/scraper/dat_pack_importer.py +++ b/scripts/scraper/dat_pack_importer.py @@ -20,7 +20,7 @@ from collections.abc import Iterator from datetime import datetime, timezone from pathlib import Path -from ..common import write_provenance_snapshot +from model.dumpcatalog import write_provenance_snapshot from .logiqx_parser import LogiqxDat, parse_logiqx MAX_MEMBER_SIZE = 100 * 1024 * 1024 diff --git a/scripts/scraper/fbneo_hash_scraper.py b/scripts/scraper/fbneo_hash_scraper.py index 1f1fea97c..3eca408fa 100644 --- a/scripts/scraper/fbneo_hash_scraper.py +++ b/scripts/scraper/fbneo_hash_scraper.py @@ -21,7 +21,9 @@ from typing import Any import yaml -from common import source_yaml_paths, write_text_atomic, yaml_load +from model.profiles import source_yaml_paths +from core.artifacts import write_text_atomic +from model.safeparse import yaml_load from scripts.scraper._hash_merge import compute_diff, merge_fbneo_profile from scripts.scraper.fbneo_parser import parse_fbneo_source_tree diff --git a/scripts/scraper/game_dat_importer.py b/scripts/scraper/game_dat_importer.py index d59f64230..2952d7d2c 100644 --- a/scripts/scraper/game_dat_importer.py +++ b/scripts/scraper/game_dat_importer.py @@ -40,7 +40,7 @@ if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path: sys.path.insert(0, _SCRIPTS_DIR) from core.artifacts import copy_stream_atomic, write_if_changed, write_text_atomic -from common import parse_untrusted_xml +from model.safeparse import parse_untrusted_xml from region import REGIONS, WORLD from region_audit import NOINTRO diff --git a/scripts/scraper/logiqx_parser.py b/scripts/scraper/logiqx_parser.py index b45a718f1..5e83a6c98 100644 --- a/scripts/scraper/logiqx_parser.py +++ b/scripts/scraper/logiqx_parser.py @@ -15,7 +15,7 @@ from __future__ import annotations import xml.etree.ElementTree as ET from dataclasses import dataclass, field -from common import parse_untrusted_xml +from model.safeparse import parse_untrusted_xml @dataclass diff --git a/scripts/scraper/mame_devices.py b/scripts/scraper/mame_devices.py index ec3c1e92a..a8a2c7cf3 100644 --- a/scripts/scraper/mame_devices.py +++ b/scripts/scraper/mame_devices.py @@ -27,7 +27,7 @@ from contextlib import contextmanager from pathlib import Path from typing import IO, NamedTuple -from common import yaml_load +from model.safeparse import yaml_load from ._hash_merge import generated_start from .mame_parser import _collect_rom_macros, _expand_macros, _parse_rom_entries diff --git a/scripts/scraper/mame_hash_scraper.py b/scripts/scraper/mame_hash_scraper.py index c6e71dc91..0100afb5a 100644 --- a/scripts/scraper/mame_hash_scraper.py +++ b/scripts/scraper/mame_hash_scraper.py @@ -24,14 +24,12 @@ from typing import Any import yaml -from common import ( - github_token, - list_registered_platforms, - load_platform_config, - source_yaml_paths, - write_text_atomic, - yaml_load, -) +from core.github import github_token +from model.registry import list_registered_platforms +from model.platforms import load_platform_config +from model.profiles import source_yaml_paths +from core.artifacts import write_text_atomic +from model.safeparse import yaml_load import upstream diff --git a/scripts/scraper/recalbox_scraper.py b/scripts/scraper/recalbox_scraper.py index 3d12876bd..91687dd1d 100644 --- a/scripts/scraper/recalbox_scraper.py +++ b/scripts/scraper/recalbox_scraper.py @@ -15,7 +15,7 @@ Recalbox verification logic: from __future__ import annotations -from common import parse_untrusted_xml +from model.safeparse import parse_untrusted_xml from .base_scraper import BaseScraper, BiosRequirement, fetch_bytes, requirement_entry from .recalbox_launchers import SOURCE_FILES as LAUNCHER_FILES diff --git a/scripts/scraper/redump_dat_scraper.py b/scripts/scraper/redump_dat_scraper.py index 629dd8f80..c0b6233d1 100644 --- a/scripts/scraper/redump_dat_scraper.py +++ b/scripts/scraper/redump_dat_scraper.py @@ -22,7 +22,7 @@ import urllib.request from datetime import datetime, timezone from pathlib import Path -from ..common import write_provenance_snapshot +from model.dumpcatalog import write_provenance_snapshot from .base_scraper import _read_limited from .logiqx_parser import parse_logiqx, validate_logiqx_format diff --git a/scripts/scraper/retrobat_scraper.py b/scripts/scraper/retrobat_scraper.py index 09e3c915a..bd20bd19d 100644 --- a/scripts/scraper/retrobat_scraper.py +++ b/scripts/scraper/retrobat_scraper.py @@ -49,7 +49,7 @@ ES_SYSTEMS_URL = ( def es_systems_dual(text: str) -> set[str]: """Emulators es_systems.cfg offers both as a libretro core and standalone.""" - from common import parse_untrusted_xml + from model.safeparse import parse_untrusted_xml libretro: set[str] = set() standalone: set[str] = set() @@ -70,7 +70,7 @@ def es_systems_cores(text: str) -> tuple[set[str], set[str]]: name. batocera-systems.json names BIOS files only, so the platform read from it alone had no core list and relied on one kept by hand. """ - from common import parse_untrusted_xml + from model.safeparse import parse_untrusted_xml root = parse_untrusted_xml(text, "es_systems.cfg") cores: set[str] = set() @@ -96,7 +96,7 @@ def es_systems_libretro_systems(text: str) -> dict[str, list[str]]: reads below its save directory sits once in each of these system folders. A commented-out system is no element and counts for nothing. """ - from common import parse_untrusted_xml + from model.safeparse import parse_untrusted_xml found: dict[str, set[str]] = {} for system in parse_untrusted_xml(text, "es_systems.cfg").iter("system"): @@ -127,7 +127,7 @@ def pinned_revision(platform_file: Path = PLATFORM_FILE) -> str: A rescrape reads this commit unless told to move, so a change to an extractor shows in the diff alone, without upstream's commits since. """ - from common import yaml_load + from model.safeparse import yaml_load with platform_file.open(encoding="utf-8") as fh: source = str((yaml_load(fh) or {}).get("source") or "") diff --git a/scripts/scraper/retrodeck_scraper.py b/scripts/scraper/retrodeck_scraper.py index 00df2dbd3..35fad3e1e 100644 --- a/scripts/scraper/retrodeck_scraper.py +++ b/scripts/scraper/retrodeck_scraper.py @@ -77,7 +77,7 @@ def es_systems_libretro_systems(text: str) -> dict[str, list[str]]: ROM>, the system's folder below %ROMPATH%. A commented-out command is no element and counts for nothing. """ - from common import parse_untrusted_xml + from model.safeparse import parse_untrusted_xml found: dict[str, set[str]] = {} for system in parse_untrusted_xml(text, "es_systems.xml").iter("system"): @@ -411,7 +411,7 @@ class Scraper(BaseScraper): def _fetch_remote_manifests(self) -> list[tuple[str, dict]]: """Fetch component manifests via GitHub API.""" - from common import github_token + from core.github import github_token token = github_token() headers = {"User-Agent": "retrobios-scraper/1.0"} diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index a5f36c521..1e4cc5a5a 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -45,12 +45,10 @@ from datetime import datetime, timezone from pathlib import Path from typing import IO -from ..common import ( - list_registered_platforms, - load_emulator_profiles, - load_platform_config, - run_cli, -) +from model.registry import list_registered_platforms +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from core.cli import run_cli from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot from .logiqx_parser import LogiqxDat, parse_logiqx diff --git a/scripts/scraper/targets/__init__.py b/scripts/scraper/targets/__init__.py index ebdf4d76a..2c6fbd777 100644 --- a/scripts/scraper/targets/__init__.py +++ b/scripts/scraper/targets/__init__.py @@ -59,7 +59,7 @@ class BaseTargetScraper(ABC): import yaml except ImportError as exc: raise ImportError("PyYAML required: pip install pyyaml") from exc - from common import write_text_atomic + from core.artifacts import write_text_atomic write_text_atomic( output_path, yaml.dump(data, default_flow_style=False, sort_keys=False) diff --git a/scripts/scraper/targets/emudeck_targets_scraper.py b/scripts/scraper/targets/emudeck_targets_scraper.py index 6920e42c3..092f435b8 100644 --- a/scripts/scraper/targets/emudeck_targets_scraper.py +++ b/scripts/scraper/targets/emudeck_targets_scraper.py @@ -20,7 +20,8 @@ from pathlib import Path import yaml -from common import github_token, yaml_load +from core.github import github_token +from model.safeparse import yaml_load from ..emudeck_launchers import SCRIPT_SUFFIXES, emulator_of_script from . import BaseTargetScraper diff --git a/scripts/scraper/targets/retropie_targets_scraper.py b/scripts/scraper/targets/retropie_targets_scraper.py index 12d2b8112..8ebc2af86 100644 --- a/scripts/scraper/targets/retropie_targets_scraper.py +++ b/scripts/scraper/targets/retropie_targets_scraper.py @@ -68,7 +68,7 @@ _MODULE_FLAGS_RE = re.compile(r'rp_module_flags\s*=\s*["\']([^"\']*)["\']') def _fetch(url: str, accept: str = "text/plain") -> str: headers = {"User-Agent": "retrobios-scraper/1.0", "Accept": accept} - from common import github_token + from core.github import github_token token = github_token() if token and "api.github.com" in url: diff --git a/scripts/site_insights.py b/scripts/site_insights.py index 5392b85b4..e772b3941 100644 --- a/scripts/site_insights.py +++ b/scripts/site_insights.py @@ -43,7 +43,10 @@ from dataclasses import dataclass from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) -from common import github_token, load_database, load_emulator_profiles, run_cli +from core.github import github_token +from model.database import load_database +from model.profiles import load_emulator_profiles +from core.cli import run_cli REPO_ROOT = Path(__file__).resolve().parent.parent CONFIG = Path(os.environ.get("RETROBIOS_CONFIG", Path.home() / ".config" / "retrobios")) diff --git a/scripts/site_markdown.py b/scripts/site_markdown.py index 9f84e27e4..3d7508b14 100644 --- a/scripts/site_markdown.py +++ b/scripts/site_markdown.py @@ -39,7 +39,7 @@ from pathlib import Path from typing import ClassVar sys.path.insert(0, os.path.dirname(__file__)) -from common import run_cli +from core.cli import run_cli SITE = "https://abdess.github.io" BASE = "/retrobios/" diff --git a/scripts/sitecollection.py b/scripts/sitecollection.py index 8184f7490..f6b3b6e14 100644 --- a/scripts/sitecollection.py +++ b/scripts/sitecollection.py @@ -15,7 +15,8 @@ from dataclasses import dataclass sys.path.insert(0, os.path.dirname(__file__)) import siteinputs -from common import GAME_DATA_TOPS, load_emulator_profiles +from model.composition import GAME_DATA_TOPS +from model.profiles import load_emulator_profiles def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]: diff --git a/scripts/sitediagrams.py b/scripts/sitediagrams.py index e0c5173fc..c8e52e3bf 100644 --- a/scripts/sitediagrams.py +++ b/scripts/sitediagrams.py @@ -432,7 +432,7 @@ def setups() -> tuple[str, ...]: @cache def _setups_in(platforms_dir: str) -> tuple[str, ...]: - from common import list_registered_platforms + from model.registry import list_registered_platforms return tuple(sorted(list_registered_platforms(platforms_dir))) @@ -452,7 +452,7 @@ def platform_modes() -> dict[str, tuple[str, str, str | None]]: @cache def _platform_modes_in(platforms_dir: str) -> dict[str, tuple[str, str, str | None]]: - from common import load_platform_config + from model.platforms import load_platform_config out: dict[str, tuple[str, str, str | None]] = {} for name in _setups_in(platforms_dir): @@ -1165,6 +1165,6 @@ def main() -> None: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/sitemeasurements.py b/scripts/sitemeasurements.py index 227b0b8ad..33bb2c144 100644 --- a/scripts/sitemeasurements.py +++ b/scripts/sitemeasurements.py @@ -433,7 +433,7 @@ class Built: def load_profiles(emulators_dir: Path) -> dict: - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles return load_emulator_profiles(str(emulators_dir), skip_aliases=False) diff --git a/scripts/siterender.py b/scripts/siterender.py index 70e28f895..ffb34ac61 100644 --- a/scripts/siterender.py +++ b/scripts/siterender.py @@ -117,7 +117,7 @@ def set_system_page_map(mapping: dict[str, tuple[str, str]]) -> None: derived from it here. Kept anywhere else, it outlived a table of the same size and linked to the pages of the previous one. """ - from common import _norm_system_id + from model.systems import _norm_system_id _system_page_map.clear() _system_page_map.update(mapping) @@ -137,7 +137,7 @@ def _page_by_norm(sys_id: str) -> tuple[str, str] | None: keyed by the platforms' spellings: 2,431 of 4,195 cards had no link. A spelling two pages share leads nowhere rather than to either. """ - from common import _norm_system_id + from model.systems import _norm_system_id return _norm_page_map.get(_norm_system_id(sys_id)) @@ -433,7 +433,7 @@ def _read_arcade_source() -> tuple[dict, dict] | None: """The profiles and database of the repository, None without a database.""" import json - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles inputs = siteinputs.current() database = inputs.db @@ -751,7 +751,7 @@ def set_console_sections( group them, or is a set of (manufacturer, console) pairs. ``programs`` are the emulator names, which never name a system. """ - from common import _norm_system_id + from model.systems import _norm_system_id pairs = ( {(mfr, console) for mfr, consoles in sections.items() for console in consoles} @@ -803,7 +803,7 @@ def _ensure_console_sections() -> None: return import json - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from sitecollection import _group_by_manufacturer inputs = siteinputs.current() @@ -820,7 +820,7 @@ def _own_section(sys_id: str) -> tuple[str, str] | None: the one under the maker the id names is kept. Two left is no answer, and neither is a section that files a program's copies. """ - from common import _norm_system_id + from model.systems import _norm_system_id _ensure_console_sections() places = _console_sections.get(_norm_system_id(sys_id), set()) @@ -846,7 +846,7 @@ def _own_section(sys_id: str) -> tuple[str, str] | None: def _heading_name(mfr: str, console: str) -> str: """A console heading read out of its page: the maker in front, unless the heading already starts with it or the page is a game publisher's.""" - from common import GAME_DATA_TOPS + from model.composition import GAME_DATA_TOPS if mfr in GAME_DATA_TOPS: return SECTION_LABELS.get((mfr, console), console) @@ -1450,11 +1450,9 @@ def system_search_aliases(sys_id: str) -> list[str]: (psx, dreamcast, gba), sorted, for search. Read from each platform's own entries by common.platform_system_names, never typed by hand.""" if not _search_aliases_built[0]: - from common import ( - list_registered_platforms, - load_platform_config, - platform_system_names, - ) + from model.registry import list_registered_platforms + from model.platforms import load_platform_config + from model.systems import platform_system_names platforms_dir = str(siteinputs.current().platforms) index: dict[str, set[str]] = {} diff --git a/scripts/sitesources.py b/scripts/sitesources.py index cf4b39ec5..a2a3fd5e8 100644 --- a/scripts/sitesources.py +++ b/scripts/sitesources.py @@ -767,11 +767,8 @@ def main() -> int: if not args.fetch and not any(path.is_dir() for path in cache_dirs): print(f"Error: no tree cache at {', '.join(map(str, cache_dirs))}", file=sys.stderr) return 1 - from common import ( - load_emulator_profiles, - repository_output_lock, - write_if_changed, - ) + from model.profiles import load_emulator_profiles + from core.artifacts import repository_output_lock, write_if_changed profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False) with repository_output_lock(str(args.output)): @@ -785,6 +782,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/sitewanted.py b/scripts/sitewanted.py index fcd37c03c..371ab7b7d 100644 --- a/scripts/sitewanted.py +++ b/scripts/sitewanted.py @@ -22,7 +22,8 @@ from collections.abc import Callable, Iterable from pathlib import Path import archive_build -from common import runs_standalone, unique_emulator_profiles +from resolve.layout import runs_standalone +from model.profiles import unique_emulator_profiles from cross_reference import _first_hash from core.hashing import cut_md5_owner, parse_hash_list from validate_pr import LARGE_FILE_ISSUE_URL, Placement, placement diff --git a/scripts/slots.py b/scripts/slots.py index 1b31adf82..0a188df9f 100644 --- a/scripts/slots.py +++ b/scripts/slots.py @@ -25,24 +25,19 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING from resolve import nativemode -from common import ( - compute_hashes, - platform_arg, - archive_entry, - build_zip_contents_index, - check_inside_zip, - entry_system_ids, - holds_required_members, - load_data_dir_registry, - parse_md5_list, - resolution_is_hash_exact, - resolve_local_file, - resolve_platform_cores, - platform_layouts, - standalone_set as platform_standalone_set, - system_dir_path, - variant_base_name, -) +from core.hashing import compute_hashes, parse_md5_list +from model.cliargs import platform_arg, require_platform +from model.database import load_database +from model.platforms import load_platform_config +from resolve.archives import archive_entry, holds_required_members +from core.ziptools import build_zip_contents_index, check_inside_zip +from model.profiles import entry_system_ids, load_emulator_profiles +from model.registry import list_registered_platforms, load_data_dir_registry +from model.targets import build_target_cores_cache +from resolve.localfile import resolution_is_hash_exact, resolve_local_file, variant_base_name +from resolve.cores import resolve_platform_cores +from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set +from resolve.layout import system_dir_path from packresolve import preferred_entries from resolve.validation import ( content_alternatives, @@ -975,7 +970,8 @@ def scan_platform( target_cores: set[str] | None = None, ) -> list[Conflict]: """Conflicts on one platform, using the cores that platform actually runs.""" - from common import load_platform_config, resolve_platform_cores + from model.platforms import load_platform_config + from resolve.cores import resolve_platform_cores config = load_platform_config(platform, platforms_dir) keys = resolve_platform_cores(config, profiles, target_cores=target_cores) @@ -998,15 +994,6 @@ def main() -> int: import argparse import json - from common import ( - build_target_cores_cache, - list_registered_platforms, - load_database, - load_emulator_profiles, - load_platform_config, - require_platform, - ) - parser = argparse.ArgumentParser( allow_abbrev=False, description="Report destinations where an emulator profile contradicts " @@ -1039,13 +1026,13 @@ def main() -> int: "without it the run reports them and exits 0", ) 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", "platforms_dir", "emulators_dir"]) 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 # Claims resolve against data/: the trees stay put until the process @@ -1147,6 +1134,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/split_pack.py b/scripts/split_pack.py index 7ca4d5b36..81cd5ef9c 100644 --- a/scripts/split_pack.py +++ b/scripts/split_pack.py @@ -358,6 +358,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/standalone_probe.py b/scripts/standalone_probe.py index 64b42bb3f..782986164 100644 --- a/scripts/standalone_probe.py +++ b/scripts/standalone_probe.py @@ -719,6 +719,6 @@ def main(argv: Sequence[str] | None = None) -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/sync_release_assets.py b/scripts/sync_release_assets.py index e67fd2871..26e032909 100644 --- a/scripts/sync_release_assets.py +++ b/scripts/sync_release_assets.py @@ -35,7 +35,7 @@ from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from check_release_assets import compare, expected_assets, expected_digests, fetch_release -from common import load_database +from model.database import load_database from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths STAGING = Path("tmp") / "sync_release_assets" @@ -187,6 +187,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/torrentzip.py b/scripts/torrentzip.py index 41f1588fb..696d2e932 100644 --- a/scripts/torrentzip.py +++ b/scripts/torrentzip.py @@ -238,6 +238,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/upstream.py b/scripts/upstream.py index bfd7c4bb7..08b14d6bd 100644 --- a/scripts/upstream.py +++ b/scripts/upstream.py @@ -230,7 +230,7 @@ def _headers(url: str, accept_json: bool = False) -> dict[str, str]: if accept_json: headers["Accept"] = "application/json" if urllib.parse.urlsplit(url).netloc in GITHUB_HOSTS: - from common import github_token + from core.github import github_token # GITHUB_TOKEN, else the one gh is logged in with. token = github_token() @@ -667,7 +667,7 @@ def _github_graphql( GraphQL refuses anonymous calls, so an untokened run keeps the REST answer it already had. """ - from common import github_token + from core.github import github_token body = json.dumps({"query": query, "variables": variables}, sort_keys=True) target = Path(cache_dir) / "_api" / f"{hashlib.sha256(body.encode()).hexdigest()}.json" diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index 02c631d8f..9d4dc881e 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -36,15 +36,12 @@ if TYPE_CHECKING: from typing_extensions import Unpack sys.path.insert(0, os.path.dirname(__file__)) -from common import ( - compute_hashes, - list_registered_platforms, - load_database, - load_emulator_profiles, - load_platform_config, - parse_md5_list, - require_directory, -) +from core.hashing import compute_hashes, parse_md5_list +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 core.cli import require_directory from core.hashing import parse_hash_list from resolve.nativemode import digest_algorithm from dedup import _in_nodedup_dir @@ -1238,6 +1235,6 @@ def main() -> None: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/validate_schemas.py b/scripts/validate_schemas.py index aa5845228..ef2150895 100644 --- a/scripts/validate_schemas.py +++ b/scripts/validate_schemas.py @@ -13,7 +13,8 @@ from pathlib import Path, PurePosixPath import yaml -from common import source_yaml_paths, yaml_load +from model.profiles import source_yaml_paths +from model.safeparse import yaml_load try: from jsonschema import Draft202012Validator, FormatChecker @@ -360,7 +361,7 @@ def _validate_pack_manifests(dist: Path) -> list[str]: return [] sys.path.insert(0, str(ROOT / "scripts")) - from common import ArtifactLockBusy, artifact_lock + from core.artifacts import ArtifactLockBusy, artifact_lock try: with artifact_lock(str(dist), exclusive=False): @@ -682,7 +683,7 @@ def _save_directory_blocks() -> list[str]: def _bios_tree_below(platform: str, folder: str) -> str: """A destination the platform declares below ``folder``, or empty.""" - from common import load_platform_config + from model.platforms import load_platform_config try: config = load_platform_config(platform, str(ROOT / "platforms")) @@ -702,7 +703,7 @@ def _bios_tree_below(platform: str, folder: str) -> str: def _libretro_systems(platform: str) -> dict: """The platform file's core -> systems table, inheritance included.""" - from common import load_platform_config + from model.platforms import load_platform_config try: config = load_platform_config(platform, str(ROOT / "platforms")) @@ -1103,6 +1104,6 @@ def main() -> int: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/validate_site.py b/scripts/validate_site.py index ec496a040..5c7cb5b1a 100644 --- a/scripts/validate_site.py +++ b/scripts/validate_site.py @@ -429,7 +429,7 @@ def _check_get_pages( sys.path.insert(0, str(Path(__file__).resolve().parent)) import release_record from siteguides import INSTALL_SH - from common import list_registered_platforms, list_release_pack_platforms + from model.registry import list_registered_platforms, list_release_pack_platforms if not (platforms_dir / "_registry.yml").is_file(): return [f"no platform registry in {platforms_dir}"] @@ -523,7 +523,7 @@ def main() -> None: help="stop listing after this many errors (default: %(default)s)", ) args = parser.parse_args() - from common import require_directory + from core.cli import require_directory require_directory(str(args.platforms_dir), "--platforms-dir") @@ -549,6 +549,6 @@ def main() -> None: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/scripts/verify.py b/scripts/verify.py index 96bed7d33..97fe6bc9b 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -47,60 +47,54 @@ from model.alternatives import ( settle_sets, slot_set_keys, ) -from common import ( - TARGET_KEY, +from resolve.contentlayout import TARGET_KEY +from model.targets import ( canonical_target_name, - OUTER_ROOTS, - _foreign_tree, - _owner_tokens, + target_listing_line, + list_available_targets, + build_target_cores_cache, +) +from resolve.layout import OUTER_ROOTS, runs_standalone, system_dir_path +from resolve.ownership import _foreign_tree, _owner_tokens +from model.cliargs import ( platform_arg, work_from_repo_root, - target_listing_line, - suggest_names, - system_index, require_platform, - archive_entry, - archive_is_optional, - archive_members, - profiles_for_systems, - PROFILE_IDENTITY_FIELDS, - list_available_targets, list_platform_system_ids, - list_registered_platforms, - build_target_cores_cache, - build_zip_contents_index, - check_inside_zip, - compute_hashes, - expand_directory_entries, - platform_declarations, - platform_declared_contents, - group_identical_platforms, list_emulator_profiles, list_system_ids, - load_data_dir_registry, - load_database, - load_emulator_profiles, - load_platform_config, - without_profile_blind, - resolve_system_arg, print_platform_listing, - select_systems, - platform_scope_systems, - system_scope_error, - md5sum, - require_yaml, - resolve_local_file, +) +from core.cli import suggest_names +from model.systems import system_index, resolve_system_arg, select_systems +from resolve.archives import archive_entry, archive_is_optional, archive_members +from model.profiles import ( + profiles_for_systems, + PROFILE_IDENTITY_FIELDS, + load_emulator_profiles, ProfileSelectionError, - resolve_platform_cores, - platform_layouts, - runs_standalone, - standalone_set as platform_standalone_set, entry_serves_systems, entry_system_ids, - sanitize_pack_path, select_emulator_profiles, - system_dir_path, ) +from model.registry import list_registered_platforms, load_data_dir_registry +from core.ziptools import build_zip_contents_index, check_inside_zip +from core.hashing import compute_hashes, md5sum +from resolve.directories import expand_directory_entries +from model.declarations import platform_declarations, platform_declared_contents +from resolve.grouping import group_identical_platforms +from model.database import load_database +from model.platforms import load_platform_config +from resolve.cores import ( + without_profile_blind, + platform_scope_systems, + system_scope_error, + resolve_platform_cores, +) +from model.safeparse import require_yaml +from resolve.localfile import resolve_local_file +from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set +from core.paths import sanitize_pack_path from resolve.categories import BIOS, EntryCategories from resolve.launchers import LauncherLayer, declared_destinations, held_record, launcher_unproven @@ -3898,6 +3892,6 @@ def _overall_summary(group_results: list[tuple[dict, list[str]]]) -> str: if __name__ == "__main__": - from common import run_cli + from core.cli import run_cli run_cli(main) diff --git a/tests/test_adler32_resolution.py b/tests/test_adler32_resolution.py index 7326e6e92..1d1968d3d 100644 --- a/tests/test_adler32_resolution.py +++ b/tests/test_adler32_resolution.py @@ -19,7 +19,8 @@ import unittest import zlib from pathlib import Path -from common import adler32_of, resolve_local_file +from resolve.content import adler32_of +from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parents[1] @@ -117,7 +118,7 @@ class TheTwoRomsFormAPairTheCodeTakes(unittest.TestCase): class DolphinGetsAPairItTakes(unittest.TestCase): def test_each_dolphin_dsp_rom_resolves_to_an_accepted_dump(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles database = REPO_ROOT / "database.json" if not database.exists(): @@ -137,7 +138,7 @@ class DolphinGetsAPairItTakes(unittest.TestCase): def test_every_paired_profile_resolves_a_pair_its_code_takes(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles database = REPO_ROOT / "database.json" if not database.exists(): diff --git a/tests/test_agnostic_scan.py b/tests/test_agnostic_scan.py index d5b2a80af..aa47a605b 100644 --- a/tests/test_agnostic_scan.py +++ b/tests/test_agnostic_scan.py @@ -19,7 +19,8 @@ import tempfile import unittest from pathlib import Path -import common +from model.profiles import load_emulator_profiles, _emulator_profiles_cache +from resolve.localfile import resolve_local_file import generate_pack as builder import packextras @@ -87,15 +88,15 @@ class AgnosticScanStaysInItsTree(unittest.TestCase): "base_destination": "", "systems": {}, } - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def _write_profile(self, body: str): (self.root / "emulators" / "demo.yml").write_text(body) - return common.load_emulator_profiles(str(self.root / "emulators")) + return load_emulator_profiles(str(self.root / "emulators")) def _scan(self, profiles): extras = builder._collect_emulator_extras( @@ -210,7 +211,7 @@ class AgnosticScanStaysInItsTree(unittest.TestCase): self.assertTrue(self._scan(profiles)) for extra in self._scan(profiles): self.assertIn("sha1", extra, f"{extra['name']} carries no identity") - path, status = common.resolve_local_file(extra, self.db) + path, status = resolve_local_file(extra, self.db) self.assertEqual(status, "sha1_exact") self.assertTrue(path.endswith(extra["name"])) @@ -254,7 +255,7 @@ class PathTailBeatsABareName(unittest.TestCase): def test_the_tail_of_the_declared_path_decides(self): entry = {"name": "index.yaml", "path": "app/resources/index.yaml"} - path, status = common.resolve_local_file( + path, status = resolve_local_file( entry, self.db, dest_hint=entry["path"] ) self.assertEqual(status, "path_exact") @@ -263,7 +264,7 @@ class PathTailBeatsABareName(unittest.TestCase): def test_a_bare_name_is_never_reached_through_the_tail(self): """The tail stops above the filename: that is the weaker step.""" entry = {"name": "index.yaml", "path": "nowhere/index.yaml"} - _path, status = common.resolve_local_file( + _path, status = resolve_local_file( entry, self.db, dest_hint=entry["path"] ) self.assertEqual(status, "name_exact") diff --git a/tests/test_agnostic_scan_mode.py b/tests/test_agnostic_scan_mode.py index 2d12f9d1a..1a0c9e6aa 100644 --- a/tests/test_agnostic_scan_mode.py +++ b/tests/test_agnostic_scan_mode.py @@ -24,7 +24,9 @@ class ScanFollowsTheBuild(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from packextras import _collect_emulator_extras profiles = load_emulator_profiles("emulators") diff --git a/tests/test_agnostic_scope.py b/tests/test_agnostic_scope.py index 4fffefe1c..af86883a2 100644 --- a/tests/test_agnostic_scope.py +++ b/tests/test_agnostic_scope.py @@ -153,13 +153,11 @@ class BundledHashIsProof(unittest.TestCase): def test_no_bundled_entry_resolves_to_other_bytes(self): if not (REPO_ROOT / "database.json").is_file(): self.skipTest("no database.json") - from common import ( - build_zip_contents_index, - load_data_dir_registry, - load_database, - load_emulator_profiles, - resolve_local_file, - ) + from core.ziptools import build_zip_contents_index + from model.registry import load_data_dir_registry + from model.database import load_database + from model.profiles import load_emulator_profiles + from resolve.localfile import resolve_local_file previous = os.getcwd() os.chdir(REPO_ROOT) diff --git a/tests/test_archive_choice.py b/tests/test_archive_choice.py index 971288eb2..9da6ffd74 100644 --- a/tests/test_archive_choice.py +++ b/tests/test_archive_choice.py @@ -157,7 +157,8 @@ class TheArchiveHoldingTheCoreMembers(unittest.TestCase): ] def test_the_copy_with_every_required_member_wins(self): - from common import archive_entry, resolve_local_file + from resolve.archives import archive_entry + from resolve.localfile import resolve_local_file path, status = resolve_local_file( archive_entry("neocdz.zip", self.profile_files), self.db @@ -166,7 +167,7 @@ class TheArchiveHoldingTheCoreMembers(unittest.TestCase): self.assertEqual(status, "name_exact") def test_without_members_the_primary_stays(self): - from common import resolve_local_file + from resolve.localfile import resolve_local_file path, _status = resolve_local_file({"name": "neocdz.zip"}, self.db) self.assertTrue(path.endswith("bios/neocdz.zip")) @@ -186,7 +187,9 @@ class TheArchiveHoldingTheCoreMembers(unittest.TestCase): MAME's 83b6f611 dump while the FBNeo dump sat loose in bios/.""" import json - from common import archive_members, load_emulator_profiles, zip_member_crcs + from resolve.archives import archive_members + from model.profiles import load_emulator_profiles + from core.ziptools import zip_member_crcs database = REPO_ROOT / "database.json" if not database.exists(): @@ -228,7 +231,7 @@ class EveryDeclaredLayoutIsHeld(unittest.TestCase): def setUp(self): import json - from common import get_mame_clone_map + from model.database import get_mame_clone_map database = REPO_ROOT / "database.json" if not (REPO_ROOT / "bios").is_dir() or not database.exists(): @@ -240,7 +243,7 @@ class EveryDeclaredLayoutIsHeld(unittest.TestCase): self.addCleanup(os.chdir, previous) def _declared_archives(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles for emu, profile in load_emulator_profiles("emulators").items(): for entry in profile.get("files") or []: @@ -273,7 +276,8 @@ class EveryDeclaredLayoutIsHeld(unittest.TestCase): self.assertEqual(absent, []) def test_a_copy_holds_each_declared_layout_and_is_served(self): - from common import resolve_local_file, zip_member_crcs + from resolve.localfile import resolve_local_file + from core.ziptools import zip_member_crcs short, unserved = [], [] for emu, entry in self._declared_archives(): @@ -321,19 +325,19 @@ class AnArchiveHashedByItsMembers(unittest.TestCase): self.archive = str(archive) def test_the_archive_answers_a_composite_frontend(self): - from common import resolve_local_file + from resolve.localfile import resolve_local_file path, status = resolve_local_file({**self.entry, "zip_digest": "composite"}, self.db) self.assertEqual((path, status), (self.archive, "md5_composite_exact")) def test_a_plain_digest_still_takes_the_md5_match(self): - from common import resolve_local_file + from resolve.localfile import resolve_local_file path, _status = resolve_local_file(self.entry, self.db) self.assertTrue(path.endswith("neocd.bin")) def test_the_registry_marks_recalbox_archives(self): - from common import load_platform_config + from model.platforms import load_platform_config config = load_platform_config("recalbox", str(REPO_ROOT / "platforms")) marks = { @@ -369,7 +373,7 @@ class AnArchiveRankedByWhatItHolds(unittest.TestCase): "by_path_suffix": {}, "by_crc32": {}}} def _resolve(self, entry: dict, db: dict) -> str: - from common import resolve_local_file + from resolve.localfile import resolve_local_file path, _status = resolve_local_file(entry, db) return str(Path(path).relative_to(self.root)) @@ -409,7 +413,7 @@ class AnArchiveRankedByWhatItHolds(unittest.TestCase): def test_a_copy_holding_no_declared_member_is_not_the_archive(self): """galgames.zip held only an assembler listing and none of the six ROMs MAME declares: the name step served it as the BIOS set.""" - from common import resolve_local_file + from resolve.localfile import resolve_local_file db = self._db([("bios/MAME/hod2bios.zip", ["listing.lst"])]) entry = {"name": "hod2bios.zip", "contents": [ @@ -465,7 +469,7 @@ class ALooseEntryNamingItsArchive(unittest.TestCase): import yaml - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache from generate_pack import generate_emulator_pack from verify import verify_emulator @@ -546,7 +550,7 @@ class AnotherEmulatorsOwnSet(unittest.TestCase): return [{"name": n, "crc32": format(zlib.crc32(self.roms[n]), "08x")} for n in names] def test_its_member_count_does_not_rank_for_another_emulator(self): - from common import resolve_local_file + from resolve.localfile import resolve_local_file entry = {"name": "naomi.zip", "source_profile": "flycast", "contents": self._contents(list(self.roms))} @@ -554,13 +558,13 @@ class AnotherEmulatorsOwnSet(unittest.TestCase): self.assertEqual(path, "bios/MAME/naomi.zip") def test_it_does_not_break_the_superset_of_an_unowned_entry(self): - from common import resolve_local_file + from resolve.localfile import resolve_local_file path, _status = resolve_local_file({"name": "naomi.zip"}, self.db) self.assertEqual(path, "bios/MAME/naomi.zip") def test_its_owner_still_gets_it(self): - from common import resolve_local_file + from resolve.localfile import resolve_local_file entry = {"name": "naomi.zip", "source_profile": "demul", "contents": self._contents(list(self.roms))} @@ -595,7 +599,7 @@ class ArchiveMembersIndexOnce(unittest.TestCase): for f in list.__iter__(files) if f.get("archive") == archive and f.get("crc32")] def test_a_profile_list_is_walked_once_and_answers_as_a_scan(self): - from common import archive_members + from resolve.archives import archive_members files = self.entries() for archive in [f"set{n}.zip" for n in range(30)] + ["absent.zip", "", None]: @@ -604,7 +608,7 @@ class ArchiveMembersIndexOnce(unittest.TestCase): self.assertEqual(self.CountingList.walks, 1) def test_a_list_that_grew_is_indexed_again(self): - from common import archive_members + from resolve.archives import archive_members files = self.entries() archive_members("set1.zip", files) diff --git a/tests/test_archive_recipes.py b/tests/test_archive_recipes.py index 20248a3f0..a868634f1 100644 --- a/tests/test_archive_recipes.py +++ b/tests/test_archive_recipes.py @@ -84,7 +84,7 @@ def _hashes(values: object) -> set[str]: def _allowed_members() -> dict[str, set[str]]: - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from romset_recipes import load_dat_recipes allowed: dict[str, set[str]] = defaultdict(set) @@ -111,7 +111,8 @@ def _allowed_members() -> dict[str, set[str]]: def _platform_pins() -> tuple[set[str], dict[str, set[tuple[str, str]]]]: - from common import list_registered_platforms, load_platform_config + from model.registry import list_registered_platforms + from model.platforms import load_platform_config pinned: set[str] = set() zipped: dict[str, set[tuple[str, str]]] = defaultdict(set) @@ -158,7 +159,7 @@ class HeldArchivesMatchTheirRecipes(unittest.TestCase): bios = REPO_ROOT / "bios" if not bios.is_dir() or not (REPO_ROOT / "recipes").is_dir(): self.skipTest("bios/ or recipes/ is not present") - from common import variant_base_name + from resolve.localfile import variant_base_name from core.hashing import md5_composite_of allowed = _allowed_members() diff --git a/tests/test_artifact_lock.py b/tests/test_artifact_lock.py index 6e757164b..bbb7d6d14 100644 --- a/tests/test_artifact_lock.py +++ b/tests/test_artifact_lock.py @@ -17,7 +17,7 @@ import tempfile import unittest from pathlib import Path -from common import ( +from core.artifacts import ( ArtifactLockBusy, artifact_lock, hold_artifact_lock, @@ -66,7 +66,7 @@ class ArtifactLockTest(unittest.TestCase): """A mistyped --output-dir given to --verify-packs or release_record was created holding a .lock, and the next run with the same typo no longer said the path did not exist.""" - from common import ArtifactDirectoryMissing + from core.artifacts import ArtifactDirectoryMissing missing = os.path.join(self.dir, "sub", "dsit") with self.assertRaises(ArtifactDirectoryMissing), artifact_lock(missing, exclusive=False): @@ -314,7 +314,7 @@ class StandaloneWritersHonourTheRepositoryHold(unittest.TestCase): def _child(self, target: str, env: dict) -> subprocess.CompletedProcess: code = ( "import sys; sys.path.insert(0, 'scripts')\n" - "from common import artifact_lock, repository_output_lock\n" + "from core.artifacts import artifact_lock, repository_output_lock\n" f"with repository_output_lock({target!r}), artifact_lock({self.scratch!r}):\n" " pass\n" ) @@ -349,7 +349,7 @@ class HeldLockTest(unittest.TestCase): def _child_locks(self, env: dict) -> subprocess.CompletedProcess: code = ( "import sys; sys.path.insert(0, 'scripts')\n" - "from common import artifact_lock\n" + "from core.artifacts import artifact_lock\n" f"with artifact_lock({self.dir!r}):\n pass\n" ) return subprocess.run( diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index 32502d045..61c4e0e53 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -309,7 +309,7 @@ class ATerminatedBuildLeavesNoScratch(unittest.TestCase): CHILD = ( "import sys, time\n" "sys.path.insert(0, 'scripts')\n" - "from common import run_cli\n" + "from core.cli import run_cli\n" "from generate_pack import _writing_pack\n" "def main():\n" " with _writing_pack(sys.argv[1]) as zf:\n" diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index f8b70a69a..64df90823 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -30,7 +30,8 @@ except ImportError: import install from scripts import pipeline, region_audit from scripts import region -from scripts.common import resolve_local_file, safe_extract_zip +from scripts.resolve.localfile import resolve_local_file +from scripts.core.ziptools import safe_extract_zip from scripts.generate_pack import ( _emulator_region_group, generate_target_manifests, @@ -600,7 +601,7 @@ class OnePlatformPerFlag(unittest.TestCase): self.assertNotIn("Traceback", completed.stderr) def test_unknown_names_still_get_a_suggestion(self): - from common import require_platform + from model.cliargs import require_platform with self.assertRaises(SystemExit) as caught: require_platform("batocra", str(ROOT / "platforms")) @@ -664,7 +665,8 @@ class EverySharedGroupServesAPlatform(unittest.TestCase): verify and no manifest, and nothing said so.""" def test_each_group_contributes_an_entry_somewhere(self): - from common import list_registered_platforms, load_platform_config + from model.registry import list_registered_platforms + from model.platforms import load_platform_config platforms_dir = str(ROOT / "platforms") with (ROOT / "platforms" / "_shared.yml").open(encoding="utf-8") as handle: @@ -1000,7 +1002,7 @@ class FaqRegressions(unittest.TestCase): # and FinalBurn Neo 1.0.0.2, versions no source at the pins states, # and the test holding them to the profiles kept the errors in step. import generate_site - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles profiles = load_emulator_profiles(str(ROOT / "emulators"), skip_aliases=False) page = (ROOT / "wiki" / "technical-faq.md").read_text(encoding="utf-8") @@ -1077,7 +1079,7 @@ class CatalogRatioRegressions(unittest.TestCase): ) def test_arcade_and_engine_data_stay_out_of_the_ratio(self): - from scripts.common import compute_composition, count_catalog_matched + from scripts.model.composition import compute_composition, count_catalog_matched db = { "files": { @@ -1097,7 +1099,7 @@ class CatalogRatioRegressions(unittest.TestCase): """Engine data collected under `Game Engines/` and under a game publisher counted as console and computer system files: 7 697 of them made the README announce 13 564 system files.""" - from scripts.common import composition_tier + from scripts.model.composition import composition_tier for path in ( "bios/Game Engines/C-Dogs SDL/cdogs/data/guns.json", @@ -1110,7 +1112,8 @@ class CatalogRatioRegressions(unittest.TestCase): self.assertEqual(composition_tier("bios/Microsoft/MSX/MSX2.ROM"), "systems") def test_readme_ratio_matches_the_database(self): - from scripts.common import compute_composition, count_catalog_matched, load_database + from scripts.model.composition import compute_composition, count_catalog_matched + from scripts.model.database import load_database database = ROOT / "database.json" if not database.exists(): @@ -1466,7 +1469,7 @@ class OneBaselineVerdict(unittest.TestCase): digit.""" import hashlib - from scripts.common import md5_composite + from scripts.core.hashing import md5_composite from scripts.resolve.validation import baseline_verdict, digest_verdict with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: @@ -1496,7 +1499,7 @@ class OneBaselineVerdict(unittest.TestCase): neocd.bin shipped as neocdz.zip passed while Recalbox marks it red.""" import hashlib - from scripts.common import md5_composite + from scripts.core.hashing import md5_composite from scripts.resolve.validation import digest_verdict with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: @@ -2393,11 +2396,11 @@ class ManifestVersionIsThePlatformsOwn(unittest.TestCase): so each manifest states the version its own platform YAML records.""" def setUp(self): - from scripts.common import _platform_config_cache + from scripts.model.platforms import _platform_config_cache _platform_config_cache.clear() def test_committed_manifests_state_their_platform_version(self): - from scripts.common import load_platform_config + from scripts.model.platforms import load_platform_config manifests = sorted((ROOT / "install").glob("*.json")) self.assertTrue(manifests) for path in manifests: @@ -2408,7 +2411,7 @@ class ManifestVersionIsThePlatformsOwn(unittest.TestCase): self.assertEqual(data["version"], str(config["version"])) def test_no_child_shows_its_parents_version(self): - from scripts.common import load_platform_config + from scripts.model.platforms import load_platform_config platforms = ROOT / "platforms" children = {} for path in sorted(platforms.glob("*.yml")): @@ -2425,7 +2428,7 @@ class ManifestVersionIsThePlatformsOwn(unittest.TestCase): self.assertNotEqual(version, parent.get("version")) def test_an_unversioned_child_has_no_version(self): - from scripts.common import load_platform_config + from scripts.model.platforms import load_platform_config with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: Path(tmp, "parent.yml").write_text("platform: P\nversion: '2.0'\nsystems: {}\n") Path(tmp, "child.yml").write_text("inherits: parent\nplatform: C\n") @@ -2907,7 +2910,7 @@ class FreshnessGuardMechanics(unittest.TestCase): """ def setUp(self): - from common import write_if_changed + from core.artifacts import write_if_changed self.write_if_changed = write_if_changed self._tmp = tempfile.TemporaryDirectory() @@ -3217,10 +3220,13 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): self.assertEqual(stop.exception.code, 1) def test_a_missing_profile_directory_says_so(self): - from scripts import common as _common + # Bare names, as the loader imports them: scripts.core.cli would be a + # second copy of the module, with a second InputMissing. + from core.cli import InputMissing + from model.profiles import load_emulator_profiles - with self.assertRaisesRegex(_common.InputMissing, "no emulator profile directory"): - _common.load_emulator_profiles(str(ROOT / "no-such-emulator-dir")) + with self.assertRaisesRegex(InputMissing, "no emulator profile directory"): + load_emulator_profiles(str(ROOT / "no-such-emulator-dir")) class TestEntryPointsRunEveryClass(unittest.TestCase): @@ -3260,7 +3266,7 @@ class ScriptsImportThreeWays(unittest.TestCase): The three do not agree on what is on the path: only the first form adds the scripts directory. Adding the package marker without the bootstrap - made `import scripts.common` fail on the first sibling import it reached. + made `import scripts.common` (now scripts.core.cli) fail on the first sibling import it reached. """ def _run(self, *args: str): @@ -3274,7 +3280,8 @@ class ScriptsImportThreeWays(unittest.TestCase): def test_imported_as_a_package(self): result = self._run( - "-c", "import scripts.common, scripts.verify, scripts.generate_pack" + "-c", "import scripts.core.cli, scripts.model.platforms, scripts.resolve.localfile, " + "scripts.verify, scripts.generate_pack" ) self.assertEqual(result.returncode, 0, result.stderr[-400:]) @@ -3467,7 +3474,7 @@ class AnotherEmulatorsTreeProvesNothing(unittest.TestCase): return db def test_neither_the_full_tail_nor_the_name_lands_in_a_foreign_tree(self): - from scripts.common import resolve_local_file + from scripts.resolve.localfile import resolve_local_file with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = Path(directory) @@ -3497,13 +3504,11 @@ class AnotherEmulatorsTreeProvesNothing(unittest.TestCase): def test_no_desktop_retroarch_pack_serves_armsx2s_tree(self): from scripts import slots - from scripts.common import ( - load_data_dir_registry, - load_database, - load_emulator_profiles, - load_platform_config, - load_target_config, - ) + from scripts.model.registry import load_data_dir_registry + from scripts.model.database import load_database + from scripts.model.profiles import load_emulator_profiles + from scripts.model.platforms import load_platform_config + from scripts.model.targets import load_target_config if not (ROOT / "database.json").exists(): self.skipTest("database.json is not generated") @@ -3556,7 +3561,7 @@ class ANameWithItsDirectoryIsTheDestination(unittest.TestCase): def test_the_directory_in_the_name_picks_the_copy(self): import hashlib - from scripts.common import resolve_local_file + from scripts.resolve.localfile import resolve_local_file with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = Path(directory) @@ -3760,7 +3765,7 @@ class KidVidTapesStayWithTheContent(unittest.TestCase): reaches: stella's tapes go there, never to the BIOS tree.""" def test_no_pack_places_them_in_the_system_directory(self): - from scripts.common import load_emulator_profiles + from scripts.model.profiles import load_emulator_profiles from scripts.resolve.validation import ( outside_gap_scope, read_from_save_dir, @@ -3869,7 +3874,8 @@ class HashMergeBackupsAreNotSources(unittest.TestCase): offenders = [ str(path.relative_to(ROOT)) for path in sorted(ROOT.glob("scripts/**/*.py")) - if path.name != "common.py" and '".old.yml"' in path.read_text() + if path.relative_to(ROOT).as_posix() != "scripts/model/profiles.py" + and '".old.yml"' in path.read_text() ] self.assertEqual(offenders, []) @@ -3880,7 +3886,7 @@ class AnUnreadableArchiveIsSaidOutLoud(unittest.TestCase): truncated archive read as a missing dump (not_found) or a wrong one.""" def test_the_resolver_names_the_archive(self): - import common + from resolve import localfile with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as tmp: broken = Path(tmp) / "neogeo.zip" @@ -3893,7 +3899,7 @@ class AnUnreadableArchiveIsSaidOutLoud(unittest.TestCase): entry = {"name": "neogeo.zip", "md5": "1" * 32, "zipped_file": "sp-s2.sp1"} stderr = io.StringIO() with contextlib.redirect_stderr(stderr): - common.resolve_local_file(entry, db) + localfile.resolve_local_file(entry, db) self.assertIn(f"unreadable archive {broken}", stderr.getvalue()) @@ -3903,19 +3909,20 @@ class GeneralUserGSReachesEveryCoreThatNamesIt(unittest.TestCase): shipped no General MIDI bank.""" def test_each_name_resolves_to_the_one_file(self): - import common + from model import profiles as model_profiles + from resolve import localfile if not (ROOT / "database.json").exists(): self.skipTest("database.json is not generated") db = json.loads((ROOT / "database.json").read_text()) - profiles = common.load_emulator_profiles(str(ROOT / "emulators")) + profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators")) held = "bios/Other/GeneralUser GS/GeneralUser-GS.sf2" for emulator, name in (("dosbox_pure", "DOSBOX.SF2"), ("dosbox-staging", "GeneralUser-GS.sf2"), ("dosbox-x", "GeneralUser_GS.sf2")): with self.subTest(emulator=emulator): entry = next(f for f in profiles[emulator]["files"] if f["name"] == name) - path, _status = common.resolve_local_file( + path, _status = localfile.resolve_local_file( {**entry, "source_profile": emulator}, db, dest_hint=entry.get("path", "")) self.assertEqual(path, held) @@ -3927,19 +3934,20 @@ class APlatformPinDoesNotReplaceTheCoresRevision(unittest.TestCase): files to cores built against newer ones.""" def test_the_profile_revision_serves_the_core(self): - import common + from model import profiles as model_profiles + from resolve import localfile if not (ROOT / "database.json").exists(): self.skipTest("database.json is not generated") db = json.loads((ROOT / "database.json").read_text()) - profiles = common.load_emulator_profiles(str(ROOT / "emulators")) + profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators")) for emulator, name, pinned in (("scummvm", "kyra.dat", "21a57f79886e46f410cfb50186ed8d77"), ("fbneo", "hiscore.dat", "37fc4e050b53a1ef2c2e7f3042553025")): with self.subTest(emulator=emulator): entry = next(f for f in profiles[emulator]["files"] if f["name"] == name) self.assertTrue(entry.get("sha1"), "the profile claims its revision") self.assertIn(pinned, db["indexes"]["by_md5"], "the platform's pin is held") - path, status = common.resolve_local_file( + path, status = localfile.resolve_local_file( {**entry, "source_profile": emulator}, db, dest_hint=entry["path"]) self.assertEqual(status, "sha1_exact") self.assertEqual(db["files"][entry["sha1"]]["path"], path) @@ -3968,7 +3976,7 @@ class ADataDirectoryIsWalkedOnce(unittest.TestCase): resolution cost names x tree on every pack build.""" def test_two_lookups_share_one_walk_and_keep_its_order(self): - import common + from resolve.datadirs import forget_data_dir_index, _resolve_in_data_dirs with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as tmp: cache = Path(tmp) / "cache" @@ -3978,7 +3986,7 @@ class ADataDirectoryIsWalkedOnce(unittest.TestCase): (cache / "b" / "font.bin").write_bytes(b"2") (cache / "b" / "other.bin").write_bytes(b"3") registry = {"x": {"local_cache": str(cache)}} - common.forget_data_dir_index() + forget_data_dir_index() walks = [] real_walk = os.walk @@ -3987,11 +3995,11 @@ class ADataDirectoryIsWalkedOnce(unittest.TestCase): return real_walk(top, *a, **k) with mock.patch.object(os, "walk", counting_walk): - first, _ = common._resolve_in_data_dirs(["font.bin"], registry, + first, _ = _resolve_in_data_dirs(["font.bin"], registry, lambda _p: "name_exact") - second, _ = common._resolve_in_data_dirs(["other.bin"], registry, + second, _ = _resolve_in_data_dirs(["other.bin"], registry, lambda _p: "name_exact") - common.forget_data_dir_index() + forget_data_dir_index() self.assertEqual(len(walks), 1) expected = sorted(str(p) for p in (cache / "a" / "Font.bin", cache / "b" / "font.bin")) self.assertIn(first[0], expected) @@ -4271,12 +4279,9 @@ class OpenMsxRomsSitInItsSystemroms(unittest.TestCase): them there.""" def test_every_entry_is_under_share_systemroms(self): - from scripts.common import ( - load_emulator_profiles, - load_platform_config, - platform_layouts, - standalone_set, - ) + from scripts.model.profiles import load_emulator_profiles + from scripts.model.platforms import load_platform_config + from scripts.resolve.standalone import platform_layouts, standalone_set profile = load_emulator_profiles(str(ROOT / "emulators"))["openmsx"] retrobat = yaml.safe_load((ROOT / "platforms" / "retrobat.yml").read_text()) @@ -4330,7 +4335,7 @@ class AnEmptyTargetIsNotEveryCore(unittest.TestCase): served gpsp's files only, the published list said null (every core).""" def test_the_published_list_is_the_builder_reading(self): - from scripts.common import load_target_config + from scripts.model.targets import load_target_config from scripts.generate_pack import generate_target_manifests tmp = Path(tempfile.mkdtemp(dir=TMP_ROOT)) @@ -4364,16 +4369,16 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase): self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, True)) def test_the_index_follows_a_swapped_tree(self): - from scripts import common + from scripts.resolve.datadirs import _data_dir_basenames cache = self.tmp / "cache" cache.mkdir() (cache / "old.rom").write_bytes(b"old") - self.assertIn("old.rom", common._data_dir_basenames(str(cache))) + self.assertIn("old.rom", _data_dir_basenames(str(cache))) cache.rename(self.tmp / "gone") cache.mkdir() (cache / "new.rom").write_bytes(b"new") - index = common._data_dir_basenames(str(cache)) + index = _data_dir_basenames(str(cache)) self.assertIn("new.rom", index) self.assertNotIn("old.rom", index) @@ -4756,7 +4761,8 @@ class TheIssueFormListsEveryPlatform(unittest.TestCase): """The missing-BIOS form offered 7 of the 12 registered platforms.""" def test_every_registered_platform_is_an_option(self): - from scripts.common import list_registered_platforms, load_platform_config + from scripts.model.registry import list_registered_platforms + from scripts.model.platforms import load_platform_config form = yaml.safe_load( (ROOT / ".github" / "ISSUE_TEMPLATE" / "missing-bios.yml").read_text() @@ -5049,7 +5055,8 @@ class SignaturesCarryTheirTypes(unittest.TestCase): # Lowered as modules are annotated, never raised. CEILING = 0 - COMPLETE = ("core/artifacts.py", "common.py", "resolve/validation.py", "generate_pack.py") + COMPLETE = ("core/artifacts.py", "model/platforms.py", "model/profiles.py", "resolve/localfile.py", + "resolve/validation.py", "generate_pack.py") @staticmethod def _missing(path: Path) -> list[str]: @@ -5105,7 +5112,9 @@ class EmuDeckRunsItsEmulatorsStandalone(unittest.TestCase): lost their standalone-only files.""" def test_every_emuscripts_emulator_is_standalone(self): - from scripts.common import load_platform_config, runs_standalone, load_emulator_profiles + from scripts.model.platforms import load_platform_config + from scripts.resolve.layout import runs_standalone + from scripts.model.profiles import load_emulator_profiles config = load_platform_config("emudeck", str(ROOT / "platforms")) self.assertEqual( @@ -5122,9 +5131,9 @@ class EmuDeckRunsItsEmulatorsStandalone(unittest.TestCase): """The scraper dropped RetroArch's own script: np2kai, neocd and every core EmuDeck installs through RetroArch got no file that checkBIOS.sh does not name.""" - from scripts.common import ( - load_emulator_profiles, load_platform_config, resolve_platform_cores, - ) + from scripts.model.profiles import load_emulator_profiles + from scripts.model.platforms import load_platform_config + from scripts.resolve.cores import resolve_platform_cores config = load_platform_config("emudeck", str(ROOT / "platforms")) self.assertIn("retroarch", config["cores"]) @@ -5419,7 +5428,8 @@ class BundledFilesAreNotToSource(unittest.TestCase): self.assertTrue(installed_with_emulator(hcl)) def test_every_platform_named_is_registered(self): - from common import list_registered_platforms, load_emulator_profiles + from model.registry import list_registered_platforms + from model.profiles import load_emulator_profiles known = set(list_registered_platforms(str(ROOT / "platforms"))) unknown = sorted({ @@ -5440,14 +5450,14 @@ class BundledFilesAreNotToSource(unittest.TestCase): import yaml as _yaml - import common + from model.profiles import installed_data_refs with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: Path(tmp, "dolphin.yml").write_text(_yaml.safe_dump({ "emulator": "Dolphin", "type": "libretro", "files": [], "data_directories": [{"ref": "dolphin-sys", "installed_on": ["lakka"]}]})) - self.assertEqual(common.installed_data_refs("lakka", tmp), frozenset({"dolphin-sys"})) - self.assertEqual(common.installed_data_refs("retroarch", tmp), frozenset()) + self.assertEqual(installed_data_refs("lakka", tmp), frozenset({"dolphin-sys"})) + self.assertEqual(installed_data_refs("retroarch", tmp), frozenset()) source = (ROOT / "scripts" / "generate_pack.py").read_text(encoding="utf-8") self.assertIn("if ref_key in installed_data_refs(platform_name):", source) @@ -5522,7 +5532,7 @@ class GapsPageCountsOneWay(unittest.TestCase): def test_the_destination_is_the_list_entrys(self): from scripts.generate_site import _declared_destination - from common import load_platform_config + from model.platforms import load_platform_config config = load_platform_config("amberelec", str(ROOT / "platforms")) detail = {"name": "N88_KNJ1.ROM", "system": "nec-pc-88"} @@ -5980,7 +5990,7 @@ const _EJS_NIGHTLY_CORES_MAP: Record = { parse_player_cores(source) def test_the_platform_file_carries_the_nightly_cores(self): - from common import load_platform_config + from model.platforms import load_platform_config cores = set(load_platform_config("romm", str(ROOT / "platforms"))["cores"]) self.assertTrue({"azahar", "bsnes", "genesis_plus_gx_wide"} <= cores) @@ -6092,7 +6102,7 @@ class TheReadmeCountsSystemsAsListSystemsDoes(unittest.TestCase): import re from contextlib import redirect_stdout - from scripts.common import list_system_ids + from scripts.model.cliargs import list_system_ids out = io.StringIO() with redirect_stdout(out): @@ -6163,7 +6173,7 @@ class AnAliasSelectsItsProfile(unittest.TestCase): import contextlib as _contextlib import io as _io - from scripts.common import ProfileSelectionError, select_emulator_profiles + from scripts.model.profiles import ProfileSelectionError, select_emulator_profiles profiles = { "flycast": {"type": "libretro", "cores": ["flycast", "flycast_gles2"]}, @@ -6277,7 +6287,7 @@ class TheRepairCommandWritesTheFileNamed(unittest.TestCase): command wrote another file and the next run failed the same way.""" def test_the_command_names_the_path(self): - from scripts.common import DatabaseUnreadable, load_database + from scripts.model.database import DatabaseUnreadable, load_database with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: target = str(Path(directory) / "nosuch.json") @@ -6292,7 +6302,7 @@ class TheRepairCommandWritesTheFileNamed(unittest.TestCase): def test_a_typo_beside_the_database_names_the_database(self): """--db databse.json beside database.json was told to rescan the whole collection into a second file named after the typo.""" - from scripts.common import DatabaseUnreadable, load_database + from scripts.model.database import DatabaseUnreadable, load_database with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: (Path(directory) / "database.json").write_text("{}") @@ -6338,7 +6348,8 @@ class AHashScanningCoreContradictsNoPlatform(unittest.TestCase): import json from scripts import slots - from scripts.common import list_registered_platforms, load_emulator_profiles + from scripts.model.registry import list_registered_platforms + from scripts.model.profiles import load_emulator_profiles root = ROOT if not (root / "database.json").exists(): @@ -6469,7 +6480,7 @@ class AHashScanLabelNamesNoOtherDump(unittest.TestCase): def test_labels_are_not_other_dumps_names(self): import json - from scripts.common import load_emulator_profiles + from scripts.model.profiles import load_emulator_profiles if not (ROOT / "database.json").exists(): self.skipTest("database.json is not built") @@ -6628,7 +6639,7 @@ class ABrokenRegistryIsNotAnEmptyOne(unittest.TestCase): and every --all build passed having checked nothing.""" def test_both_raise(self): - from scripts.common import list_registered_platforms + from scripts.model.registry import list_registered_platforms with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: with self.assertRaises(FileNotFoundError): @@ -6801,7 +6812,8 @@ class AnUnknownTargetIsRefusedUnderAll(unittest.TestCase): BizHawk and MiSTer unfiltered: a green run about no Switch at all.""" def test_a_typo_is_refused_and_targetless_platforms_are_left_out(self): - from scripts.common import build_target_cores_cache, list_registered_platforms + from scripts.model.targets import build_target_cores_cache + from scripts.model.registry import list_registered_platforms platforms = list_registered_platforms(str(ROOT / "platforms")) with contextlib.redirect_stdout(io.StringIO()): @@ -7028,7 +7040,8 @@ class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase): """The pull request checks run this suite, not the pipeline: without this, a copy only a bundled entry reaches merges green.""" import bundled_only - from common import load_database, load_emulator_profiles + from model.database import load_database + from model.profiles import load_emulator_profiles rows = bundled_only.bundled_only( load_database(str(ROOT / "database.json")), diff --git a/tests/test_batocera_cores.py b/tests/test_batocera_cores.py index 4e867d616..b96721cf0 100644 --- a/tests/test_batocera_cores.py +++ b/tests/test_batocera_cores.py @@ -82,7 +82,8 @@ class AnEmulatorLaunchedBothWaysGetsBothLayouts(unittest.TestCase): self.assertEqual(standalone & es_systems_libretro(text), {"dolphin"}) def test_the_layouts_are_both(self): - from common import DUAL_MODE_PREFIX, platform_layouts + from resolve.layout import DUAL_MODE_PREFIX + from resolve.standalone import platform_layouts profile = {"type": "standalone + libretro", "cores": ["dolphin"], "files": []} both = platform_layouts("dolphin", profile, {"dolphin", DUAL_MODE_PREFIX + "dolphin"}) @@ -127,7 +128,7 @@ class DualModeNameReachesTheLibretroBuild(unittest.TestCase): left out of the platform.""" def test_both_builds_of_a_dual_mode_name_resolve(self): - from common import resolve_platform_cores + from resolve.cores import resolve_platform_cores profiles = { "pcsx2": {"type": "standalone", "cores": ["pcsx2"]}, @@ -145,7 +146,7 @@ class APlatformsOwnBuildWinsItsName(unittest.TestCase): the standalone uae4all2: one name, two programs.""" def test_built_by_beats_the_key_match_for_that_platform_only(self): - from common import resolve_platform_cores + from resolve.cores import resolve_platform_cores profiles = { "uae4all": {"type": "standalone", "cores": ["uae4all"]}, @@ -164,7 +165,7 @@ class APatchedLibretroBuildTakesItsNameOnly(unittest.TestCase): the same name, stays.""" def test_own_libretro_build_keeps_the_standalone_of_a_dual_name(self): - from common import resolve_platform_cores + from resolve.cores import resolve_platform_cores profiles = { "pcsx2": {"type": "standalone", "source": "s", "cores": ["pcsx2"]}, @@ -179,7 +180,9 @@ class APatchedLibretroBuildTakesItsNameOnly(unittest.TestCase): self.assertEqual(resolve_platform_cores(config, profiles), {"lrps2-own"}) def test_the_registry_resolves_each_platform_build(self): - from common import load_emulator_profiles, load_platform_config, resolve_platform_cores + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from resolve.cores import resolve_platform_cores profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) platforms = str(REPO_ROOT / "platforms") diff --git a/tests/test_batocera_md5_list.py b/tests/test_batocera_md5_list.py index 19e6b6ada..c9bfa6714 100644 --- a/tests/test_batocera_md5_list.py +++ b/tests/test_batocera_md5_list.py @@ -17,7 +17,7 @@ import unittest import zipfile from pathlib import Path -from common import resolve_local_file +from resolve.localfile import resolve_local_file from exporter import discover_exporters from export_native import landed_changes from resolve.reconcile import NativeFile, build_native_model diff --git a/tests/test_bundled_identity.py b/tests/test_bundled_identity.py index 10313b90f..2f2dbe945 100644 --- a/tests/test_bundled_identity.py +++ b/tests/test_bundled_identity.py @@ -21,7 +21,8 @@ from pathlib import Path import yaml -from common import load_database, resolve_local_file +from model.database import load_database +from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_cache_independent_counts.py b/tests/test_cache_independent_counts.py index 77141ac0c..0f89237c9 100644 --- a/tests/test_cache_independent_counts.py +++ b/tests/test_cache_independent_counts.py @@ -21,13 +21,10 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class DeclaredFilesResolveWithoutDataCaches(unittest.TestCase): def test_no_platform_entry_rests_on_a_data_directory_cache(self): - from common import ( - build_zip_contents_index, - list_registered_platforms, - load_data_dir_registry, - load_database, - load_platform_config, - ) + from core.ziptools import build_zip_contents_index + from model.registry import list_registered_platforms, load_data_dir_registry + from model.database import load_database + from model.platforms import load_platform_config from packresolve import resolve_declaration platforms_dir = REPO_ROOT / "platforms" diff --git a/tests/test_case_insensitive_platforms.py b/tests/test_case_insensitive_platforms.py index d328781ef..d71960080 100644 --- a/tests/test_case_insensitive_platforms.py +++ b/tests/test_case_insensitive_platforms.py @@ -19,7 +19,7 @@ from pathlib import Path import yaml -from common import load_platform_config +from model.platforms import load_platform_config REPO_ROOT = Path(__file__).resolve().parents[1] @@ -42,7 +42,8 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): nothing about it.""" def setUp(self): - import common + from model.platforms import _platform_config_cache + from model.profiles import _emulator_profiles_cache import generate_db import generate_pack @@ -73,19 +74,19 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): "emulator": "mesence", "type": "libretro", "systems": ["coleco"], "files": [{"name": "bios.col", "required": True}], })) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.addCleanup(common._platform_config_cache.clear) - self.addCleanup(common._emulator_profiles_cache.clear) + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.addCleanup(_platform_config_cache.clear) + self.addCleanup(_emulator_profiles_cache.clear) def _readme(self, systems: list[str]) -> str: - import common + from model.platforms import _platform_config_cache Path("platforms/p.yml").write_text(yaml.dump(self.config)) Path("platforms/_registry.yml").write_text(yaml.dump({"platforms": {"p": { "install": {"detect": [{"os": os_name} for os_name in systems]}, }}})) - common._platform_config_cache.clear() + _platform_config_cache.clear() texts: dict[str, str] = {} real = self.gp._write_generated_member diff --git a/tests/test_casefold_cache.py b/tests/test_casefold_cache.py index 7d7d4116a..950d9eaba 100644 --- a/tests/test_casefold_cache.py +++ b/tests/test_casefold_cache.py @@ -7,7 +7,7 @@ import tests import unittest from pathlib import Path -from common import _casefold_name_index +from resolve.localfile import _casefold_name_index REPO_ROOT = Path(__file__).resolve().parents[1] @@ -54,7 +54,7 @@ class APrimaryUnderAnotherCasing(unittest.TestCase): self.by_name.setdefault(name, []).append(sha1) def _resolve(self, name: str) -> str: - from common import _casefold_index_cache, resolve_local_file + from resolve.localfile import _casefold_index_cache, resolve_local_file _casefold_index_cache.clear() db = {"files": self.files, "indexes": {"by_name": self.by_name, "by_md5": {}, diff --git a/tests/test_check_freshness.py b/tests/test_check_freshness.py index 808d3bfc0..3b0e7cef4 100644 --- a/tests/test_check_freshness.py +++ b/tests/test_check_freshness.py @@ -19,7 +19,7 @@ from unittest import mock from pathlib import Path import check_freshness as cf -from common import yaml_load +from model.safeparse import yaml_load REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_content_checks.py b/tests/test_content_checks.py index 7ffd40b58..a049b1215 100644 --- a/tests/test_content_checks.py +++ b/tests/test_content_checks.py @@ -19,7 +19,9 @@ import tempfile import unittest from pathlib import Path -import common +from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from resolve.content import content_fits, size_fits, _masked_sha1_verdict +from resolve.localfile import resolve_local_file import generate_pack as builder import packextras from core.romdir import romdir_accepts, walk @@ -191,21 +193,21 @@ class OtherContentTests(unittest.TestCase): config[0x20] ^= 0xFF reconfigured = Path(tmp, "reconfigured.rom") reconfigured.write_bytes(bytes(config)) - self.assertTrue(common.content_fits(entry_, str(good))) - self.assertTrue(common.content_fits(entry_, str(reconfigured))) - self.assertTrue(common.content_fits(entry_, str(other))) # past 0x1c000 - self.assertFalse(common.content_fits(entry_, str(short))) + self.assertTrue(content_fits(entry_, str(good))) + self.assertTrue(content_fits(entry_, str(reconfigured))) + self.assertTrue(content_fits(entry_, str(other))) # past 0x1c000 + self.assertFalse(content_fits(entry_, str(short))) payload[0x100] ^= 1 good.write_bytes(bytes(payload)) - common._masked_sha1_verdict.cache_clear() - self.assertFalse(common.content_fits(entry_, str(good))) + _masked_sha1_verdict.cache_clear() + self.assertFalse(content_fits(entry_, str(good))) def test_size_multiple(self): flash = {"min_size": 65536, "size_multiple": 65536, "validation": ["size"]} - self.assertTrue(common.size_fits(flash, 262144)) - self.assertTrue(common.size_fits(flash, 65536 * 3)) - self.assertFalse(common.size_fits(flash, 65536 + 1)) - self.assertFalse(common.size_fits(flash, 0)) + self.assertTrue(size_fits(flash, 262144)) + self.assertTrue(size_fits(flash, 65536 * 3)) + self.assertFalse(size_fits(flash, 65536 + 1)) + self.assertFalse(size_fits(flash, 0)) class ScannerVerifyManifestAgree(unittest.TestCase): @@ -255,13 +257,13 @@ class ScannerVerifyManifestAgree(unittest.TestCase): " - name: \".nvm\"\n path: \"ps2/.nvm\"\n size: 1024\n" " - name: \".mec\"\n path: \"ps2/.mec\"\n size: 4\n" ) - common._emulator_profiles_cache.clear() - self.profiles = common.load_emulator_profiles(str(self.root / "emulators")) + _emulator_profiles_cache.clear() + self.profiles = load_emulator_profiles(str(self.root / "emulators")) self.config = {"platform": "Demo", "verification_mode": "existence", "cores": ["demo", "anchor"], "base_destination": "", "systems": {}} def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def accepted(self) -> set[str]: @@ -269,7 +271,7 @@ class ScannerVerifyManifestAgree(unittest.TestCase): beside an accepted image of its stem.""" seed = self.profiles["demo"]["files"][0] images = {n for n in self.IMAGES - if common.content_fits(seed, str(self.root / "bios" / "PS2" / n))} + if content_fits(seed, str(self.root / "bios" / "PS2" / n))} stems = {n.rsplit(".", 1)[0] for n in images} return images | {n for n in self.COMPANIONS if n.rsplit(".", 1)[0] in stems} @@ -300,7 +302,7 @@ class ScannerVerifyManifestAgree(unittest.TestCase): path = str(self.root / "bios" / "PS2" / name) entry_ = {"name": name, "found_by": "content", "validation": ["romdir"], "romdir": MODERN, "source_profile": "labels"} - resolved, status = common.resolve_local_file(entry_, self.db) + resolved, status = resolve_local_file(entry_, self.db) failure = check_file_validation(path, name, index) with self.subTest(name=name): accepted = name in self.accepted() diff --git a/tests/test_content_declarations.py b/tests/test_content_declarations.py index 92310a661..ea5234558 100644 --- a/tests/test_content_declarations.py +++ b/tests/test_content_declarations.py @@ -12,7 +12,7 @@ import tests import unittest -from common import platform_declared_contents +from model.declarations import platform_declared_contents from resolve.validation import declaration_settles SHA1 = "70cdf57469a208528f78a14275837352e90e20f1" diff --git a/tests/test_contributing_text.py b/tests/test_contributing_text.py index ef21ea8c8..d585e9e3f 100644 --- a/tests/test_contributing_text.py +++ b/tests/test_contributing_text.py @@ -184,7 +184,7 @@ class OneFileThroughTheBrowser(unittest.TestCase): with tempfile.TemporaryDirectory(dir=scratch) as directory: (Path(directory) / "bios").mkdir() (Path(directory) / "bios" / "boot.rom").write_bytes(b"boot") - from common import compute_hashes + from core.hashing import compute_hashes sha1 = compute_hashes(str(Path(directory) / "bios" / "boot.rom"))["sha1"] hashes = {"sha1": {sha1}, "folders": {sha1: {"bios/Maker/Console/"}}} diff --git a/tests/test_core_data_trees.py b/tests/test_core_data_trees.py index 3431462bd..7cf96e29b 100644 --- a/tests/test_core_data_trees.py +++ b/tests/test_core_data_trees.py @@ -16,7 +16,12 @@ import os import unittest from pathlib import Path -import common +from model.database import load_database +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles, installed_data_refs +from model.registry import load_data_dir_registry, list_registered_platforms +from resolve.cores import resolve_platform_cores +from resolve.standalone import platform_layouts, standalone_set import generate_pack as builder from resolve.validation import deliverable, read_from_system_dir @@ -123,19 +128,19 @@ class EveryReaderHasTheTreeOrAReason(unittest.TestCase): def test_for_platforms_leaves_no_reader_without_a_reason(self) -> None: platforms_dir = str(REPO_ROOT / "platforms") - registry = common.load_data_dir_registry(platforms_dir) - profiles = common.load_emulator_profiles(str(REPO_ROOT / "emulators")) + registry = load_data_dir_registry(platforms_dir) + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) unexplained = [] - for platform in common.list_registered_platforms(platforms_dir): - config = common.load_platform_config(platform, platforms_dir) - handed = common.standalone_set(config) - for core in sorted(common.resolve_platform_cores(config, profiles)): + for platform in list_registered_platforms(platforms_dir): + config = load_platform_config(platform, platforms_dir) + handed = standalone_set(config) + for core in sorted(resolve_platform_cores(config, profiles)): profile = profiles[core] if all(standalone for _view, standalone - in common.platform_layouts(core, profile, handed)): + in platform_layouts(core, profile, handed)): continue trees = [t for t in profile.get("data_directories") or [] if isinstance(t, dict)] - installed = common.installed_data_refs(platform) + installed = installed_data_refs(platform) for tree in deliverable(trees, False, platform): allowed = registry.get(tree.get("ref"), {}).get("for_platforms") if tree.get("ref") in installed or not read_from_system_dir(tree): @@ -162,9 +167,9 @@ class AmberelecCarriesTheMachines(unittest.TestCase): cwd = os.getcwd() os.chdir(REPO_ROOT) try: - config = common.load_platform_config("amberelec", platforms_dir) - registry = common.load_data_dir_registry(platforms_dir) - profiles = common.load_emulator_profiles(str(REPO_ROOT / "emulators")) + config = load_platform_config("amberelec", platforms_dir) + registry = load_data_dir_registry(platforms_dir) + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) trees = builder.core_data_trees(config, profiles, "amberelec", registry) refs: dict = {} members = dict( @@ -194,13 +199,13 @@ class TheCountLineKeepsTreesOutOfTheBaseline(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) - db = common.load_database("database.json") + db = load_database("database.json") record = builder.PackRecord() out = io.StringIO() with contextlib.redirect_stdout(out): builder.generate_pack( "myminui", "platforms", db, "bios", "tmp", offline=True, record=record, - data_registry=common.load_data_dir_registry("platforms"), + data_registry=load_data_dir_registry("platforms"), ) line = next(entry for entry in out.getvalue().splitlines() if "files packed" in entry) self.assertIn("(0 baseline + ", line) diff --git a/tests/test_core_file_fills_declaration.py b/tests/test_core_file_fills_declaration.py index bde19394a..397c54efa 100644 --- a/tests/test_core_file_fills_declaration.py +++ b/tests/test_core_file_fills_declaration.py @@ -23,7 +23,8 @@ from unittest import mock import yaml -from common import _emulator_profiles_cache, load_platform_config +from model.profiles import _emulator_profiles_cache +from model.platforms import load_platform_config from generate_pack import generate_pack from verify import verify_platform diff --git a/tests/test_core_size_refusal.py b/tests/test_core_size_refusal.py index 1df8b6a8d..120508b1c 100644 --- a/tests/test_core_size_refusal.py +++ b/tests/test_core_size_refusal.py @@ -21,7 +21,8 @@ from pathlib import Path import yaml -import common +from model.platforms import _platform_config_cache +from model.profiles import load_emulator_profiles, _emulator_profiles_cache import generate_db import generate_pack as builder from resolve.validation import core_size_refusal @@ -86,13 +87,13 @@ class _Collection(unittest.TestCase): ) Path("emulators/sized.yml").write_text(SIZED) Path("emulators/unsized.yml").write_text(UNSIZED) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.profiles = common.load_emulator_profiles("emulators") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.profiles = load_emulator_profiles("emulators") def tearDown(self): - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() os.chdir(self._cwd) self._tmp.cleanup() @@ -156,8 +157,8 @@ class SizeTheCoreRefuses(_Collection): Path("emulators/sized.yml").write_text( SIZED + " - name: ROM\n path: ROM\n size: 8\n validation: [size]\n" ) - common._emulator_profiles_cache.clear() - self.profiles = common.load_emulator_profiles("emulators") + _emulator_profiles_cache.clear() + self.profiles = load_emulator_profiles("emulators") self.assertTrue(self._report("sized")["in_repo"]) self.assertIn("ROM", self._pack_members()) self.assertIn("ROM", {f["dest"] for f in self._manifest()["files"]}) diff --git a/tests/test_deterministic_zip.py b/tests/test_deterministic_zip.py index 77f6c0453..b6d3cf5bd 100644 --- a/tests/test_deterministic_zip.py +++ b/tests/test_deterministic_zip.py @@ -313,14 +313,14 @@ class TestPackDeterminism(unittest.TestCase): " system: test-sys\n" " required: true\n" ) - import common + from model.profiles import _emulator_profiles_cache - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() path = generate_emulator_pack( ["detcore"], str(self.tmp / "emulators"), self.db, str(self.bios), str(out), offline=True, ) - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self.assertIsNotNone(path) return Path(path) diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index 197f3d7a2..9e081cae0 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -25,7 +25,8 @@ try: import jsonschema except ImportError: jsonschema = None -import common +from model.profiles import load_emulator_profiles, _emulator_profiles_cache +from resolve.directories import directory_members import generate_db import generate_pack as builder import verify @@ -87,10 +88,10 @@ class DirectoryFixture(unittest.TestCase): (self.platforms / "_registry.yml").write_text( yaml.dump({"platforms": {"demo": {"config": "demo.yml"}}}) ) - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def _add(self, relative: str, payload: bytes) -> None: @@ -120,14 +121,14 @@ class DirectoryFixture(unittest.TestCase): def _profiles(self, body: str = PROFILE) -> dict: (self.emulators / "demo.yml").write_text(body) - common._emulator_profiles_cache.clear() - return common.load_emulator_profiles(str(self.emulators)) + _emulator_profiles_cache.clear() + return load_emulator_profiles(str(self.emulators)) class DirectoryMembers(DirectoryFixture): def test_every_file_under_the_tail_is_a_member(self): self.assertEqual( - common.directory_members(self._db(), "rtp/2000/"), + directory_members(self._db(), "rtp/2000/"), { "rtp/2000/Backdrop/a.png": self.sha1[ "Engine/demo/rtp/2000/Backdrop/a.png" @@ -137,19 +138,19 @@ class DirectoryMembers(DirectoryFixture): ) def test_a_directory_nobody_collected_has_no_member(self): - self.assertEqual(common.directory_members(self._db(), "demo/Fonts/"), {}) + self.assertEqual(directory_members(self._db(), "demo/Fonts/"), {}) def test_two_trees_answering_one_tail_prove_nothing(self): """`voice/` under two unrelated parents is two directories, and merging them would hand one emulator the other's files.""" self._add("Console/voice/E480.WAV", b"speech") self._add("Other/app/voice/hello.wav", b"another program") - self.assertEqual(common.directory_members(self._db(), "voice/"), {}) + self.assertEqual(directory_members(self._db(), "voice/"), {}) def test_one_tree_under_a_generic_name_is_enough(self): self._add("Console/voice/E480.WAV", b"speech") self.assertEqual( - common.directory_members(self._db(), "voice/"), + directory_members(self._db(), "voice/"), {"voice/E480.WAV": self.sha1["Console/voice/E480.WAV"]}, ) diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index d6bf86074..e04d87896 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -238,9 +238,9 @@ class OneResolutionChain(unittest.TestCase): ORDER = ("SHA1", "SHA256", "CRC32", "MD5", "Path suffix") def test_the_table_follows_the_code(self): - import common + from resolve.localfile import resolve_local_file - source = inspect.getsource(common.resolve_local_file) + source = inspect.getsource(resolve_local_file) steps = re.findall(r"# \d+[a-z]?\. (SHA1|SHA256|CRC32|MD5|Path suffix)", source) self.assertEqual(tuple(dict.fromkeys(steps)), self.ORDER) table = _table_rows(_section(_page("verification-modes.md"), "File resolution chain")) @@ -460,13 +460,13 @@ class Md5CompositeDefinition(unittest.TestCase): def test_composite_only_is_read_by_both_checks(self): """The page said the direct MD5 is tried before the composite, which Recalbox never does for a .zip, and the pack check did the same.""" - import common + from resolve.localfile import resolve_local_file from resolve import validation section = _section(_page("verification-modes.md"), "md5_composite (Recalbox ZIP verification)") self.assertIn("zip_digest: composite", section) self.assertNotIn("is tried before reporting a mismatch", section) - for function in (common.resolve_local_file, validation.digest_verdict): + for function in (resolve_local_file, validation.digest_verdict): self.assertIn('get("zip_digest") == "composite"', inspect.getsource(function)) @@ -493,16 +493,16 @@ class CoreResolutionWrittenOnce(unittest.TestCase): def test_one_statement_matching_the_platforms_and_the_code(self): import yaml - import common + from resolve.cores import resolve_platform_cores, _platform_profiles self.assertNotIn("cores: [list]", _page("architecture.md")) # resolve_platform_cores narrows by target, _platform_profiles holds # the strategies. - source = inspect.getsource(common._platform_profiles) + source = inspect.getsource(_platform_profiles) self.assertIn('not p.get("built_by")', source) self.assertIn('"retroarch" in core_set', source) self.assertIn('config.get("installable_cores")', source) - self.assertIn("downloadable_on", inspect.getsource(common.resolve_platform_cores)) + self.assertIn("downloadable_on", inspect.getsource(resolve_platform_cores)) naming = set() for path in (ROOT / "platforms").glob("*.yml"): config = yaml.safe_load(path.read_text(encoding="utf-8")) or {} @@ -667,12 +667,12 @@ class ShortMd5Handling(unittest.TestCase): self.assertEqual(offenders, []) def test_the_page_names_what_the_code_does(self): - import common + from resolve.localfile import resolve_local_file from scraper import batocera_scraper scraper = inspect.getsource(batocera_scraper) self.assertIn("_resolve_truncated_md5(value, md5_index) for value in values", scraper) - resolver = inspect.getsource(common.resolve_local_file) + resolver = inspect.getsource(resolve_local_file) self.assertIn("cut_md5_owner(cut, by_md5)", resolver) self.assertIn("_md5_name_ok(path)", resolver) section = _section(_page("verification-modes.md"), "MD5 shorter than 32 characters (Batocera)") @@ -695,9 +695,9 @@ class RegistryKeysDocumented(unittest.TestCase): self.assertEqual(sorted(k for k in keys if not re.search(rf"\b{k}\b", page)), []) def test_the_page_says_the_registry_reaches_the_config(self): - import common + from model import platforms - source = inspect.getsource(common.load_platform_config) + source = inspect.getsource(platforms.load_platform_config) self.assertIn("config[key] = val", source) section = _section(_page("adding-a-platform.md"), "Step 2: Register the platform") self.assertIn("copies every registry key", section) @@ -710,9 +710,9 @@ class ResolutionSkipsNamesForUnheldFiles(unittest.TestCase): disk, skips every step that answers by name and returns not_found.""" def test_the_page_names_both_cases_the_code_guards(self): - import common + from resolve.localfile import resolve_local_file - source = inspect.getsource(common.resolve_local_file) + source = inspect.getsource(resolve_local_file) self.assertIn('unsourceable = bool(file_entry.get("unsourceable")) or own_file_absent', source) for guard in ( "if not has_strong_hash and not unsourceable:", @@ -1114,9 +1114,9 @@ class PlatformListsFollowTheRegistry(unittest.TestCase): return names def _modes(self) -> dict[str, str]: - import common + from model import platforms - return {key: common.load_platform_config(key, str(ROOT / "platforms")).get("verification_mode") + return {key: platforms.load_platform_config(key, str(ROOT / "platforms")).get("verification_mode") for key in _registry()} def _split(self, text: str) -> set[str]: @@ -2027,8 +2027,9 @@ class RegionFreeRuleNamesWhereItDoesNotHold(unittest.TestCase): where it is the only PlayStation core the filter drops it.""" def test_every_platform_that_drops_a_named_file_is_named(self): - 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 from region import WORLD, platform_region_index section = _section(_page("advanced-usage.md"), "Region filtering") diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index 90057de2c..a0bc0f36d 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -85,7 +85,7 @@ class TheDownloadTablesFollowTheRegistry(unittest.TestCase): def test_every_detected_system_lists_the_platform(self): import yaml - from common import load_platform_config + from model.platforms import load_platform_config registry = yaml.safe_load(_read("platforms/_registry.yml")) page = _which_pack() @@ -186,7 +186,7 @@ class DownloadLinksKeepTheirAddress(unittest.TestCase): def test_the_generated_readme_links_every_get_page(self): if not RECORD.get("packs"): self.skipTest("release.json is not written") - from common import list_registered_platforms, list_release_pack_platforms + from model.registry import list_registered_platforms, list_release_pack_platforms readme = _read("README.md") table = _section(readme, "## Or download a ZIP") @@ -212,7 +212,8 @@ class DownloadLinksKeepTheirAddress(unittest.TestCase): """KNULLI, AmberELEC and EmuELEC were registered after the recorded release, and the platforms without release_pack never get a ZIP: a row for them offers the command.""" - from common import list_registered_platforms, load_platform_config + from model.registry import list_registered_platforms + from model.platforms import load_platform_config import generate_site record = release_record.load_advertised() @@ -445,7 +446,9 @@ class CoreCountsReadFromTheData(unittest.TestCase): def test_the_run_count_is_what_the_platforms_resolve(self): import yaml - from common import load_emulator_profiles, load_platform_config, resolve_platform_cores + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from resolve.cores import resolve_platform_cores from tests import sitepages diff --git a/tests/test_e2e.py b/tests/test_e2e.py index a1684513d..ca06a6b8b 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -33,20 +33,14 @@ from unittest import mock from model import largefiles import yaml -from common import ( - build_zip_contents_index, - check_inside_zip, - compute_hashes, - expand_platform_declared_names, - group_identical_platforms, - load_emulator_profiles, - load_platform_config, - md5_composite, - parse_md5_list, - resolve_local_file, - resolve_platform_cores, - safe_extract_zip, -) +from core.ziptools import build_zip_contents_index, check_inside_zip, safe_extract_zip +from core.hashing import compute_hashes, md5_composite, parse_md5_list +from model.declarations import expand_platform_declared_names +from resolve.grouping import group_identical_platforms +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from resolve.localfile import resolve_local_file +from resolve.cores import resolve_platform_cores from resolve.truth import diff_platform_truth, generate_platform_truth from resolve.validation import _build_validation_index, check_file_validation, filter_files_by_mode from verify import ( @@ -85,7 +79,7 @@ class TestE2E(unittest.TestCase): def setUp(self): # Clear emulator profile cache to avoid stale data between tests - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() @@ -917,7 +911,7 @@ class TestE2E(unittest.TestCase): def test_24b_a_held_group_member_makes_the_others_optional(self): """RetroBat's group: one file held is enough (batocera-systems/Program.cs).""" - from common import _platform_config_cache + from model.platforms import _platform_config_cache with open(os.path.join(self.platforms_dir, "test_md5.yml")) as fh: config = yaml.safe_load(fh) @@ -1893,21 +1887,21 @@ class TestE2E(unittest.TestCase): def test_load_target_config(self): self._write_target_fixtures() - from common import load_target_config + from model.targets import load_target_config cores = load_target_config("testplatform", "target-minimal", self.platforms_dir) self.assertEqual(cores, {"core_a"}) def test_target_alias_resolution(self): self._write_target_fixtures() - from common import load_target_config + from model.targets import load_target_config cores = load_target_config("testplatform", "full", self.platforms_dir) self.assertEqual(cores, {"core_a", "core_b", "core_d"}) def test_target_unknown_error(self): self._write_target_fixtures() - from common import load_target_config + from model.targets import load_target_config with self.assertRaises(ValueError) as ctx: load_target_config("testplatform", "nonexistent", self.platforms_dir) @@ -1916,7 +1910,7 @@ class TestE2E(unittest.TestCase): def test_target_override_add_remove(self): self._write_target_fixtures() - from common import load_target_config + from model.targets import load_target_config cores = load_target_config("testplatform", "full", self.platforms_dir) self.assertIn("core_d", cores) @@ -1927,7 +1921,7 @@ class TestE2E(unittest.TestCase): def test_target_default_override_reaches_every_target(self): """`_default` drops a name on every target, then the target adds its own.""" self._write_target_fixtures() - from common import load_target_config + from model.targets import load_target_config targets_dir = os.path.join(self.platforms_dir, "targets") overrides = { @@ -1953,7 +1947,7 @@ class TestE2E(unittest.TestCase): def test_target_single_target_noop(self): self._write_target_fixtures() - from common import load_target_config + from model.targets import load_target_config cores = load_target_config("singleplatform", "only-target", self.platforms_dir) self.assertEqual(cores, {"core_a", "core_b"}) @@ -1974,7 +1968,7 @@ class TestE2E(unittest.TestCase): } with open(os.path.join(targets_dir, "childplatform.yml"), "w") as f: yaml.dump(child_config, f) - from common import load_target_config + from model.targets import load_target_config parent = load_target_config( "testplatform", "target-minimal", self.platforms_dir @@ -2441,7 +2435,7 @@ class TestE2E(unittest.TestCase): def test_133_platform_system_filter_normalized(self): """_norm_system_id normalization matches with manufacturer prefix.""" - from common import _norm_system_id + from model.systems import _norm_system_id self.assertEqual( _norm_system_id("sony-playstation"), @@ -2452,7 +2446,7 @@ class TestE2E(unittest.TestCase): """list_platform_system_ids lists systems from a platform YAML.""" import io - from common import list_platform_system_ids + from model.cliargs import list_platform_system_ids config = { "platform": "ListSysTest", @@ -2507,7 +2501,7 @@ class TestE2E(unittest.TestCase): with open(file_b, "wb") as f: f.write(b"system_b") - from common import compute_hashes + from core.hashing import compute_hashes ha = compute_hashes(file_a) hb = compute_hashes(file_b) @@ -2557,7 +2551,8 @@ class TestE2E(unittest.TestCase): with open(os.path.join(plat_dir, "splitplat.yml"), "w") as f: yaml.dump(plat_cfg, f) - from common import build_zip_contents_index, load_emulator_profiles + from core.ziptools import build_zip_contents_index + from model.profiles import load_emulator_profiles from generate_pack import generate_split_packs zip_contents = build_zip_contents_index(db) @@ -2594,7 +2589,7 @@ class TestE2E(unittest.TestCase): def test_136_derive_manufacturer(self): """derive_manufacturer extracts manufacturer correctly.""" - from common import derive_manufacturer + from model.systems import derive_manufacturer # From system ID prefix self.assertEqual(derive_manufacturer("sony-playstation", {}), "Sony") @@ -2738,7 +2733,7 @@ class TestE2E(unittest.TestCase): bios_file = os.path.join(bios_dir, "scph5501.bin") with open(bios_file, "wb") as f: f.write(b"ps1_bios_content") - from common import compute_hashes + from core.hashing import compute_hashes h = compute_hashes(bios_file) @@ -2783,7 +2778,7 @@ class TestE2E(unittest.TestCase): with open(os.path.join(plat_dir, "testplat.yml"), "w") as f: yaml.dump(plat_cfg, f) - from common import build_zip_contents_index + from core.ziptools import build_zip_contents_index from generate_pack import generate_md5_pack zip_contents = build_zip_contents_index(db) @@ -3404,7 +3399,7 @@ class TestE2E(unittest.TestCase): _yaml.dump(profile, f) # Clear profile cache so fresh load picks up our file - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() @@ -3434,7 +3429,7 @@ class TestE2E(unittest.TestCase): def test_169_generate_truth_mode_filtering(self): """generate_platform_truth excludes standalone-only files for all_libretro.""" import yaml as _yaml - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache profile = { "emulator": "DualMode", @@ -3484,7 +3479,7 @@ class TestE2E(unittest.TestCase): def test_170_generate_truth_standalone_cores(self): """generate_platform_truth uses standalone mode for standalone_cores.""" import yaml as _yaml - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache profile = { "emulator": "DualCore", @@ -3527,7 +3522,7 @@ class TestE2E(unittest.TestCase): def test_171_generate_truth_dedup_required_wins(self): """Dedup merges cores and required=True wins over required=False.""" import yaml as _yaml - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache core_a = { "emulator": "CoreA", @@ -3582,7 +3577,7 @@ class TestE2E(unittest.TestCase): def test_172_generate_truth_coverage_metadata(self): """Coverage tracks profiled vs unprofiled cores.""" import yaml as _yaml - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache profile = { "emulator": "ProfiledCore", @@ -3747,7 +3742,7 @@ class TestE2E(unittest.TestCase): A YAML without one, an inheriting child included, is refused rather than written with a stand-in or its parent's version. """ - from common import _platform_config_cache + from model.platforms import _platform_config_cache from generate_pack import generate_manifest registry_path = os.path.join(self.platforms_dir, "_test_registry_version.yml") @@ -3803,7 +3798,7 @@ class TestE2E(unittest.TestCase): entry["sha1"] = "0" * 40 # upstream hash, absent from the repo with open(config_path, "w") as fh: yaml.dump(config, fh) - from common import _platform_config_cache + from model.platforms import _platform_config_cache _platform_config_cache.clear() @@ -4405,7 +4400,7 @@ class TestE2E(unittest.TestCase): # No profile for core_b (unprofiled) # Clear cache so the new profile is picked up - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() profiles = load_emulator_profiles(self.emulators_dir) @@ -4509,7 +4504,7 @@ class TestE2E(unittest.TestCase): def test_175_registry_merge_cores(self): """load_platform_config merges cores from _registry.yml.""" - from common import _platform_config_cache + from model.platforms import _platform_config_cache # Platform YAML with 1 core config = { @@ -4540,7 +4535,8 @@ class TestE2E(unittest.TestCase): def test_176_all_libretro_in_list(self): """resolve_platform_cores expands all_libretro/retroarch in a list.""" - from common import load_emulator_profiles, resolve_platform_cores + from model.profiles import load_emulator_profiles + from resolve.cores import resolve_platform_cores # Create a libretro profile and a standalone profile for name, ptype in [("lr_core", "libretro"), ("sa_core", "standalone")]: @@ -5253,7 +5249,7 @@ struct BurnDriver BurnDrvneogeo = { with zipfile.ZipFile(zip_src, "w", zipfile.ZIP_DEFLATED) as zf: info = zipfile.ZipInfo("rom.bin", date_time=(2020, 6, 15, 12, 0, 0)) zf.writestr(info, b"rom_content_bytes") - from common import compute_hashes + from core.hashing import compute_hashes h = compute_hashes(zip_src) @@ -5427,7 +5423,7 @@ struct BurnDriver BurnDrvneogeo = { """resolve_local_file matches files by declared sha256.""" import tempfile - from common import resolve_local_file + from resolve.localfile import resolve_local_file with tempfile.TemporaryDirectory() as tmpdir: path = os.path.join(tmpdir, "SNES_dsp1.rom") @@ -5472,7 +5468,7 @@ struct BurnDriver BurnDrvneogeo = { import tempfile import urllib.error - import common + from model.largefiles import fetch_large_file attempts = [] @@ -5503,7 +5499,7 @@ struct BurnDriver BurnDrvneogeo = { with tempfile.TemporaryDirectory() as tmpdir, mock.patch.dict( os.environ, {"RETROBIOS_OFFLINE": ""} ): - path = common.fetch_large_file( + path = fetch_large_file( "MAME 0.174 Arcade XML.dat", dest_dir=tmpdir ) self.assertIsNotNone(path) @@ -5534,7 +5530,7 @@ struct BurnDriver BurnDrvneogeo = { import tempfile import zlib - from common import resolve_local_file + from resolve.localfile import resolve_local_file with tempfile.TemporaryDirectory() as tmpdir: data = b"exos rom bytes" * 100 @@ -5574,7 +5570,7 @@ struct BurnDriver BurnDrvneogeo = { """Name resolution falls back to a case-insensitive match.""" import tempfile - from common import resolve_local_file + from resolve.localfile import resolve_local_file with tempfile.TemporaryDirectory() as tmpdir: path = os.path.join(tmpdir, "VEC_Minestorm.vec") @@ -5605,7 +5601,7 @@ struct BurnDriver BurnDrvneogeo = { import hashlib as hl import tempfile - from common import resolve_local_file + from resolve.localfile import resolve_local_file rom = b"inner rom bytes" rom_md5 = hl.md5(rom).hexdigest() @@ -6075,7 +6071,7 @@ struct BurnDriver BurnDrvneogeo = { self.assertNotIn("rgn_jp.bin", names) def test_verify_platform_region_matches_the_pack(self): - from common import load_platform_config + from model.platforms import load_platform_config from verify import verify_platform self._create_region_fixtures() @@ -6773,7 +6769,7 @@ class StandaloneModeRequiresAStandaloneBuild(unittest.TestCase): profile loses every ``path:`` and drops its files at the root.""" def test_libretro_only_profile_keeps_its_layout(self): - from common import runs_standalone + from resolve.layout import runs_standalone libretro_only = {"type": "libretro", "cores": ["scummvm"]} dual = {"type": "standalone + libretro", "cores": ["dolphin"]} @@ -6800,7 +6796,7 @@ class OneOfASearchList(unittest.TestCase): """ def setUp(self): - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() repo = Path(__file__).resolve().parent.parent @@ -6985,7 +6981,7 @@ class OneOfASearchList(unittest.TestCase): def test_an_archive_needs_one_member_of_a_set(self): import zlib - from common import holds_required_members + from resolve.archives import holds_required_members path = self.root / "set.zip" with zipfile.ZipFile(path, "w") as zf: @@ -7066,7 +7062,7 @@ class AnArchiveIsAMemberOfASet(unittest.TestCase): def _fixture(self, held: bool) -> dict: import zlib - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() repo = Path(__file__).resolve().parent.parent diff --git a/tests/test_elec_scrapers.py b/tests/test_elec_scrapers.py index 1e65e9512..ca7f5aff5 100644 --- a/tests/test_elec_scrapers.py +++ b/tests/test_elec_scrapers.py @@ -240,7 +240,7 @@ class CoreFilesGoUnderTheStatedFolder(unittest.TestCase): /storage/roms itself, where no core reads them.""" def test_core_destination_wins_over_the_guess(self): - from common import declared_root + from model.declarations import declared_root files = [{"destination": f"bios/f{i}"} for i in range(3)] files.append({"destination": "ports/diablo/diabdat.mpq"}) diff --git a/tests/test_emulator_pack_counts.py b/tests/test_emulator_pack_counts.py index 55dff2a58..590bbc960 100644 --- a/tests/test_emulator_pack_counts.py +++ b/tests/test_emulator_pack_counts.py @@ -80,7 +80,7 @@ class APlaceholderIsAnsweredByEvidence(unittest.TestCase): import yaml - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache from generate_pack import generate_emulator_pack from verify import verify_emulator diff --git a/tests/test_export_native_layer.py b/tests/test_export_native_layer.py index 7113c8363..ccfe9458e 100644 --- a/tests/test_export_native_layer.py +++ b/tests/test_export_native_layer.py @@ -16,7 +16,7 @@ import tempfile import unittest from pathlib import Path -import common +from model.platforms import load_platform_config, _shared_yml_cache, _platform_config_cache from export_native import load_inputs REPO_ROOT = Path(__file__).resolve().parent.parent @@ -24,10 +24,10 @@ REPO_ROOT = Path(__file__).resolve().parent.parent class TheNativeLayerIsThePlatformsOwn(unittest.TestCase): def setUp(self): - common._platform_config_cache.clear() - common._shared_yml_cache.clear() - self.addCleanup(common._platform_config_cache.clear) - self.addCleanup(common._shared_yml_cache.clear) + _platform_config_cache.clear() + _shared_yml_cache.clear() + self.addCleanup(_platform_config_cache.clear) + self.addCleanup(_shared_yml_cache.clear) def test_shared_and_mirrored_entries_are_left_out(self): with tempfile.TemporaryDirectory() as tmp: @@ -48,7 +48,7 @@ class TheNativeLayerIsThePlatformsOwn(unittest.TestCase): " - name: dsp_rom.bin\n destination: dolphin-emu/Sys/GC/dsp_rom.bin\n" " curated: true\n" ) - pack_view = common.load_platform_config("demo", str(platforms)) + pack_view = load_platform_config("demo", str(platforms)) _truth, native = load_inputs("demo", platforms / "truth", str(platforms)) self.assertEqual( diff --git a/tests/test_export_report.py b/tests/test_export_report.py index 496ec375f..0ef0d5ab4 100644 --- a/tests/test_export_report.py +++ b/tests/test_export_report.py @@ -296,7 +296,7 @@ def _parse_dat(text: str) -> dict[tuple[str, str], dict[str, str]]: def _parse_es_bios(text: str) -> dict[tuple[str, str], dict[str, str]]: """Each bios element of an es_bios.xml, keyed by system and path.""" - from common import parse_untrusted_xml + from model.safeparse import parse_untrusted_xml root = parse_untrusted_xml(text) elements: dict[tuple[str, str], dict[str, str]] = {} @@ -315,7 +315,7 @@ class ReportedChangesAreTheDiff(unittest.TestCase): entry, or a maintainer checks the diff against a list that differs.""" def _run(self, platform: str, filename: str) -> tuple[list[dict], str, str, dict]: - from common import load_platform_config, native_layer + from model.platforms import load_platform_config, native_layer from exporter import discover_exporters from resolve.reconcile import build_native_model @@ -392,7 +392,7 @@ class ReportedChangesAreTheDiff(unittest.TestCase): def test_retropie(self): """Each addition is a name a help sentence gains, and no other: the report counted every file a profiled core reads as added.""" - from common import load_platform_config, native_layer + from model.platforms import load_platform_config, native_layer from exporter import discover_exporters from resolve.reconcile import build_native_model @@ -550,7 +550,7 @@ class RemovalCandidatesNeedAReadingNoCoreAnswers(unittest.TestCase): self.assertIn("corea", found[0]["reason"]) def test_unresolved_names_skip_the_all_libretro_markers(self): - from common import unresolved_platform_cores + from resolve.cores import unresolved_platform_cores config = {"cores": ["retroarch", "all_libretro", "corea", "nope"]} self.assertEqual(unresolved_platform_cores(config, self.PROFILES), {"nope"}) diff --git a/tests/test_exporters.py b/tests/test_exporters.py index aaef93213..2749432a1 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -30,12 +30,9 @@ import zipfile from collections import OrderedDict from pathlib import Path -from common import ( - list_registered_platforms, - load_platform_config, - native_layer, - parse_untrusted_xml, -) +from model.registry import list_registered_platforms +from model.platforms import load_platform_config, native_layer +from model.safeparse import parse_untrusted_xml from exporter import discover_exporters from exporter.base_exporter import BaseExporter from export_native import ( diff --git a/tests/test_extra_identity.py b/tests/test_extra_identity.py index 830fa8f15..8087b3ac6 100644 --- a/tests/test_extra_identity.py +++ b/tests/test_extra_identity.py @@ -13,7 +13,7 @@ import tests import unittest from pathlib import Path -from common import PROFILE_IDENTITY_FIELDS +from model.profiles import PROFILE_IDENTITY_FIELDS from packextras import _collect_emulator_extras from verify import find_undeclared_files diff --git a/tests/test_extract_targets.py b/tests/test_extract_targets.py index ac128c2b0..ebf453fa4 100644 --- a/tests/test_extract_targets.py +++ b/tests/test_extract_targets.py @@ -14,7 +14,8 @@ import tests import unittest from pathlib import Path -from common import load_platform_config, load_platform_registry +from model.platforms import load_platform_config +from model.registry import load_platform_registry from generate_readme import extract_notes, extract_targets REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_file_consumers.py b/tests/test_file_consumers.py index 67c883242..42b49bfd7 100644 --- a/tests/test_file_consumers.py +++ b/tests/test_file_consumers.py @@ -153,7 +153,7 @@ class ReadersFollowTheDataTrees(unittest.TestCase): def tearDown(self): import os - from common import forget_data_dir_index + from resolve.datadirs import forget_data_dir_index os.chdir(self._previous) forget_data_dir_index() @@ -206,7 +206,7 @@ class TheDestinationBasenameComesLast(unittest.TestCase): self._tree.cleanup() def test_the_resolver_keeps_the_entry_name(self): - from common import resolve_local_file + from resolve.localfile import resolve_local_file path, status = resolve_local_file( {**self.entry, "source_profile": "melonds-nightly"}, self.db, @@ -222,7 +222,7 @@ class TheDestinationBasenameComesLast(unittest.TestCase): def test_a_descriptive_name_still_reaches_the_basename(self): """name: "MDA font ROM", path: "mda.rom" is the case the basename step serves.""" - from common import resolve_local_file + from resolve.localfile import resolve_local_file path, _ = resolve_local_file( {"name": "Wii NAND image", "path": "nand.bin"}, self.db, dest_hint="nand.bin", @@ -242,10 +242,10 @@ class EveryReaderIsTheEmulatorPackFile(unittest.TestCase): import json import os - from common import ( - build_zip_contents_index, load_data_dir_registry, - load_emulator_profiles, resolve_local_file, - ) + from core.ziptools import build_zip_contents_index + from model.registry import load_data_dir_registry + from model.profiles import load_emulator_profiles + from resolve.localfile import resolve_local_file db_path = REPO_ROOT / "database.json" if not db_path.exists(): diff --git a/tests/test_foreign_tree.py b/tests/test_foreign_tree.py index c9b2e7726..73a4810c0 100644 --- a/tests/test_foreign_tree.py +++ b/tests/test_foreign_tree.py @@ -18,7 +18,7 @@ import unittest from pathlib import Path import generate_db -from common import resolve_local_file +from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parent.parent @@ -107,7 +107,7 @@ class AReleaseNamedAfterTheTree(unittest.TestCase): def test_only_whole_leading_words_name_the_tree(self): """dolphin-mmjr2 is not a release of dolphin-mmjr: mmjr2 is one word.""" - from common import _owner_tokens + from resolve.ownership import _owner_tokens self.assertNotIn("dolphinmmjr", _owner_tokens({"source_profile": "dolphin-mmjr2"})) self.assertIn("cxbxreloaded", _owner_tokens({"source_profile": "cxbx-reloaded-2023"})) @@ -121,7 +121,7 @@ class AnotherMachinesRomIsNotServed(unittest.TestCase): def test_np2pi_does_not_receive_the_apple_ii_rom(self): import yaml - from common import load_database + from model.database import load_database if not (REPO_ROOT / "database.json").is_file(): self.skipTest("database.json is absent") diff --git a/tests/test_foreign_tree_names.py b/tests/test_foreign_tree_names.py index a8a5b9b0a..48b50ff6d 100644 --- a/tests/test_foreign_tree_names.py +++ b/tests/test_foreign_tree_names.py @@ -18,7 +18,7 @@ import tempfile import unittest from pathlib import Path -from common import resolve_local_file +from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parents[1] @@ -160,7 +160,7 @@ class RetailDashboardTree(unittest.TestCase): def test_partition_c_resolves_by_path_for_both_importers(self): import yaml - from common import load_database + from model.database import load_database db_path = REPO_ROOT / "database.json" if not db_path.exists(): diff --git a/tests/test_frontend_digest.py b/tests/test_frontend_digest.py index 27b367247..024de7007 100644 --- a/tests/test_frontend_digest.py +++ b/tests/test_frontend_digest.py @@ -19,7 +19,7 @@ from pathlib import Path import yaml -from common import load_platform_config +from model.platforms import load_platform_config from generate_pack import generate_manifest, generate_pack from verify import verify_platform diff --git a/tests/test_game_data_homonyms.py b/tests/test_game_data_homonyms.py index 8542ef41a..c5bb64d57 100644 --- a/tests/test_game_data_homonyms.py +++ b/tests/test_game_data_homonyms.py @@ -20,14 +20,11 @@ import re import unittest from pathlib import Path -from common import ( - build_zip_contents_index, - load_data_dir_registry, - load_database, - load_emulator_profiles, - resolution_is_hash_exact, - resolve_local_file, -) +from core.ziptools import build_zip_contents_index +from model.registry import load_data_dir_registry +from model.database import load_database +from model.profiles import load_emulator_profiles +from resolve.localfile import resolution_is_hash_exact, resolve_local_file REPO_ROOT = Path(__file__).resolve().parents[1] @@ -201,7 +198,7 @@ class APlatformEntryTakesNoOtherEmulatorsTree(unittest.TestCase): def test_the_emuelec_entry_is_not_served_xrick(self): os.chdir(self._cwd) - from common import load_platform_config + from model.platforms import load_platform_config config = load_platform_config("emuelec", str(REPO_ROOT / "platforms")) entry = config["systems"]["vvvvvv"]["files"][0] @@ -330,7 +327,7 @@ class ForeignCopyYieldsToADataDirectory(unittest.TestCase): def test_the_data_directory_answers_before_another_emulators_copy(self): import tempfile - from common import resolve_local_file + from resolve.localfile import resolve_local_file with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() @@ -371,7 +368,7 @@ class NameStepPrefersTheOwnersCopy(unittest.TestCase): def test_the_copy_stored_with_the_profile_wins(self): import tempfile - from common import resolve_local_file + from resolve.localfile import resolve_local_file with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() diff --git a/tests/test_game_headers.py b/tests/test_game_headers.py index 69f1cc0ed..7d62b3640 100644 --- a/tests/test_game_headers.py +++ b/tests/test_game_headers.py @@ -11,7 +11,7 @@ from pathlib import Path import yaml -from common import load_emulator_profiles +from model.profiles import load_emulator_profiles from region import REGIONS ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_game_regions.py b/tests/test_game_regions.py index 37727c6cd..91cd6f449 100644 --- a/tests/test_game_regions.py +++ b/tests/test_game_regions.py @@ -16,7 +16,7 @@ import unittest from pathlib import Path import game_rules -from common import load_emulator_profiles +from model.profiles import load_emulator_profiles REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_games_index.py b/tests/test_games_index.py index 5cb8bfc51..80a852d23 100644 --- a/tests/test_games_index.py +++ b/tests/test_games_index.py @@ -236,7 +236,7 @@ class CommittedData(unittest.TestCase): setups = load_setups(ROOT / "platforms" / "romfolders") if not setups: self.skipTest("no setup scraped") - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from romfolders import ProfileResolver resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) @@ -257,7 +257,7 @@ class CommittedData(unittest.TestCase): unrecognised GBA game got none of the nintendo-gba files. A CD folder run by mednafen_pce_fast, which lists nec-pc-engine, got no System Card.""" - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from romfolders import ProfileResolver, folder_names setups = load_setups(ROOT / "platforms" / "romfolders") @@ -301,7 +301,7 @@ class CommittedData(unittest.TestCase): self.assertIn("gba_bios.bin", dests) def test_a_folder_of_a_several_machine_core_holds_its_machines(self) -> None: - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) profiles = gi.Profiles(load_emulator_profiles(str(ROOT / "emulators")), resolver) @@ -344,7 +344,7 @@ KNOWN_UNRESOLVED = { class EveryCoreResolvesOrIsExplained(unittest.TestCase): def setUp(self) -> None: - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from romfolders import ProfileResolver self.resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) diff --git a/tests/test_hidden_extras.py b/tests/test_hidden_extras.py index be5b01678..aa9c8c7c0 100644 --- a/tests/test_hidden_extras.py +++ b/tests/test_hidden_extras.py @@ -86,9 +86,10 @@ class TheReportSaysSo(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) try: - from common import load_database, load_emulator_profiles + from model.database import load_database + from model.profiles import load_emulator_profiles from verify import verify_platform - from common import load_platform_config + from model.platforms import load_platform_config db = load_database("database.json") profiles = load_emulator_profiles("emulators") @@ -152,7 +153,9 @@ class TheGapReportIsComputedOnce(unittest.TestCase): os.chdir(REPO_ROOT) try: import verify - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config db = load_database("database.json") profiles = load_emulator_profiles("emulators") diff --git a/tests/test_install.py b/tests/test_install.py index 9a5846aa1..f6279cd2a 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -1828,7 +1828,7 @@ class TargetFlagIsAppliedOrRefused(unittest.TestCase): self.assertEqual(targets[alias], targets["nintendo-switch"]) def test_every_alias_resolves_to_its_canonical_core_list(self): - from common import load_target_config + from model.targets import load_target_config for name in ("install/targets/retroarch.json",): path = REPO_ROOT / name @@ -1861,7 +1861,7 @@ class TargetFlagIsAppliedOrRefused(unittest.TestCase): "unknown target" on one side only, and a published null left behind once the builder filters a target makes the installer serve every core. """ - from common import list_available_targets, load_target_config + from model.targets import list_available_targets, load_target_config platforms = str(REPO_ROOT / "platforms") sources = sorted( @@ -2486,7 +2486,7 @@ class TestAvailablePlatforms(unittest.TestCase): def test_every_registered_platform_is_installable(self): """The installer serves every registered platform from its manifest.""" - from common import list_registered_platforms + from model.registry import list_registered_platforms registered = set( list_registered_platforms( @@ -3407,7 +3407,7 @@ class CaseVariants(unittest.TestCase): folded = {e["dest"] for e in manifest["files"]} # A case-keeping RetroArch install is the Lakka list, less what # Lakka's own core packages install (installed_on: lakka). - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles installed = { entry.get("path") or entry.get("name") diff --git a/tests/test_install_cores.py b/tests/test_install_cores.py index 5766cfa52..ed817300f 100644 --- a/tests/test_install_cores.py +++ b/tests/test_install_cores.py @@ -266,7 +266,7 @@ class TheBuildersOrder(unittest.TestCase): if not db_path.exists(): self.skipTest("database.json is not built") import generate_pack as gp - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles db = json.loads(db_path.read_text(encoding="utf-8")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) diff --git a/tests/test_install_expert.py b/tests/test_install_expert.py index cfe82452f..d7dceb756 100644 --- a/tests/test_install_expert.py +++ b/tests/test_install_expert.py @@ -49,8 +49,10 @@ class RealListParity(unittest.TestCase): # The builder's floor: install.py alone keeps 3.8. raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer") import generate_pack as gp - from common import (build_zip_contents_index, list_registered_platforms, - load_emulator_profiles, load_platform_config) + from core.ziptools import build_zip_contents_index + from model.registry import list_registered_platforms + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config cls.gp = gp cls.config = staticmethod( @@ -134,7 +136,7 @@ class RealListParity(unittest.TestCase): self.assertGreater(dropped, 0) def test_one_per_slot_on_a_board(self): - from common import load_target_config + from model.targets import load_target_config for plat, target in TARGETS: with self.subTest(platform=plat, target=target): @@ -150,7 +152,7 @@ class RealListParity(unittest.TestCase): """--installed-cores ranks a slot by the cores found, as a pack built for exactly those cores (generate_pack target_cores) ranks it: the run passes the found cores as its reach (slot_reach).""" - from common import load_target_config + from model.targets import load_target_config for plat, target in (("retroarch", "switch"), ("retroarch", "playstation-psp")): with self.subTest(platform=plat, cores=target): diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index d16eb1527..1477a4a48 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -813,7 +813,7 @@ class InstallMatchesThePack(unittest.TestCase): if not db_path.exists(): raise unittest.SkipTest("database.json is not built") import generate_pack as gp - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles cls.gp = gp cls.db = json.loads(db_path.read_text(encoding="utf-8")) @@ -866,7 +866,8 @@ class InstallMatchesASystemPack(unittest.TestCase): if not db_path.exists(): raise unittest.SkipTest("database.json is not built") import generate_pack as gp - from common import load_emulator_profiles, load_platform_config + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config cls.gp = gp cls.db = json.loads(db_path.read_text(encoding="utf-8")) @@ -921,7 +922,7 @@ class DataTreesFollowTheSystemsTheyServe(InstallMatchesASystemPack): def _packed(self, systems, regions) -> set[str]: import zipfile - from common import load_data_dir_registry + from model.registry import load_data_dir_registry # The trees come from the registry the manifest reads by itself. with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out: @@ -997,7 +998,8 @@ class InstallMatchesATargetManifest(unittest.TestCase): if not db_path.exists(): raise unittest.SkipTest("database.json is not built") import generate_pack as gp - from common import load_emulator_profiles, load_target_config + from model.profiles import load_emulator_profiles + from model.targets import load_target_config cls.gp = gp cls.load_target_config = staticmethod(load_target_config) @@ -1023,7 +1025,7 @@ class InstallMatchesATargetManifest(unittest.TestCase): files, omitted = install.narrow_to_cores(full, cores, target=target) # A case-insensitive platform reads one file under both # spellings (BlastEm's 32X_M_BIOS.bin, PicoDrive's .BIN). - from common import load_platform_config + from model.platforms import load_platform_config config = load_platform_config(platform, str(REPO_ROOT / "platforms")) fold = str.lower if config.get("case_insensitive_fs") else str @@ -1049,7 +1051,9 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): pack drops.""" def setUp(self): - import common + from model import profiles + from model.platforms import _platform_config_cache + from model.profiles import _emulator_profiles_cache import generate_db import generate_pack @@ -1094,11 +1098,11 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): {"name": "us.bin", "system": "sys", "region": ["north-america"], "required": True}, ]})) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.addCleanup(common._platform_config_cache.clear) - self.addCleanup(common._emulator_profiles_cache.clear) - self.profiles = common.load_emulator_profiles("emulators") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.addCleanup(_platform_config_cache.clear) + self.addCleanup(_emulator_profiles_cache.clear) + self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): return self.gp.generate_manifest( @@ -1131,7 +1135,9 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): the pack kept the European BIOS the installer drops.""" def setUp(self): - import common + from model import profiles + from model.platforms import _platform_config_cache + from model.profiles import _emulator_profiles_cache import generate_db import generate_pack @@ -1178,11 +1184,11 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): {"name": name, "system": "sys", "required": False} for name in ("eu.bin", "jp.bin") ]})) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.addCleanup(common._platform_config_cache.clear) - self.addCleanup(common._emulator_profiles_cache.clear) - self.profiles = common.load_emulator_profiles("emulators") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.addCleanup(_platform_config_cache.clear) + self.addCleanup(_emulator_profiles_cache.clear) + self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): return self.gp.generate_manifest( @@ -1215,7 +1221,9 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): which records the path once, dropped it.""" def setUp(self): - import common + from model import profiles + from model.platforms import _platform_config_cache + from model.profiles import _emulator_profiles_cache import generate_db import generate_pack @@ -1268,11 +1276,11 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): "emulator": "other", "type": "libretro", "systems": ["sys"], "files": [ {"name": "us.bin", "path": "alt/us.bin", "system": "sys", "required": False}, ]})) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.addCleanup(common._platform_config_cache.clear) - self.addCleanup(common._emulator_profiles_cache.clear) - self.profiles = common.load_emulator_profiles("emulators") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.addCleanup(_platform_config_cache.clear) + self.addCleanup(_emulator_profiles_cache.clear) + self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): return self.gp.generate_manifest( @@ -1355,8 +1363,8 @@ class ThePlatformsOwnSystemNamesAreAccepted(unittest.TestCase): file records psx as the native_system of sony-playstation.""" def test_the_names_come_from_the_platform_file(self): - from common import load_platform_config - from common import platform_system_names + from model.platforms import load_platform_config + from model.systems import platform_system_names config = load_platform_config("batocera", str(REPO_ROOT / "platforms")) names = platform_system_names(config, list(config["systems"])) @@ -1425,7 +1433,7 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): import generate_pack as gp import pipeline import verify - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles cls.gp, cls.pipeline, cls.verify = gp, pipeline, verify cls.db = json.loads(db_path.read_text(encoding="utf-8")) @@ -1449,7 +1457,8 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): return {i.filename: i.file_size for i in infos} def test_pack_verify_and_installer_agree(self): - from common import load_platform_config, resolve_system_arg + from model.platforms import load_platform_config + from model.systems import resolve_system_arg for platform, native, system_id in self.CASES: with self.subTest(platform=platform, name=native): @@ -1514,7 +1523,7 @@ class SystemNamesResolveOneWay(unittest.TestCase): }} def _resolve(self, value, config=CONFIG): - from common import resolve_system_arg + from model.systems import resolve_system_arg return resolve_system_arg(value, list(self.CONFIG["systems"]), config) diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 5908a6f3a..2d5db7320 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -16165,7 +16165,7 @@ class EmulatorChoiceMatchesTheEmulatorPack(unittest.TestCase): # The builder's floor: install.py alone keeps 3.8. raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer") import generate_pack as gp - from common import build_zip_contents_index + from core.ziptools import build_zip_contents_index cls.gp = gp cls.db = json.loads(db_path.read_text(encoding="utf-8")) diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index ab1943e7c..3c0275425 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -22,7 +22,8 @@ import urllib.error from pathlib import Path from unittest import mock -import common +from model.composition import GAME_DATA_TOPS, composition_tier +from model.profiles import load_emulator_profiles from model import largefiles import check_release_assets @@ -110,7 +111,7 @@ class LargeFileCacheTest(unittest.TestCase): results: list[str | None] = [None, None] def worker(slot: int): - results[slot] = common.fetch_large_file("asset.bin", dest_dir=self.dir) + results[slot] = largefiles.fetch_large_file("asset.bin", dest_dir=self.dir) threads = [threading.Thread(target=worker, args=(i,)) for i in range(2)] for t in threads: @@ -129,7 +130,7 @@ class LargeFileCacheTest(unittest.TestCase): largefiles.urllib.request.urlopen = lambda req, timeout=None: _SlowResponse( PAYLOAD_A ) - common.fetch_large_file("asset.bin", dest_dir=self.dir) + largefiles.fetch_large_file("asset.bin", dest_dir=self.dir) leftovers = [f for f in os.listdir(self.dir) if f.endswith(".tmp")] self.assertEqual(leftovers, []) @@ -138,7 +139,7 @@ class LargeFileCacheTest(unittest.TestCase): raise urllib.error.URLError("offline") largefiles.urllib.request.urlopen = fail - self.assertIsNone(common.fetch_large_file("asset.bin", dest_dir=self.dir)) + self.assertIsNone(largefiles.fetch_large_file("asset.bin", dest_dir=self.dir)) self.assertEqual(os.listdir(self.dir), []) def test_a_spaced_name_served_dotted_reports_nothing(self): @@ -154,7 +155,7 @@ class LargeFileCacheTest(unittest.TestCase): largefiles.urllib.request.urlopen = urlopen with mock.patch("sys.stderr", new_callable=io.StringIO) as err: - result = common.fetch_large_file("spaced asset.bin", dest_dir=self.dir) + result = largefiles.fetch_large_file("spaced asset.bin", dest_dir=self.dir) self.assertIsNotNone(result) self.assertEqual(len(asked), 2) self.assertEqual(err.getvalue(), "") @@ -165,7 +166,7 @@ class LargeFileCacheTest(unittest.TestCase): largefiles.urllib.request.urlopen = fail with mock.patch("sys.stderr", new_callable=io.StringIO) as err: - self.assertIsNone(common.fetch_large_file("spaced asset.bin", dest_dir=self.dir)) + self.assertIsNone(largefiles.fetch_large_file("spaced asset.bin", dest_dir=self.dir)) self.assertIn("spaced asset.bin", err.getvalue()) self.assertIn("spaced.asset.bin", err.getvalue()) @@ -173,7 +174,7 @@ class LargeFileCacheTest(unittest.TestCase): largefiles.urllib.request.urlopen = lambda req, timeout=None: _SlowResponse( PAYLOAD_A ) - result = common.fetch_large_file( + result = largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, expected_sha1="00" * 20 ) self.assertIsNone(result) @@ -188,7 +189,7 @@ class LargeFileCacheTest(unittest.TestCase): largefiles.urllib.request.urlopen = fail self.assertTrue(os.path.samefile( - common.fetch_large_file("asset.bin", dest_dir=self.dir), cached + largefiles.fetch_large_file("asset.bin", dest_dir=self.dir), cached )) def test_offline_cache_miss_never_opens_the_network(self): @@ -197,7 +198,7 @@ class LargeFileCacheTest(unittest.TestCase): largefiles.urllib.request.urlopen = fail self.assertIsNone( - common.fetch_large_file( + largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, offline=True ) ) @@ -212,7 +213,7 @@ class LargeFileCacheTest(unittest.TestCase): largefiles.urllib.request.urlopen = fail self.assertTrue(os.path.samefile( - common.fetch_large_file( + largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, expected_sha1=hashlib.sha1(PAYLOAD_A).hexdigest(), @@ -247,7 +248,7 @@ class LargeFileCacheTest(unittest.TestCase): rebuilt = b"C" * 1000 gets: list = [] self._serve(rebuilt, gets) - result = common.fetch_large_file( + result = largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, expected_sha1=hashlib.sha1(rebuilt).hexdigest(), ) @@ -261,11 +262,11 @@ class LargeFileCacheTest(unittest.TestCase): the prune of that same download removed it.""" self._serve(PAYLOAD_A, []) sha1 = hashlib.sha1(PAYLOAD_A).hexdigest() - first = common.fetch_large_file("asset.bin", dest_dir=self.dir, expected_sha1=sha1) + first = largefiles.fetch_large_file("asset.bin", dest_dir=self.dir, expected_sha1=sha1) self.assertTrue(first and os.path.isfile(first)) os.unlink(Path(self.dir) / "asset.bin") with mock.patch.object(largefiles, "ORPHAN_GRACE", -1): - second = common.fetch_large_file( + second = largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, expected_sha1=sha1 ) self.assertTrue(second and os.path.isfile(second)) @@ -276,11 +277,11 @@ class LargeFileCacheTest(unittest.TestCase): handed out the old link, which a prune elsewhere would remove.""" self._serve(PAYLOAD_A, []) sha1 = hashlib.sha1(PAYLOAD_A).hexdigest() - common.fetch_large_file("asset.bin", dest_dir=self.dir, expected_sha1=sha1) + largefiles.fetch_large_file("asset.bin", dest_dir=self.dir, expected_sha1=sha1) cached = Path(self.dir) / "asset.bin" os.unlink(cached) cached.write_bytes(PAYLOAD_A) - hit = common.fetch_large_file( + hit = largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, expected_sha1=sha1, offline=True ) self.assertTrue(os.path.samefile(hit, cached)) @@ -290,7 +291,7 @@ class LargeFileCacheTest(unittest.TestCase): cached.write_bytes(PAYLOAD_A) gets: list = [] self._serve(PAYLOAD_A, gets) - result = common.fetch_large_file( + result = largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, expected_sha1="00" * 20 ) self.assertIsNone(result) @@ -302,7 +303,7 @@ class LargeFileCacheTest(unittest.TestCase): cached.write_bytes(PAYLOAD_A) gets: list = [] self._serve(b"D" * 10, gets) - result = common.fetch_large_file( + result = largefiles.fetch_large_file( "asset.bin", dest_dir=self.dir, expected_sha1="00" * 20 ) self.assertIsNone(result) @@ -410,12 +411,12 @@ class PreservedLargeFileEntries(unittest.TestCase): self._cwd = os.getcwd() os.chdir(self.tmp) (self.tmp / ".gitignore").write_text("bios/Sony/PS3/FW.PUP\n") - self._real_fetch = common.fetch_large_file + self._real_fetch = largefiles.fetch_large_file generate_db.__dict__.pop("fetch_large_file", None) def tearDown(self): os.chdir(self._cwd) - common.fetch_large_file = self._real_fetch + largefiles.fetch_large_file = self._real_fetch self._tmp.cleanup() def _write_db(self, entries: dict) -> str: @@ -424,7 +425,7 @@ class PreservedLargeFileEntries(unittest.TestCase): return path def test_stale_entry_for_a_rescanned_path_is_dropped(self): - common.fetch_large_file = lambda *_a, **_k: None + largefiles.fetch_large_file = lambda *_a, **_k: None db_path = self._write_db( { "a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}, @@ -438,7 +439,7 @@ class PreservedLargeFileEntries(unittest.TestCase): self.assertEqual(list(files), ["a" * 40]) def test_absent_large_file_is_still_preserved(self): - common.fetch_large_file = lambda *_a, **_k: None + largefiles.fetch_large_file = lambda *_a, **_k: None db_path = self._write_db( {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) @@ -451,7 +452,7 @@ class PreservedLargeFileEntries(unittest.TestCase): cache = self.tmp / "cache" / "FW.PUP" cache.parent.mkdir() cache.write_bytes(b"firmware") - common.fetch_large_file = lambda *_a, **_k: str(cache) + largefiles.fetch_large_file = lambda *_a, **_k: str(cache) db_path = self._write_db( {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) @@ -465,7 +466,7 @@ class PreservedLargeFileEntries(unittest.TestCase): cache = self.tmp / "cache" / "FW.PUP" cache.parent.mkdir() cache.write_bytes(b"firmware") - common.fetch_large_file = lambda *_a, **_k: str(cache) + largefiles.fetch_large_file = lambda *_a, **_k: str(cache) db_path = self._write_db( {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) @@ -481,7 +482,7 @@ class PreservedLargeFileEntries(unittest.TestCase): self.assertEqual(list(directory.iterdir()), []) def test_a_file_sharing_only_the_name_is_not_preserved(self): - common.fetch_large_file = lambda *_a, **_k: "/cache/large/FW.PUP" + largefiles.fetch_large_file = lambda *_a, **_k: "/cache/large/FW.PUP" db_path = self._write_db( {"c" * 40: {"name": "FW.PUP", "path": "bios/Sony/PSP/FW.PUP"}} ) @@ -492,7 +493,7 @@ class PreservedLargeFileEntries(unittest.TestCase): self.assertEqual(files, {}) def test_a_second_revision_under_a_rescanned_path_is_dropped(self): - common.fetch_large_file = lambda *_a, **_k: "/cache/large/FW.PUP" + largefiles.fetch_large_file = lambda *_a, **_k: "/cache/large/FW.PUP" db_path = self._write_db( {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) @@ -737,7 +738,7 @@ class GameDataHasOneDefinition(unittest.TestCase): "bios/Toys for Bob/The Ur-Quan Masters/uqm-0.8.0-voice.uqm", ): with self.subTest(path=path): - self.assertEqual(common.composition_tier(path), "game_data") + self.assertEqual(composition_tier(path), "game_data") self.assertEqual( check_release_assets._section_for(path), "Game engine data" ) @@ -747,7 +748,7 @@ class GameDataHasOneDefinition(unittest.TestCase): if not db_path.exists(): self.skipTest("database.json not generated") db = json.loads(db_path.read_text(encoding="utf-8")) - profiles = common.load_emulator_profiles(str(REPO_ROOT / "emulators")) + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) names: dict[str, set[str]] = {} for profile in profiles.values(): for entry in profile.get("files") or []: @@ -766,7 +767,7 @@ class GameDataHasOneDefinition(unittest.TestCase): top for top, categories in trees.items() if categories == {"game_data"} ) self.assertEqual( - [top for top in only_game_data if top not in common.GAME_DATA_TOPS], [] + [top for top in only_game_data if top not in GAME_DATA_TOPS], [] ) diff --git a/tests/test_launcher_evidence.py b/tests/test_launcher_evidence.py index 33a726c44..01f4a9bb3 100644 --- a/tests/test_launcher_evidence.py +++ b/tests/test_launcher_evidence.py @@ -14,7 +14,7 @@ from pathlib import Path import yaml -from common import load_platform_config +from model.platforms import load_platform_config from resolve.launchers import ( bound_launchers, config_evidence, diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index 0f61b0f38..9eaf71dd0 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -28,7 +28,8 @@ from unittest import mock import yaml import verify -from common import _emulator_profiles_cache, load_emulator_profiles, load_platform_config +from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.platforms import load_platform_config from cross_reference import ( LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, diff --git a/tests/test_launcher_layer.py b/tests/test_launcher_layer.py index 60e7a78b8..5d2da4ac8 100644 --- a/tests/test_launcher_layer.py +++ b/tests/test_launcher_layer.py @@ -20,7 +20,8 @@ import zipfile import yaml -from common import _emulator_profiles_cache, load_emulator_profiles, load_platform_config +from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.platforms import load_platform_config from resolve.launchers import LauncherLayer, launcher_places, suffixed_stem from verify import find_undeclared_files, verify_platform diff --git a/tests/test_launcher_paths.py b/tests/test_launcher_paths.py index 806efe876..b83132fd3 100644 --- a/tests/test_launcher_paths.py +++ b/tests/test_launcher_paths.py @@ -324,8 +324,10 @@ class AUserFolderInTheConfigsFolder(unittest.TestCase): of the configs root its batoceraPaths builds (../system/configs).""" def test_the_sys_modules_go_below_the_configs_root(self): - from common import load_emulator_profiles, load_platform_config, platform_layouts - from common import standalone_set + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from resolve.standalone import platform_layouts + from resolve.standalone import standalone_set profile = load_emulator_profiles(str(REPO_ROOT / "emulators"))["shadps4"] # KNULLI's generator does the same, but no KNULLI board builds shadps4. diff --git a/tests/test_launcher_placement.py b/tests/test_launcher_placement.py index 0f3b18321..6da19ac88 100644 --- a/tests/test_launcher_placement.py +++ b/tests/test_launcher_placement.py @@ -23,13 +23,9 @@ from pathlib import Path import yaml -from common import ( - _emulator_profiles_cache, - load_emulator_profiles, - load_platform_config, - platform_layouts, - standalone_set, -) +from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.platforms import load_platform_config +from resolve.standalone import platform_layouts, standalone_set from generate_pack import generate_manifest, generate_pack from verify import verify_platform @@ -241,7 +237,7 @@ class FsUaeOnRetroPie(unittest.TestCase): def test_the_launcher_name_is_filled_without_another_core(self) -> None: import json - from common import load_target_config + from model.targets import load_target_config db_path = REPO_ROOT / "database.json" if not db_path.exists(): @@ -528,7 +524,8 @@ class EachProgramItsOwnProfile(unittest.TestCase): """PICO-8 and Voxatron are two programs: a platform running one gets its files only.""" def test_only_the_platforms_that_run_voxatron_get_it(self) -> None: - from common import list_registered_platforms, resolve_platform_cores + from model.registry import list_registered_platforms + from resolve.cores import resolve_platform_cores profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) runs = { @@ -544,7 +541,7 @@ class EachProgramItsOwnProfile(unittest.TestCase): "batocera", "knulli", "rocknix", "retrodeck", "retrobat", "recalbox"))) def test_a_standalone_emulator_is_run(self) -> None: - from common import resolve_platform_cores + from resolve.cores import resolve_platform_cores profiles = {"emu": {"emulator": "Emu", "type": "standalone", "cores": ["emu"], "systems": ["sys"], "files": []}} @@ -895,7 +892,8 @@ class MameSearchPaths(unittest.TestCase): self.assertEqual(bbc["standalone_path"], "mame/samples/bbc.zip") def test_a_moved_tree_is_found_by_its_layout_path(self) -> None: - from common import expand_directory_entries, load_database + from resolve.directories import expand_directory_entries + from model.database import load_database db = load_database(str(REPO_ROOT / "database.json")) view = standalone_view("mame", "retrodeck") @@ -996,7 +994,7 @@ class AdvanceMameOnEmuELEC(unittest.TestCase): def test_both_copies_are_one_file(self) -> None: # Outside the BIOS tree the folder is no proof of content: each copy # resolves by its layout path, so both folders hold the same file. - from common import load_database + from model.database import load_database db = load_database(str(REPO_ROOT / "database.json")) with redirect_stdout(io.StringIO()): @@ -1022,7 +1020,8 @@ class AdvanceMameOnEmuELEC(unittest.TestCase): def test_the_roms_folder_is_no_proof_of_content(self) -> None: # bios/Arcade/MAME/konamigv.zip is MAME 0.289's set, not AdvanceMAME's. - 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(REPO_ROOT / "database.json")) view = standalone_view("advancemame", "emuelec") @@ -1094,7 +1093,7 @@ class SetsReadBesideTheGame(unittest.TestCase): self.assertTrue(all("load_from" not in e and "root" not in e for e in sets)) def test_the_manifest_drops_the_root_copy_no_core_reads(self) -> None: - from common import load_database + from model.database import load_database db = load_database(str(REPO_ROOT / "database.json")) with redirect_stdout(io.StringIO()): @@ -1125,7 +1124,7 @@ class MameOnRetroDeckRomPaths(unittest.TestCase): self.assertTrue(found["neogeo"]["any_machine"]) def test_a_machine_reads_its_own_set_and_its_devices(self) -> None: - from common import rom_search_sets + from resolve.contentlayout import rom_search_sets self.assertIn("adam", rom_search_sets("mame", "adam", ["adam"], False)) neogeo = rom_search_sets("mame", "neogeo", [], True) @@ -1212,7 +1211,7 @@ class CloneReadsItsParent(unittest.TestCase): finds o2bios.rom in the parent's videopac.zip (src/emu/driver.cpp:31-38).""" def test_the_parent_set_goes_to_the_clone_folder(self) -> None: - from common import rom_search_sets + from resolve.contentlayout import rom_search_sets self.assertIn("videopac", rom_search_sets("mame", "odyssey2", ["odyssey2"], False)) for platform, dest in (("emudeck", "odyssey2/videopac.zip"), @@ -1264,7 +1263,7 @@ class CoreOfferedOnSomeBoards(unittest.TestCase): return {**base, "_rom_folders": [self.ROW], **extra} def test_a_branch_names_the_boards(self) -> None: - from common import when_admits + from resolve.contentlayout import when_admits self.assertTrue(when_admits("DEVICE H700|RK3326", "rk3326")) self.assertFalse(when_admits("DEVICE H700|RK3326", "s922x")) @@ -1272,7 +1271,7 @@ class CoreOfferedOnSomeBoards(unittest.TestCase): self.assertTrue(when_admits('if [ "${PREFER_GLES}" = "yes" ]; then', "h700")) def test_an_offer_carries_the_boards_its_branch_names(self) -> None: - from common import offer_boards + from resolve.contentlayout import offer_boards boards = offer_boards(self.config()) self.assertEqual(boards[("uae4arm", "amiga")], frozenset({"h700", "rk3326"})) @@ -1280,7 +1279,8 @@ class CoreOfferedOnSomeBoards(unittest.TestCase): self.assertIsNone(boards[("puae2021", "amiga")]) def test_a_board_pack_places_the_core_where_the_board_offers_it(self) -> None: - from common import CONTENT_FOLDER_PREFIX, TARGET_KEY, content_folder_tags + from resolve.layout import CONTENT_FOLDER_PREFIX + from resolve.contentlayout import TARGET_KEY, content_folder_tags def placed(config: dict) -> dict: rows = [json.loads(t[len(CONTENT_FOLDER_PREFIX):]) for t in content_folder_tags(config) @@ -1296,7 +1296,7 @@ class CoreOfferedOnSomeBoards(unittest.TestCase): def platform_manifest(platform: str) -> dict: - from common import load_database + from model.database import load_database db = load_database(str(REPO_ROOT / "database.json")) with redirect_stdout(io.StringIO()): diff --git a/tests/test_libretro_layout.py b/tests/test_libretro_layout.py index 8f68abac1..787111e08 100644 --- a/tests/test_libretro_layout.py +++ b/tests/test_libretro_layout.py @@ -60,7 +60,9 @@ class RetroArchCarriesDolphinWhereItReads(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from packextras import _collect_emulator_extras config = load_platform_config("retroarch") diff --git a/tests/test_libretro_slugs.py b/tests/test_libretro_slugs.py index 97cc16b15..1c66d67ef 100644 --- a/tests/test_libretro_slugs.py +++ b/tests/test_libretro_slugs.py @@ -34,7 +34,7 @@ class ScrapedSystemIdsAreSlugs(unittest.TestCase): The quasi88 group supplies N88EXT0-3.ROM, which the core reads first (src/LIBRETRO/libretro.c:109-112) and which match that main ROM. """ - from common import load_platform_config + from model.platforms import load_platform_config config = load_platform_config("retroarch", str(REPO_ROOT / "platforms")) names = { diff --git a/tests/test_maker_folder_names.py b/tests/test_maker_folder_names.py index 856993a79..7d15f6fb7 100644 --- a/tests/test_maker_folder_names.py +++ b/tests/test_maker_folder_names.py @@ -25,7 +25,14 @@ from pathlib import Path import yaml -import common +from model import cliargs, platforms +from resolve import cores, grouping, localfile +from model.database import load_database +from model.platforms import _platform_config_cache +from model.profiles import _emulator_profiles_cache, load_emulator_profiles +from model.registry import list_registered_platforms, load_data_dir_registry +from resolve.localfile import resolve_local_file +from resolve.ownership import BUCKET_FOLDERS, names_manufacturer import generate_db import generate_pack as builder import generate_site @@ -95,15 +102,15 @@ class _Collection(unittest.TestCase): "--bios-dir", "bios", "--output", "database.json"], check=True, capture_output=True, ) - self.db = common.load_database("database.json") - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.config = common.load_platform_config("handheld", "platforms") - self.profiles = common.load_emulator_profiles("emulators") + self.db = load_database("database.json") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.config = platforms.load_platform_config("handheld", "platforms") + self.profiles = load_emulator_profiles("emulators") def tearDown(self): - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() os.chdir(self._cwd) self._tmp.cleanup() @@ -138,33 +145,33 @@ class DiskRomGoesToThePc88File(_Collection): def test_resolution(self): entry = self._entry("nec-pc-88") - path, status = common.resolve_local_file( + path, status = resolve_local_file( entry, self.db, dest_hint=entry["destination"] ) self.assertEqual((path, status), ("bios/NEC/PC-88/n88sub.rom", "name_exact")) def test_the_msx_system_keeps_the_msx_file(self): entry = self._entry("microsoft-msx") - path, _status = common.resolve_local_file( + path, _status = resolve_local_file( entry, self.db, dest_hint=entry["destination"] ) self.assertEqual(path, "bios/Microsoft/MSX/DISK.ROM") def test_a_declared_hash_still_decides(self): entry = {**self._entry("nec-pc-88"), "md5": hashlib.md5(MSX_DISK).hexdigest()} - path, status = common.resolve_local_file(entry, self.db) + path, status = resolve_local_file(entry, self.db) self.assertEqual((path, status), ("bios/Microsoft/MSX/DISK.ROM", "md5_exact")) def test_an_emulator_entry_is_not_narrowed(self): entry = {**self._entry("nec-pc-88"), "source_profile": "msx-emu"} - path, _status = common.resolve_local_file(entry, self.db) + path, _status = resolve_local_file(entry, self.db) self.assertEqual(path, "bios/Microsoft/MSX/DISK.ROM") def test_no_pc88_copy_leaves_it_missing_not_mismatched(self): Path("bios/NEC/PC-88/n88sub.rom").unlink() entry = self._entry("nec-pc-88") self.assertEqual( - common.resolve_local_file(entry, self.db, dest_hint=entry["destination"]), + resolve_local_file(entry, self.db, dest_hint=entry["destination"]), (None, "not_found"), ) @@ -189,7 +196,9 @@ class DiskRomGoesToThePc88File(_Collection): def test_the_manifest_changes_only_that_row(self): manifest = self._manifest() - original = (common.load_platform_config, common.system_makers) + original = (platforms.load_platform_config, localfile.system_makers) + # Every module that reads the loader by its own name sees the stub. + readers = (builder, platforms, cliargs, cores, grouping) def untagged(*args, **kwargs): config = original[0](*args, **kwargs) @@ -198,15 +207,17 @@ class DiskRomGoesToThePc88File(_Collection): f.pop("platform_system", None) return config - common._platform_config_cache.clear() - builder.load_platform_config = common.load_platform_config = untagged - common.system_makers = lambda *args: frozenset() + _platform_config_cache.clear() + for module in readers: + module.load_platform_config = untagged + localfile.system_makers = lambda *args: frozenset() try: before = self._manifest() finally: - builder.load_platform_config = common.load_platform_config = original[0] - common.system_makers = original[1] - common._platform_config_cache.clear() + for module in readers: + module.load_platform_config = original[0] + localfile.system_makers = original[1] + _platform_config_cache.clear() rows = {f["dest"]: f for f in manifest["files"]} old_rows = {f["dest"]: f for f in before["files"]} self.assertEqual(rows["bios/quasi88/DISK.ROM"]["size"], len(PC88_DISK)) @@ -225,8 +236,8 @@ class DiskRomGoesToThePc88File(_Collection): class SiteSharesTheMakerTest(unittest.TestCase): def test_one_copy(self): - self.assertIs(generate_site.names_manufacturer, common.names_manufacturer) - self.assertIs(generate_site.BUCKET_FOLDERS, common.BUCKET_FOLDERS) + self.assertIs(generate_site.names_manufacturer, names_manufacturer) + self.assertIs(generate_site.BUCKET_FOLDERS, BUCKET_FOLDERS) class NoHashlessNameMatchCrossesMakers(unittest.TestCase): @@ -238,24 +249,24 @@ class NoHashlessNameMatchCrossesMakers(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): self.skipTest("database.json not built") - db = common.load_database(str(db_path)) - registry = common.load_data_dir_registry("platforms") + db = load_database(str(db_path)) + registry = load_data_dir_registry("platforms") folders = { parts[1] for entry in db["files"].values() if len(parts := entry["path"].split("/")) >= 3 and parts[0] == "bios" - } - common.BUCKET_FOLDERS + } - BUCKET_FOLDERS crossings = [] - for platform in common.list_registered_platforms("platforms"): - config = common.load_platform_config(platform, "platforms") + for platform in list_registered_platforms("platforms"): + config = platforms.load_platform_config(platform, "platforms") for sys_id, system in config.get("systems", {}).items(): - makers = {f for f in folders if common.names_manufacturer(sys_id, f)} + makers = {f for f in folders if names_manufacturer(sys_id, f)} if not makers: continue for entry in system.get("files") or []: if any(entry.get(k) for k in ("sha1", "md5", "sha256", "crc32")): continue - path, status = common.resolve_local_file( + path, status = resolve_local_file( entry, db, dest_hint=entry.get("destination", ""), data_dir_registry=registry, ) @@ -264,7 +275,7 @@ class NoHashlessNameMatchCrossesMakers(unittest.TestCase): status.startswith("name") and len(parts) >= 3 and parts[0] == "bios" - and parts[1] not in common.BUCKET_FOLDERS + and parts[1] not in BUCKET_FOLDERS and parts[1] not in makers ): crossings.append(f"{platform} {sys_id} {entry.get('name')}: {path}") diff --git a/tests/test_mame_devices.py b/tests/test_mame_devices.py index defb2405f..a5959a403 100644 --- a/tests/test_mame_devices.py +++ b/tests/test_mame_devices.py @@ -17,7 +17,7 @@ import tempfile import unittest from pathlib import Path -from scripts.common import yaml_load +from scripts.model.safeparse import yaml_load from scripts.scraper._hash_merge import ( DEVICE_SECTION, SOFTLIST_SECTION, @@ -607,7 +607,7 @@ class APickReadsTheEntrySystems(unittest.TestCase): SYSTEMS = ["apple2gs", "coco", "snk-neogeo-mvs"] def test_entry_system_ids(self): - from scripts.common import entry_system_ids + from scripts.model.profiles import entry_system_ids profile = {"systems": self.SYSTEMS} self.assertEqual(entry_system_ids({"system": "coco"}, profile), ["coco"]) @@ -617,7 +617,7 @@ class APickReadsTheEntrySystems(unittest.TestCase): self.assertEqual(entry_system_ids({}, profile), self.SYSTEMS) def test_entry_serves_systems(self): - from scripts.common import entry_serves_systems + from scripts.model.profiles import entry_serves_systems profile = {"systems": self.SYSTEMS} entry = {"systems": ["apple2gs", "coco"]} @@ -966,7 +966,8 @@ class TheSupportMergeWritesListsAndSamples(unittest.TestCase): self.assertEqual(profile_seeds(text), {"neogeo": "acorn-bbc-micro"}) def test_a_pick_takes_its_lists_and_leaves_the_others(self): - from scripts.common import entry_serves_systems, expand_directory_entries + from scripts.model.profiles import entry_serves_systems + from scripts.resolve.directories import expand_directory_entries self._merge() profile = yaml_load(self.path.read_text(encoding="utf-8")) diff --git a/tests/test_md5_pack_context.py b/tests/test_md5_pack_context.py index b2fe0c960..9c08836b4 100644 --- a/tests/test_md5_pack_context.py +++ b/tests/test_md5_pack_context.py @@ -75,7 +75,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): import yaml - import common + from model.profiles import _emulator_profiles_cache import generate_db import generate_pack as gp @@ -99,7 +99,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): "systems": ["sega-triforce"], "files": [{"name": "segaboot.gcm", "required": True}], })) - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() try: emulator_pack = gp.generate_emulator_pack( ["triforce"], str(root / "emulators"), db, str(root / "bios"), @@ -110,7 +110,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): str(root / "bios"), str(out), offline=True, ) finally: - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self.assertNotEqual(Path(emulator_pack).name, Path(system_pack).name) self.assertTrue(Path(emulator_pack).exists()) self.assertTrue(Path(system_pack).exists()) diff --git a/tests/test_minui_platform.py b/tests/test_minui_platform.py index 206af8d01..8248ae9f0 100644 --- a/tests/test_minui_platform.py +++ b/tests/test_minui_platform.py @@ -27,7 +27,8 @@ from pathlib import Path import yaml -from common import load_emulator_profiles, load_platform_config +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config from scraper import minui_scraper REPO_ROOT = Path(__file__).resolve().parent.parent @@ -167,7 +168,7 @@ class PackPlacesCoreFilesUnderTheTag(unittest.TestCase): folder the platform hands it, and nowhere else.""" def setUp(self): - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() self.root = tempfile.mkdtemp(dir=REPO_ROOT / "tmp" / "tests") @@ -300,7 +301,7 @@ class PackPlacesCoreFilesUnderTheTag(unittest.TestCase): self.assertEqual(outside, []) def test_the_same_cores_in_other_folders_make_another_pack(self): - from common import group_identical_platforms + from resolve.grouping import group_identical_platforms twin = yaml.safe_load(Path(self.platforms, "test_minui.yml").read_text()) twin["core_system_dirs"]["Bios/GB"]["cores"] = ["arcade_lib"] @@ -335,7 +336,7 @@ class PublishedPlatformsHoldTheRule(unittest.TestCase): repository the platform's recipe names: a library renamed from another project (dosbox-pure as dosbox) would hand the wrong profile's files to the folder.""" - from common import resolve_platform_cores + from resolve.cores import resolve_platform_cores profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -421,7 +422,8 @@ class TheSitePageOfACardPlatform(unittest.TestCase): def test_folders_replace_the_empty_coverage(self): import generate_site - from common import load_database, load_platform_registry + from model.database import load_database + from model.registry import load_platform_registry from generate_readme import compute_coverage if not (REPO_ROOT / "database.json").is_file(): @@ -445,7 +447,7 @@ class TheWholeTreeKeepsCoresMinUILeavesOut(unittest.TestCase): and the global report lost 238 profiles.""" def test_a_core_minui_does_not_list_keeps_its_files(self): - from common import merged_standalone_set, platform_layouts + from resolve.standalone import merged_standalone_set, platform_layouts minui = {"core_system_dirs": {"Bios/FC": {"cores": ["fceumm"]}}} retroarch = {} diff --git a/tests/test_name_tiebreak.py b/tests/test_name_tiebreak.py index f8c7d1f32..12bfa07af 100644 --- a/tests/test_name_tiebreak.py +++ b/tests/test_name_tiebreak.py @@ -13,7 +13,7 @@ import tempfile import unittest from pathlib import Path -from common import _by_affinity +from resolve.localfile import _by_affinity REPO_ROOT = Path(__file__).resolve().parents[1] @@ -36,7 +36,7 @@ class DeclaredSizeOrders(unittest.TestCase): class OwnerOutranksSharedTree(unittest.TestCase): def test_the_owners_copy_beats_two_matching_segments(self): """armsx2's fxaa.fx lost to NetherSX2's under shaders/common/.""" - from common import _by_affinity + from resolve.localfile import _by_affinity paths = [ "bios/Other/nethersx2/assets/shaders/common/fxaa.fx", diff --git a/tests/test_native_mode.py b/tests/test_native_mode.py index e6085841c..80a423470 100644 --- a/tests/test_native_mode.py +++ b/tests/test_native_mode.py @@ -219,13 +219,13 @@ class GapAnalysisAgreesWithTheBuilder(unittest.TestCase): return tmp, root, db def _in_repo(self, mode: str) -> bool: - import common + from model.profiles import _emulator_profiles_cache, load_emulator_profiles from verify import find_undeclared_files tmp, root, db = self._fixture() try: - common._emulator_profiles_cache.clear() - profiles = common.load_emulator_profiles(str(root / "emulators")) + _emulator_profiles_cache.clear() + profiles = load_emulator_profiles(str(root / "emulators")) config = { "platform": "Demo", "verification_mode": mode, @@ -238,7 +238,7 @@ class GapAnalysisAgreesWithTheBuilder(unittest.TestCase): entry = next(e for e in found if e["name"] == "collide.rom") return bool(entry["in_repo"]) finally: - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() tmp.cleanup() def test_a_digest_mode_does_not_call_a_contradicted_copy_available(self): @@ -365,7 +365,7 @@ class SkippingIsNotSettling(unittest.TestCase): import hashlib import tempfile - import common + from model.profiles import _emulator_profiles_cache, load_emulator_profiles from verify import find_undeclared_files tmp = tempfile.TemporaryDirectory() @@ -396,8 +396,8 @@ class SkippingIsNotSettling(unittest.TestCase): "files:\n" + entry ) try: - common._emulator_profiles_cache.clear() - profiles = common.load_emulator_profiles(str(root / "emulators")) + _emulator_profiles_cache.clear() + profiles = load_emulator_profiles(str(root / "emulators")) config = { "platform": "Demo", "verification_mode": "existence", "cores": ["a_standalone_only", "b_libretro"], "systems": {}, @@ -407,7 +407,7 @@ class SkippingIsNotSettling(unittest.TestCase): ) return {(u["emulator"], u["name"]) for u in found} finally: - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() tmp.cleanup() def test_the_profile_that_needs_the_file_still_reports_it(self): @@ -438,7 +438,7 @@ class OneProfileSelector(unittest.TestCase): } def _select(self, names, standalone=False): - from common import ProfileSelectionError, select_emulator_profiles + from model.profiles import ProfileSelectionError, select_emulator_profiles try: return select_emulator_profiles(names, self.PROFILES, standalone), None diff --git a/tests/test_nec_filing.py b/tests/test_nec_filing.py index bfa49f606..67947590f 100644 --- a/tests/test_nec_filing.py +++ b/tests/test_nec_filing.py @@ -25,7 +25,7 @@ class PC88FilesStayInPC88(unittest.TestCase): folder = REPO_ROOT / "bios" / "NEC" / "PC-98" if not folder.is_dir(): self.skipTest("bios/NEC/PC-98 is absent") - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles readers: dict[str, set[str]] = {} for profile in load_emulator_profiles(str(REPO_ROOT / "emulators")).values(): diff --git a/tests/test_no_case_collisions.py b/tests/test_no_case_collisions.py index ac8c4fbbd..d5644d0a3 100644 --- a/tests/test_no_case_collisions.py +++ b/tests/test_no_case_collisions.py @@ -74,11 +74,9 @@ class SharedGroupsAddNoSecondSpelling(unittest.TestCase): and verify counted one more required file.""" def test_no_group_entry_respells_a_declared_destination(self) -> None: - 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 # A spelling some code opens as its own file stands: NP2kai's rhythm # engine reads 2608_bd.wav, its fmgen engine 2608_BD.WAV, and a @@ -117,7 +115,7 @@ class Np2kaiRhythmSamplesAreTwoSets(unittest.TestCase): from the profile shipped one spelling and reported both OK.""" def test_each_spelling_is_its_own_entry(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles files = load_emulator_profiles(str(REPO_ROOT / "emulators"))["np2kai"]["files"] paths = {entry.get("path") for entry in files} diff --git a/tests/test_no_game_data.py b/tests/test_no_game_data.py index 44be1a6ee..175c3786e 100644 --- a/tests/test_no_game_data.py +++ b/tests/test_no_game_data.py @@ -28,7 +28,8 @@ from pathlib import Path import yaml -import common +from model.platforms import load_platform_config, _platform_config_cache +from model.profiles import _emulator_profiles_cache import generate_db import generate_pack as builder import install @@ -103,14 +104,14 @@ class _Fixture(unittest.TestCase): (self.platforms / "_registry.yml").write_text( yaml.dump({"platforms": {"handheld": {"config": "handheld.yml"}}}) ) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() self.out = self.root / "dist" self.out.mkdir() def tearDown(self): - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def pack(self, no_game_data: bool) -> tuple[str, set[str], str]: @@ -182,7 +183,7 @@ class PackNarrowing(_Fixture): def test_verify_reports_the_pack_the_builder_wrote(self): zip_path, members, _ = self.pack(no_game_data=True) - config = common.load_platform_config("handheld", str(self.platforms)) + config = load_platform_config("handheld", str(self.platforms)) result = verify.verify_platform( config, self.db, str(self.emulators), PROFILES, no_game_data=True, ) @@ -202,7 +203,7 @@ class PackNarrowing(_Fixture): self.assertFalse(full[0]) def test_the_full_report_is_unchanged(self): - config = common.load_platform_config("handheld", str(self.platforms)) + config = load_platform_config("handheld", str(self.platforms)) result = verify.verify_platform(config, self.db, str(self.emulators), PROFILES) self.assertNotIn("left_out", result) self.assertEqual(set(result["pack_destinations"]), FIRMWARE | GAME) diff --git a/tests/test_np2_fonts.py b/tests/test_np2_fonts.py index 97e8d4431..750bdc7ec 100644 --- a/tests/test_np2_fonts.py +++ b/tests/test_np2_fonts.py @@ -20,7 +20,7 @@ from pathlib import Path import yaml -from common import resolve_local_file +from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_optional_dependencies.py b/tests/test_optional_dependencies.py index d96f09466..dd90c63a8 100644 --- a/tests/test_optional_dependencies.py +++ b/tests/test_optional_dependencies.py @@ -158,7 +158,8 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase): class TheDownloaderRunsWithoutPyyaml(unittest.TestCase): """download.py is the documented Windows downloader, "stdlib only". It - stays so only because common.py imports yaml optionally: made a plain + stays so only because the core modules it imports use the standard + library alone (tests/test_layers.py): had one imported yaml as a plain import, every CI job (which installs pyyaml) would stay green.""" def test_help_runs_with_yaml_unimportable(self): diff --git a/tests/test_owner_resolution.py b/tests/test_owner_resolution.py index 10b4f5fa9..408770382 100644 --- a/tests/test_owner_resolution.py +++ b/tests/test_owner_resolution.py @@ -19,11 +19,9 @@ from pathlib import Path import cross_reference import slots -from common import ( - build_zip_contents_index, - load_database, - load_emulator_profiles, -) +from core.ziptools import build_zip_contents_index +from model.database import load_database +from model.profiles import load_emulator_profiles REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_pack_core_extras.py b/tests/test_pack_core_extras.py index b7df27caf..6bae4cd22 100644 --- a/tests/test_pack_core_extras.py +++ b/tests/test_pack_core_extras.py @@ -147,7 +147,8 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): now held to the platform list narrowed the way it was built.""" def setUp(self): - import common + from model.platforms import _platform_config_cache + from model.profiles import load_emulator_profiles, _emulator_profiles_cache import generate_db import generate_pack @@ -184,11 +185,11 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): {"name": "core.bin", "path": "core.bin", "required": True}, {"name": "extra.bin", "path": "extra.bin", "required": False}, ]}), encoding="utf-8") - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.addCleanup(common._platform_config_cache.clear) - self.addCleanup(common._emulator_profiles_cache.clear) - self.profiles = common.load_emulator_profiles("emulators") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.addCleanup(_platform_config_cache.clear) + self.addCleanup(_emulator_profiles_cache.clear) + self.profiles = load_emulator_profiles("emulators") def _build(self, source: str, required: bool) -> tuple[str, set[str]]: zip_path = self.gp.generate_pack( diff --git a/tests/test_pack_counts.py b/tests/test_pack_counts.py index 2e5ed4d47..c4e9e2f8e 100644 --- a/tests/test_pack_counts.py +++ b/tests/test_pack_counts.py @@ -28,7 +28,9 @@ try: import jsonschema except ImportError: jsonschema = None -import common +from core.artifacts import ArtifactLockBusy, artifact_lock +from model.platforms import _platform_config_cache +from model.profiles import _emulator_profiles_cache, load_emulator_profiles import generate_db import generate_pack as builder import generate_readme @@ -104,11 +106,11 @@ class PackCountFixture(unittest.TestCase): yaml.dump({"platforms": {"demo": {"config": "demo.yml"}}}) ) (self.emulators / "demo.yml").write_text(PROFILE) - common._emulator_profiles_cache.clear() - self.profiles = common.load_emulator_profiles(str(self.emulators)) + _emulator_profiles_cache.clear() + self.profiles = load_emulator_profiles(str(self.emulators)) def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def _manifest(self) -> dict: @@ -157,8 +159,8 @@ class ManifestStatesWhatThePackHolds(PackCountFixture): ], }}} (self.platforms / "demo.yml").write_text(yaml.dump(platform)) - common._platform_config_cache.clear() - self.addCleanup(common._platform_config_cache.clear) + _platform_config_cache.clear() + self.addCleanup(_platform_config_cache.clear) out = self.root / "dist" out.mkdir() zip_path = builder.generate_pack( @@ -491,8 +493,8 @@ class ReleaseRecord(unittest.TestCase): self.assertNotIn(narrowed, owners) def test_a_directory_being_written_is_not_read(self): - with common.artifact_lock(str(self.dist)), \ - self.assertRaises(common.ArtifactLockBusy): + with artifact_lock(str(self.dist)), \ + self.assertRaises(ArtifactLockBusy): release_record.build_record(self.dist, "v1", owners=self.OWNERS) @@ -527,7 +529,7 @@ class RefusedFilesAreNotPresent(unittest.TestCase): def test_the_coverage_subtracts_a_refused_file(self): import os - import common + from model.platforms import _platform_config_cache import generate_db import generate_readme @@ -560,8 +562,8 @@ class RefusedFilesAreNotPresent(unittest.TestCase): Path("platforms/_registry.yml").write_text( yaml.dump({"platforms": {"hashy": {"config": "hashy.yml"}}}) ) - common._platform_config_cache.clear() - self.addCleanup(common._platform_config_cache.clear) + _platform_config_cache.clear() + self.addCleanup(_platform_config_cache.clear) coverage = generate_readme.compute_coverage( "hashy", "platforms", db, emulators_dir="emulators" ) diff --git a/tests/test_pack_destinations.py b/tests/test_pack_destinations.py index d832e491e..45035c286 100644 --- a/tests/test_pack_destinations.py +++ b/tests/test_pack_destinations.py @@ -29,7 +29,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class _Fixture(unittest.TestCase): def setUp(self) -> None: - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) @@ -61,7 +61,8 @@ class _Fixture(unittest.TestCase): return config def _both(self) -> tuple[dict, set[str]]: - from common import load_emulator_profiles, load_platform_config + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from generate_pack import generate_pack from verify import verify_platform @@ -126,7 +127,8 @@ class ARequiredOnlyPack(_Fixture): """verify had no --required-only: nothing compared the pack to a report.""" def test_verify_credits_what_the_pack_writes(self): - from common import load_emulator_profiles, load_platform_config + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from generate_pack import PackRecord, generate_pack from verify import verify_platform @@ -206,7 +208,8 @@ class EveryNarrowingIsCompared(unittest.TestCase): def test_the_variants_reach_every_compared_dimension(self): import pipeline - from common import load_emulator_profiles, load_platform_config + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config platforms = str(REPO_ROOT / "platforms") config = load_platform_config("retroarch", platforms) diff --git a/tests/test_pack_grouping.py b/tests/test_pack_grouping.py index 9eba81986..5c53ed9a9 100644 --- a/tests/test_pack_grouping.py +++ b/tests/test_pack_grouping.py @@ -22,7 +22,9 @@ class SlotPassReadsTheRegionGrouping(unittest.TestCase): if not (REPO_ROOT / "database.json").is_file(): self.skipTest("database.json not built") import generate_pack as gp - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config previous = os.getcwd() os.chdir(REPO_ROOT) @@ -56,7 +58,9 @@ class VariantGroupSpansSystems(unittest.TestCase): self.skipTest("database.json not built") import generate_pack as gp import region as region_mod - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config previous = os.getcwd() os.chdir(REPO_ROOT) @@ -86,7 +90,8 @@ class AFrontendCheckSeparatesPacks(unittest.TestCase): import yaml - import common + from model.platforms import _platform_config_cache + from resolve.grouping import group_identical_platforms files = [{"name": "a.bin", "destination": "a.bin", "md5": "0" * 32}] with tempfile.TemporaryDirectory() as tmp: @@ -98,9 +103,9 @@ class AFrontendCheckSeparatesPacks(unittest.TestCase): "systems": {"s": {"files": [entry]}}, })) Path(tmp, "_registry.yml").write_text(yaml.dump({"platforms": {}})) - common._platform_config_cache.clear() - self.addCleanup(common._platform_config_cache.clear) - groups = common.group_identical_platforms(["one", "two", "three"], tmp) + _platform_config_cache.clear() + self.addCleanup(_platform_config_cache.clear) + groups = group_identical_platforms(["one", "two", "three"], tmp) self.assertEqual(sorted(g for g, _ in groups), [["one"], ["three"], ["two"]]) diff --git a/tests/test_pack_integrity.py b/tests/test_pack_integrity.py index b26cc3f19..b3465a844 100644 --- a/tests/test_pack_integrity.py +++ b/tests/test_pack_integrity.py @@ -43,7 +43,7 @@ def _pack_path(platform_name: str) -> str | None: def _registered_platforms() -> list[str]: - from common import list_registered_platforms + from model.registry import list_registered_platforms return list_registered_platforms(PLATFORMS_DIR) @@ -55,7 +55,9 @@ def _profiles_newer_than(path: str, platform_name: str) -> list[str]: comment edited in any of 500 profiles used to disarm the integrity check of every pack on disk. """ - from common import load_emulator_profiles, load_platform_config, resolve_platform_cores + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from resolve.cores import resolve_platform_cores built = os.path.getmtime(path) config = load_platform_config(platform_name, PLATFORMS_DIR) diff --git a/tests/test_path_conflict_status.py b/tests/test_path_conflict_status.py index 81edf6df0..15101b3e8 100644 --- a/tests/test_path_conflict_status.py +++ b/tests/test_path_conflict_status.py @@ -20,7 +20,8 @@ from pathlib import Path import yaml -import common +from model.platforms import load_platform_config, _platform_config_cache +from model.profiles import _emulator_profiles_cache import generate_db import generate_pack as builder from verify import verify_platform @@ -66,11 +67,11 @@ class ConflictingDeclarations(unittest.TestCase): (self.platforms / "_registry.yml").write_text( yaml.dump({"platforms": {"conflict": {"config": "conflict.yml"}}}) ) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._platform_config_cache.clear() + _platform_config_cache.clear() self._tmp.cleanup() def test_the_pack_and_verify_count_alike(self): @@ -86,7 +87,7 @@ class ConflictingDeclarations(unittest.TestCase): packed = re.search(r"(\d+)/(\d+) files OK", report.getvalue()) self.assertIsNotNone(packed, report.getvalue()) - config = common.load_platform_config("conflict", str(self.platforms)) + config = load_platform_config("conflict", str(self.platforms)) verified = verify_platform(config, self.db, str(self.emulators)) counts = verified["status_counts"] self.assertEqual(counts.get("missing"), 1) @@ -142,12 +143,12 @@ class AnExtraDoesNotPassAHashCheck(unittest.TestCase): "required": True}], } (self.emulators / "fxcore.yml").write_text(yaml.dump(profile)) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def test_the_declaration_stays_failed(self): @@ -161,7 +162,7 @@ class AnExtraDoesNotPassAHashCheck(unittest.TestCase): ) packed = re.search(r"(\d+)/(\d+) files OK", report.getvalue()) self.assertIsNotNone(packed, report.getvalue()) - config = common.load_platform_config("hashed", str(self.platforms)) + config = load_platform_config("hashed", str(self.platforms)) verified = verify_platform(config, self.db, str(self.emulators)) self.assertEqual(verified["status_counts"].get("ok", 0), 0) self.assertEqual(int(packed.group(1)), 0, report.getvalue()) @@ -196,10 +197,10 @@ class TheEmulatorPackShipsWhatTheCoreAccepts(unittest.TestCase): "max_size": 1048576, "validation": ["size"]}], } (self.emulators / "mac.yml").write_text(yaml.dump(profile)) - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def test_the_refused_rom_is_named_not_shipped(self): @@ -253,10 +254,10 @@ class AlternativesAgreeWithThePack(unittest.TestCase): ], } (self.emulators / "eng.yml").write_text(yaml.dump(profile)) - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def test_verify_counts_what_the_pack_ships(self): @@ -315,10 +316,10 @@ class AMaskedArchiveIsMissing(unittest.TestCase): "files": [{"name": "y.bin", "archive": "pack.zip", "required": True, "crc32": f"{__import__('zlib').crc32(b'y'):08x}"}], })) - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self._tmp.cleanup() def test_both_report_the_archive_missing(self): diff --git a/tests/test_path_null_copies.py b/tests/test_path_null_copies.py index 5b9b14018..76db05ecf 100644 --- a/tests/test_path_null_copies.py +++ b/tests/test_path_null_copies.py @@ -24,7 +24,9 @@ class NoPathNoCopy(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from packextras import _collect_emulator_extras profiles = load_emulator_profiles("emulators") diff --git a/tests/test_path_suffix.py b/tests/test_path_suffix.py index eddef2f06..861d90ce4 100644 --- a/tests/test_path_suffix.py +++ b/tests/test_path_suffix.py @@ -10,7 +10,7 @@ import tempfile import unittest from pathlib import Path -from common import resolve_local_file +from resolve.localfile import resolve_local_file from generate_db import _path_suffixes diff --git a/tests/test_pin_build.py b/tests/test_pin_build.py index 77829ca51..2d7d2d9a0 100644 --- a/tests/test_pin_build.py +++ b/tests/test_pin_build.py @@ -137,7 +137,7 @@ class EveryBuildReferenceNamesThePin(unittest.TestCase): platform's own YAML was scraped from that repository.""" def test_the_values_agree(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles disagree = [] for name, profile in load_emulator_profiles(str(REPO_ROOT / "emulators")).items(): diff --git a/tests/test_platform_inheritance.py b/tests/test_platform_inheritance.py index 081c1fe63..125ac36a5 100644 --- a/tests/test_platform_inheritance.py +++ b/tests/test_platform_inheritance.py @@ -17,7 +17,8 @@ from pathlib import Path import yaml -import common +from model.platforms import load_platform_config, _platform_config_cache, _shared_yml_cache +from resolve.grouping import group_identical_platforms REPO_ROOT = Path(__file__).resolve().parents[1] @@ -26,8 +27,8 @@ class AChildLeavesItsParentAlone(unittest.TestCase): def setUp(self): self.dir = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, self.dir, True) - self.addCleanup(common._platform_config_cache.clear) - self.addCleanup(common._shared_yml_cache.clear) + self.addCleanup(_platform_config_cache.clear) + self.addCleanup(_shared_yml_cache.clear) files = { "parent.yml": {"platform": "Parent", "verification_mode": "existence", "systems": {"sys-a": {"files": [{"name": "a.bin"}]}}}, @@ -44,7 +45,7 @@ class AChildLeavesItsParentAlone(unittest.TestCase): (self.dir / name).write_text(yaml.safe_dump(data)) def load(self, name): - return common.load_platform_config(name, str(self.dir)) + return load_platform_config(name, str(self.dir)) def test_the_parent_keeps_its_systems(self): self.load("parent") @@ -75,15 +76,15 @@ class ALinuxPlatformKeepsBothCases(unittest.TestCase): exact case, and only System.dat's 2608_BD.WAV and BIOS.col shipped.""" def setUp(self): - self.addCleanup(common._platform_config_cache.clear) - common._platform_config_cache.clear() + self.addCleanup(_platform_config_cache.clear) + _platform_config_cache.clear() def test_the_linux_platforms_do_not_fold(self): platforms = str(REPO_ROOT / "platforms") - self.assertTrue(common.load_platform_config("retroarch", platforms)["case_insensitive_fs"]) + self.assertTrue(load_platform_config("retroarch", platforms)["case_insensitive_fs"]) for name in ("lakka", "retropie"): with self.subTest(platform=name): - config = common.load_platform_config(name, platforms) + config = load_platform_config(name, platforms) self.assertFalse(config["case_insensitive_fs"]) dests = { f.get("destination", f.get("name")) @@ -92,7 +93,7 @@ class ALinuxPlatformKeepsBothCases(unittest.TestCase): self.assertTrue({"np2kai/2608_BD.WAV", "np2kai/2608_bd.wav"} <= dests) def test_lakka_does_not_share_retroarchs_pack(self): - groups = common.group_identical_platforms( + groups = group_identical_platforms( ["retroarch", "lakka"], str(REPO_ROOT / "platforms") ) self.assertEqual(sorted(g for g, _rep in groups), [["lakka"], ["retroarch"]]) diff --git a/tests/test_platform_keys.py b/tests/test_platform_keys.py index 9e6498cf5..5e96d9472 100644 --- a/tests/test_platform_keys.py +++ b/tests/test_platform_keys.py @@ -31,7 +31,7 @@ class ZippedFileKey(unittest.TestCase): self.assertIsNone(pattern.search(path.read_text(encoding="utf-8"))) def test_member_md5_declares_no_loose_name(self): - from common import expand_platform_declared_names + from model.declarations import expand_platform_declared_names config = {"systems": {"s": {"files": [ {"name": "casloopy.zip", "md5": "m1", "zipped_file": "hd6437021.lsi302"}, diff --git a/tests/test_profile_names.py b/tests/test_profile_names.py index 42ce7cbfc..21930e65d 100644 --- a/tests/test_profile_names.py +++ b/tests/test_profile_names.py @@ -12,7 +12,7 @@ import tests import unittest from pathlib import Path -from common import load_emulator_profiles +from model.profiles import load_emulator_profiles REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index 2a45ddb70..d098efbe0 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -3039,7 +3039,7 @@ class TestDeliberatelyFrozenPin(TestBuildReport): # reicast is the commit Recalbox's reicast.mk builds, 789 commits # behind master. Compared to HEAD it showed eight refs to review that # nobody could act on. - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles root = Path(__file__).resolve().parents[1] / "emulators" profiles = load_emulator_profiles(str(root)) @@ -3059,7 +3059,7 @@ class TestDeliberatelyFrozenPin(TestBuildReport): # RetroPie builds ppsspp-1.5.4 as PPSSPPSDL alone: the frozen build # is the standalone half of a project that also ships a core. builds_differ = {("duckstation-legacy", "duckstation"), ("ppsspp-1.5.4", "ppsspp")} - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles root = Path(__file__).resolve().parents[1] / "emulators" profiles = load_emulator_profiles(str(root)) @@ -5125,7 +5125,7 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): with mock.patch.object(sitesources, "build_source_paths", return_value=({}, [])) as built, \ mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \ - mock.patch("common.write_if_changed") as written, \ + mock.patch("core.artifacts.write_if_changed") as written, \ contextlib.redirect_stderr(io.StringIO()): profile_sync._WRITTEN.clear() profile_sync._refresh_source_paths(self._args()) @@ -5143,19 +5143,20 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): # before writing them: the record kept the pins it had replaced. from unittest import mock - import common + from model import profiles as model_profiles + from model.profiles import _emulator_profiles_cache import sitesources with tempfile.TemporaryDirectory() as tmp: profile = Path(tmp) / "p.yml" profile.write_text('emulator: P\nsource_commit: "old"\n', encoding="utf-8") - common._emulator_profiles_cache.clear() - self.addCleanup(common._emulator_profiles_cache.clear) - common.load_emulator_profiles(tmp, skip_aliases=False) + _emulator_profiles_cache.clear() + self.addCleanup(_emulator_profiles_cache.clear) + model_profiles.load_emulator_profiles(tmp, skip_aliases=False) profile.write_text('emulator: P\nsource_commit: "new"\n', encoding="utf-8") with mock.patch.object(sitesources, "build_source_paths", return_value=({}, [])) as built, \ mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ - mock.patch("common.write_if_changed"), \ + mock.patch("core.artifacts.write_if_changed"), \ contextlib.redirect_stderr(io.StringIO()), \ contextlib.redirect_stdout(io.StringIO()): profile_sync._WRITTEN.add("p") diff --git a/tests/test_proven_name.py b/tests/test_proven_name.py index 87a196662..7a7c93f47 100644 --- a/tests/test_proven_name.py +++ b/tests/test_proven_name.py @@ -22,7 +22,7 @@ import zlib from pathlib import Path import generate_db -from common import resolve_local_file +from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_provenance.py b/tests/test_provenance.py index 3322f9acd..34dd0916e 100644 --- a/tests/test_provenance.py +++ b/tests/test_provenance.py @@ -10,7 +10,7 @@ import unittest import zipfile from pathlib import Path -from scripts.common import ( +from scripts.model.dumpcatalog import ( annotate_provenance, build_provenance_index, load_provenance_snapshots, diff --git a/tests/test_region.py b/tests/test_region.py index b2919f676..eef654e99 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -11,7 +11,8 @@ import sys import unittest from pathlib import Path -import common +from model import profiles as model_profiles +from model.profiles import _emulator_profiles_cache import region from packextras import emulator_region_drops @@ -491,7 +492,7 @@ class OneCodeOneRegionAnswer(unittest.TestCase): PROFILES = os.path.join(os.path.dirname(__file__), "..", "emulators") def test_the_mednafen_saturn_profiles_agree(self): - profiles = common.load_emulator_profiles(self.PROFILES) + profiles = model_profiles.load_emulator_profiles(self.PROFILES) seen: dict[str, dict[str, frozenset]] = {} for name in ("mednafen", "beetle_saturn", "saturn-emu", "mednafen_stv"): for entry in profiles[name]["files"]: @@ -505,7 +506,7 @@ class OneCodeOneRegionAnswer(unittest.TestCase): self.assertIn("oceania", next(iter(tags.values()))) def test_export_cartridges_and_allowed_regions(self): - profiles = common.load_emulator_profiles(self.PROFILES) + profiles = model_profiles.load_emulator_profiles(self.PROFILES) bios_sms = next(e for e in profiles["clk"]["files"] if e["name"] == "bios.sms") self.assertIn("oceania", bios_sms["region"]) # A Mexican export cartridge is analysed as Europe or USA and boots the @@ -526,7 +527,7 @@ class AustraliaReadsThePalIpl(unittest.TestCase): alone, `--region australia` dropped it and kept the American one.""" def test_the_pal_ipl_answers_oceania(self): - profiles = common.load_emulator_profiles( + profiles = model_profiles.load_emulator_profiles( os.path.join(os.path.dirname(__file__), "..", "emulators") ) for name in ("dolphin", "primehack", "ishiiruka", "triforce"): @@ -694,14 +695,15 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): return tmp, root, db, config def test_the_report_withdraws_what_the_builder_withdraws(self): - import common + from model import profiles as model_profiles + from model.profiles import _emulator_profiles_cache import generate_pack as builder import verify as reporter tmp, root, db, config = self._fixture() try: - common._emulator_profiles_cache.clear() - profiles = common.load_emulator_profiles(str(root / "emulators")) + _emulator_profiles_cache.clear() + profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) groups, extra_dests = builder.platform_region_groups( config, config["systems"], str(root / "emulators"), db, "", profiles, @@ -730,14 +732,15 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): "the report must withdraw exactly the builder's drop set", ) finally: - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() tmp.cleanup() def test_a_missing_regional_core_file_is_withdrawn_too(self): """A missing platform file is grouped and withdrawn under --region, but a missing core file was never grouped and stayed "required missing" for a region the request excludes.""" - import common + from model import profiles as model_profiles + from model.profiles import _emulator_profiles_cache import verify as reporter tmp, root, db, config = self._fixture() @@ -745,8 +748,8 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): jp = next(k for k, v in db["files"].items() if v["name"] == "jp.bin") del db["files"][jp] del db["indexes"]["by_name"]["jp.bin"] - common._emulator_profiles_cache.clear() - profiles = common.load_emulator_profiles(str(root / "emulators")) + _emulator_profiles_cache.clear() + profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) plain = reporter.verify_platform( config, db, str(root / "emulators"), profiles, ) @@ -760,19 +763,20 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): {u["name"] for u in narrowed["undeclared_files"]}, {"us.bin"} ) finally: - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() tmp.cleanup() def test_the_report_names_the_fallback_groups(self): """The pack README lists the systems kept whole because nothing answers the request. verify said all OK and named none.""" - import common + from model import profiles as model_profiles + from model.profiles import _emulator_profiles_cache import verify as reporter tmp, root, db, config = self._fixture() try: - common._emulator_profiles_cache.clear() - profiles = common.load_emulator_profiles(str(root / "emulators")) + _emulator_profiles_cache.clear() + profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) result = reporter.verify_platform( config, db, str(root / "emulators"), profiles, regions=["brazil"], @@ -783,7 +787,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): reporter.print_platform_result(result, ["Demo"]) self.assertIn("all kept (1): demo-system", out.getvalue()) finally: - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() tmp.cleanup() def test_one_grouping_pass_serves_both_sides(self): @@ -820,7 +824,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): if not (repo / "emulators" / "o2em.yml").is_file(): self.skipTest("no o2em profile") from verify import verify_emulator - from common import load_database + from model.database import load_database db = load_database(str(repo / "database.json")) full = verify_emulator(["o2em"], str(repo / "emulators"), db) @@ -934,7 +938,7 @@ class RegionalRequestsKeepWhatTheCodeLoads(unittest.TestCase): ) def test_each_request_keeps_its_file(self): - profiles = common.load_emulator_profiles( + profiles = model_profiles.load_emulator_profiles( os.path.join(os.path.dirname(__file__), "..", "emulators") ) for name, regions, kept in self.CASES: @@ -960,7 +964,7 @@ class DsiNandFollowsTheHeaderRegion(unittest.TestCase): } def _profile(self) -> dict: - return common.load_emulator_profiles( + return model_profiles.load_emulator_profiles( os.path.join(os.path.dirname(__file__), "..", "emulators") )["bizhawk"] @@ -984,7 +988,7 @@ class FontRomsCarryNoTerritory(unittest.TestCase): from the generic MSX2+ machine whose config.ini loads both.""" def test_no_kanji_or_hangul_font_declares_a_region(self): - profiles = common.load_emulator_profiles( + profiles = model_profiles.load_emulator_profiles( os.path.join(os.path.dirname(__file__), "..", "emulators") ) tagged = [ @@ -1083,7 +1087,7 @@ class GenesisPlusGxUsBiosServesEurope(unittest.TestCase): def test_eu_jp_keeps_bios_u(self): from pathlib import Path - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from region import build_region_index, parse_requested, resolve_region_drops root = Path(__file__).resolve().parents[1] @@ -1104,7 +1108,7 @@ class GenesisPlusGxUsBiosServesEurope(unittest.TestCase): def _real_drops(profile: str, members: list[str], requested: str) -> set[str]: from pathlib import Path - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from region import build_region_index, parse_requested, resolve_region_drops root = Path(__file__).resolve().parents[1] @@ -1139,7 +1143,7 @@ class KoreanGameCubeDiscsReadTheJapaneseIpl(unittest.TestCase): for profile in ("dolphin", "dolphin-mmjr", "dolphin-mmjr2", "ishiiruka", "primehack", "triforce"): with self.subTest(profile=profile): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles entries = [ f for f in load_emulator_profiles("emulators")[profile]["files"] @@ -1157,7 +1161,7 @@ class ANameNoCodeOpensCarriesNoRegion(unittest.TestCase): exist.""" def test_scph5903_is_unregioned(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles entry = next( f for f in load_emulator_profiles("emulators")["beetle_psx"]["files"] @@ -1216,7 +1220,7 @@ class PcsxRearmedUsSlotIsTheDefault(unittest.TestCase): other market boots the US slot.""" def test_every_us_slot_bios_includes_latin_america(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles tagged = [ f for f in load_emulator_profiles("emulators")["pcsx_rearmed"]["files"] @@ -1241,7 +1245,7 @@ class PlayStationUsImageAnswersTheAmericaLicence(unittest.TestCase): "rustation": 6, "duckstation": 28} def test_every_us_image_includes_latin_america(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles profiles = load_emulator_profiles("emulators") for name, count in self.COUNTS.items(): @@ -1263,7 +1267,7 @@ class FusionSmsExportBiosFollowsTheSetting(unittest.TestCase): list. Neither export BIOS is chosen for a territory the cart names.""" def test_the_export_bioses_are_unregioned(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles files = {f["name"]: f for f in load_emulator_profiles("emulators")["kega-fusion"]["files"]} for name in ("bios_U.sms", "bios_E.sms"): @@ -1307,7 +1311,7 @@ class ARefusedRegionalFileHoldsNoSlot(unittest.TestCase): from generate_pack import generate_emulator_pack from verify import verify_emulator - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() repo = Path(__file__).resolve().parents[1] (repo / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=repo / "tmp")) @@ -1394,7 +1398,7 @@ class MachineModelRomsCarryNoTerritory(unittest.TestCase): } def test_model_roms_are_unregioned(self): - profiles = common.load_emulator_profiles( + profiles = model_profiles.load_emulator_profiles( os.path.join(os.path.dirname(__file__), "..", "emulators") ) for profile, names in self.CASES.items(): diff --git a/tests/test_region_agnostic_scan.py b/tests/test_region_agnostic_scan.py index b41b67173..3d3ffe272 100644 --- a/tests/test_region_agnostic_scan.py +++ b/tests/test_region_agnostic_scan.py @@ -26,7 +26,9 @@ class ScanCopiesStay(unittest.TestCase): os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) import region as region_mod - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from packextras import platform_region_groups db = load_database("database.json") diff --git a/tests/test_region_check.py b/tests/test_region_check.py index deb73d3f4..8e1e5de84 100644 --- a/tests/test_region_check.py +++ b/tests/test_region_check.py @@ -180,7 +180,7 @@ class ContentList(unittest.TestCase): def test_every_region_system_has_a_game_per_region_or_says_why(self) -> None: """A system whose BIOS a profile ties to JP, US and EU has a game for each of the three, or the content list says why it has none.""" - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles import yaml diff --git a/tests/test_region_groups.py b/tests/test_region_groups.py index ee8277737..56b7e7efe 100644 --- a/tests/test_region_groups.py +++ b/tests/test_region_groups.py @@ -47,7 +47,9 @@ class TheEnterpriseKeepsItsRom(unittest.TestCase): if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not built") import region - from common import load_database, load_emulator_profiles, load_platform_config + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from packextras import platform_region_groups db = load_database(str(REPO_ROOT / "database.json")) @@ -65,7 +67,7 @@ class TheEnterpriseKeepsItsRom(unittest.TestCase): def test_brd_rom_is_chosen_by_the_content_not_a_territory(self): # core.hpp:221-226: "[req brd-rom]" in the content name selects it, # whatever the user's country, as "[req zrom]" selects hun.rom. - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) entry = next( @@ -107,8 +109,10 @@ class ALosingClaimIsKeyedLikeTheWinner(unittest.TestCase): def test_a_losing_claim_carries_the_declared_root(self): import os - from common import declared_root, load_database, load_emulator_profiles - from common import load_platform_config + from model.declarations import declared_root + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from packextras import platform_region_groups previous = os.getcwd() diff --git a/tests/test_region_held.py b/tests/test_region_held.py index e9bf91692..c7b85c7f4 100644 --- a/tests/test_region_held.py +++ b/tests/test_region_held.py @@ -66,8 +66,10 @@ class ADataDirectoryCopyIsHeld(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) try: - from common import load_data_dir_registry, load_database - from common import load_emulator_profiles, load_platform_config + from model.registry import load_data_dir_registry + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config cls.db = load_database("database.json") cls.registry = load_data_dir_registry("platforms") cls.profiles = load_emulator_profiles("emulators") diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index bbe275310..845045f70 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -26,7 +26,7 @@ from unittest import mock import yaml -import common +from model.registry import list_registered_platforms, list_release_pack_platforms import release_record REPO_ROOT = Path(__file__).resolve().parent.parent @@ -62,7 +62,7 @@ def _which_pack() -> str: class TheFieldIsTheList(unittest.TestCase): def test_the_registry_marks_the_most_downloaded_setups(self): self.assertEqual( - set(common.list_release_pack_platforms(PLATFORMS)), RELEASED + set(list_release_pack_platforms(PLATFORMS)), RELEASED ) def test_only_marked_platforms_are_listed(self): @@ -72,9 +72,9 @@ class TheFieldIsTheList(unittest.TestCase): "small": {}, "off": {"release_pack": False}, }) - self.assertEqual(common.list_release_pack_platforms(platforms_dir), ["big"]) + self.assertEqual(list_release_pack_platforms(platforms_dir), ["big"]) self.assertEqual( - common.list_registered_platforms(platforms_dir), ["big", "off", "small"] + list_registered_platforms(platforms_dir), ["big", "off", "small"] ) def test_the_schema_holds_the_field(self): @@ -145,7 +145,7 @@ class TheBuildReadsTheField(unittest.TestCase): def test_manifests_cover_every_platform(self): self.assertEqual( set(self._groups("--all", "--manifest", "--offline")), - set(common.list_registered_platforms(PLATFORMS)), + set(list_registered_platforms(PLATFORMS)), ) def test_the_release_owners_are_the_marked_platforms(self): @@ -475,7 +475,7 @@ class EveryPlatformHasAPermanentPage(unittest.TestCase): record = release_record.load_advertised() with contextlib.chdir(REPO_ROOT): - for name in common.list_registered_platforms(PLATFORMS): + for name in list_registered_platforms(PLATFORMS): page = generate_site.generate_get_page(name) pack = release_record.pack_for(name, record) with self.subTest(platform=name): @@ -501,7 +501,7 @@ class EveryPlatformHasAPermanentPage(unittest.TestCase): docs = REPO_ROOT / "website" / "src" / "content" / "docs" / release_record.GET_DIR if not docs.is_dir(): self.skipTest("the site is not generated") - for name in common.list_registered_platforms(PLATFORMS): + for name in list_registered_platforms(PLATFORMS): with self.subTest(platform=name): self.assertTrue(any(docs.glob(f"{name}.md*"))) @@ -529,7 +529,7 @@ class TheSiteCheckResolvesEveryGetPage(unittest.TestCase): record_path.write_text(json.dumps(record), encoding="utf-8") pages = { f"get/{name}/index.html": "install.sh" - for name in common.list_registered_platforms(PLATFORMS) + for name in list_registered_platforms(PLATFORMS) } pages["get/romm/index.html"] = f'x' pages["get/knulli/index.html"] = f'x' diff --git a/tests/test_required_only_twins.py b/tests/test_required_only_twins.py index 8e4231fd8..e4858d6ec 100644 --- a/tests/test_required_only_twins.py +++ b/tests/test_required_only_twins.py @@ -21,7 +21,8 @@ from pathlib import Path import yaml -import common +from model.platforms import _platform_config_cache +from model.profiles import _emulator_profiles_cache import generate_db import generate_pack as builder @@ -69,11 +70,11 @@ class RequiredTwins(unittest.TestCase): (self.platforms / "_registry.yml").write_text( yaml.dump({"platforms": {"twins": {"config": "twins.yml"}}}) ) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._platform_config_cache.clear() + _platform_config_cache.clear() self._tmp.cleanup() def test_the_required_only_pack_carries_the_required_file(self): diff --git a/tests/test_resolution_evidence.py b/tests/test_resolution_evidence.py index 7e91f161b..d9018374e 100644 --- a/tests/test_resolution_evidence.py +++ b/tests/test_resolution_evidence.py @@ -19,7 +19,8 @@ import zipfile import zlib from pathlib import Path -import common +from resolve.content import declared_hash_verdict +from resolve.localfile import resolve_local_file, _resolve_agnostic REPO_ROOT = Path(__file__).resolve().parent.parent @@ -55,7 +56,7 @@ class DeclaredHashVerdict(unittest.TestCase): md5_list=[], crc_candidates=set(), zipped_file=None, declared_size=None, ) base.update(declared) - return common.declared_hash_verdict(str(path), **base) + return declared_hash_verdict(str(path), **base) def test_no_declared_hash_means_the_name_is_all_there_is(self): self.assertEqual( @@ -173,13 +174,13 @@ class AgnosticFallback(unittest.TestCase): "size": 64, } self.assertEqual( - common._resolve_agnostic(entry, self.files_db, False), + _resolve_agnostic(entry, self.files_db, False), (str(self.match), "agnostic_fallback"), ) def test_a_declared_hash_outranks_the_shape(self): entry = {"agnostic": True, "agnostic_path_prefix": str(self.root), "size": 64} - self.assertIsNone(common._resolve_agnostic(entry, self.files_db, True)) + self.assertIsNone(_resolve_agnostic(entry, self.files_db, True)) def test_the_wrong_size_is_not_a_candidate(self): entry = { @@ -187,7 +188,7 @@ class AgnosticFallback(unittest.TestCase): "agnostic_path_prefix": str(self.root), "size": 65, } - self.assertIsNone(common._resolve_agnostic(entry, self.files_db, False)) + self.assertIsNone(_resolve_agnostic(entry, self.files_db, False)) def test_a_size_range_is_honoured(self): entry = { @@ -196,7 +197,7 @@ class AgnosticFallback(unittest.TestCase): "min_size": 32, "max_size": 128, } - self.assertIsNotNone(common._resolve_agnostic(entry, self.files_db, False)) + self.assertIsNotNone(_resolve_agnostic(entry, self.files_db, False)) def test_a_list_of_accepted_sizes_is_honoured(self): entry = { @@ -205,19 +206,19 @@ class AgnosticFallback(unittest.TestCase): "size": [32, 64], } self.assertEqual( - common._resolve_agnostic(entry, self.files_db, False), + _resolve_agnostic(entry, self.files_db, False), (str(self.match), "agnostic_fallback"), ) entry["size"] = [32, 65] - self.assertIsNone(common._resolve_agnostic(entry, self.files_db, False)) + self.assertIsNone(_resolve_agnostic(entry, self.files_db, False)) def test_without_a_prefix_nothing_is_scanned(self): entry = {"agnostic": True, "size": 64} - self.assertIsNone(common._resolve_agnostic(entry, self.files_db, False)) + self.assertIsNone(_resolve_agnostic(entry, self.files_db, False)) def test_an_entry_that_is_not_agnostic_is_left_alone(self): entry = {"agnostic_path_prefix": str(self.root), "size": 64} - self.assertIsNone(common._resolve_agnostic(entry, self.files_db, False)) + self.assertIsNone(_resolve_agnostic(entry, self.files_db, False)) class OneSpellingForAcceptedSizes(unittest.TestCase): @@ -271,7 +272,7 @@ class SeveralAcceptedCrc32(unittest.TestCase): hack_first = sorted([crc[variant], crc[primary]]) entry = {"name": "syscard3.pce", "crc32": hack_first} self.assertEqual( - common.resolve_local_file(entry, db), (str(primary), "crc32_exact") + resolve_local_file(entry, db), (str(primary), "crc32_exact") ) @@ -296,7 +297,7 @@ class TheMatchingArchiveForAMember(unittest.TestCase): "by_md5": {}, "by_crc32": {}, "by_path_suffix": {}}} entry = {"name": "neogeo.zip", "zipped_file": "sfix.sfix", "md5": hashlib.md5(b"second").hexdigest()} - self.assertEqual(common.resolve_local_file(entry, db), (str(paths[1]), "zip_exact")) + self.assertEqual(resolve_local_file(entry, db), (str(paths[1]), "zip_exact")) if __name__ == "__main__": diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index 33d54ed71..d1bd3e5b3 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -663,7 +663,8 @@ class RepositoryRun(unittest.TestCase): if not database.is_file() or not bios.is_dir(): self.skipTest("collection not present in this checkout") - from common import load_database, load_emulator_profiles + from model.database import load_database + from model.profiles import load_emulator_profiles db = load_database(str(database)) recipes = collect_recipes( diff --git a/tests/test_save_root.py b/tests/test_save_root.py index 4e45c17dc..4b5d9a2a4 100644 --- a/tests/test_save_root.py +++ b/tests/test_save_root.py @@ -119,7 +119,7 @@ class ThePlatformNamesItsSaveDirectory(unittest.TestCase): ) def test_retroarch_and_lakka_have_one_retropie_none(self): - from common import load_platform_config + from model.platforms import load_platform_config platforms = str(REPO_ROOT / "platforms") self.assertEqual(save_layout(load_platform_config("retroarch", platforms)), @@ -132,7 +132,7 @@ class ThePlatformNamesItsSaveDirectory(unittest.TestCase): def test_each_platform_running_these_cores_says_where(self): """The layout read from each platform's launch code, or none where saves sit beside each game or in a browser.""" - from common import load_platform_config + from model.platforms import load_platform_config platforms = str(REPO_ROOT / "platforms") expected = { @@ -211,7 +211,8 @@ class _Fixture(unittest.TestCase): OTHER_KEYS = b"PLATFORM KEYS" def setUp(self) -> None: - from common import _emulator_profiles_cache, _platform_config_cache + from model.profiles import _emulator_profiles_cache + from model.platforms import _platform_config_cache _emulator_profiles_cache.clear() _platform_config_cache.clear() @@ -265,12 +266,12 @@ class _Fixture(unittest.TestCase): })) def config(self, name: str) -> dict: - from common import load_platform_config + from model.platforms import load_platform_config return load_platform_config(name, str(self.platforms)) def profiles(self) -> dict: - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles return load_emulator_profiles(str(self.emulators)) diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index a3cb5e91d..f9e724357 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -611,7 +611,7 @@ class EveryTargetCoreReachesAProfile(unittest.TestCase): import yaml import check_freshness - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles root = Path(__file__).resolve().parents[1] index = check_freshness.profile_name_index( @@ -932,7 +932,7 @@ class OneNativeIdOneSystem(unittest.TestCase): FOLDS = {"fbneo", "pcenginecd"} def test_scrapers_agree_on_every_shared_native_id(self): - from common import _norm_system_id + from model.systems import _norm_system_id seen: dict[str, dict[str, str]] = {} for path in sorted((REPO_ROOT / "scripts" / "scraper").glob("*_scraper.py")): @@ -977,11 +977,9 @@ class OneNativeIdOneSystem(unittest.TestCase): def test_every_platform_system_meets_a_profile_system(self): import yaml - from common import ( - _norm_system_id, - load_emulator_profiles, - load_platform_config, - ) + from model.systems import _norm_system_id + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config known = set() for profile in load_emulator_profiles(str(REPO_ROOT / "emulators")).values(): @@ -1000,7 +998,7 @@ class OneNativeIdOneSystem(unittest.TestCase): def test_xroar_machines_reach_the_platforms_that_run_it(self): import yaml - from common import _norm_system_id + from model.systems import _norm_system_id xroar = yaml.safe_load((REPO_ROOT / "emulators" / "xroar.yml").read_text()) machines = {_norm_system_id(s) for s in xroar["systems"]} diff --git a/tests/test_sega_filing.py b/tests/test_sega_filing.py index 9c2c2524b..445fc88df 100644 --- a/tests/test_sega_filing.py +++ b/tests/test_sega_filing.py @@ -22,7 +22,7 @@ class SegaFilesStayUnderSega(unittest.TestCase): folder = REPO_ROOT / "bios" / "Microsoft" / "MSX" if not folder.is_dir(): self.skipTest("bios/Microsoft/MSX is absent") - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles systems: dict[str, set[str]] = {} for profile in load_emulator_profiles(str(REPO_ROOT / "emulators")).values(): diff --git a/tests/test_shared_groups.py b/tests/test_shared_groups.py index f272e9eff..18e28809c 100644 --- a/tests/test_shared_groups.py +++ b/tests/test_shared_groups.py @@ -14,7 +14,7 @@ import tests import unittest from pathlib import Path -from common import load_emulator_profiles +from model.profiles import load_emulator_profiles from model.safeparse import yaml_load REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_shipped_content.py b/tests/test_shipped_content.py index 4c4f57237..e1e764c1e 100644 --- a/tests/test_shipped_content.py +++ b/tests/test_shipped_content.py @@ -26,7 +26,12 @@ import unittest import zipfile from pathlib import Path -import common +from core.hashing import md5_composite +from core.paths import sanitize_pack_path +from model.database import load_database +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from resolve.localfile import resolve_local_file from resolve.nativemode import reads_file_contents ROOT = Path(__file__).resolve().parent.parent @@ -71,7 +76,7 @@ class ShippedFilesSatisfyTheirDeclaration(unittest.TestCase): for manifest_path in sorted(self.install.glob("*.json")): platform = manifest_path.stem try: - config = common.load_platform_config(platform, str(ROOT / "platforms")) + config = load_platform_config(platform, str(ROOT / "platforms")) except (FileNotFoundError, KeyError): continue if not reads_file_contents(config.get("verification_mode")): @@ -85,13 +90,13 @@ class ShippedFilesSatisfyTheirDeclaration(unittest.TestCase): dest = entry.get("destination") or entry.get("name", "") if dest: declared.setdefault( - common.sanitize_pack_path(dest), [] + sanitize_pack_path(dest), [] ).append(entry) manifest = json.loads(manifest_path.read_text()) for shipped in manifest.get("files", []): entries = declared.get( - common.sanitize_pack_path(shipped.get("dest", "")), [] + sanitize_pack_path(shipped.get("dest", "")), [] ) entries = [e for e in entries if not e.get("zipped_file")] candidates = [(e, _declared_digests(e)) for e in entries] @@ -116,7 +121,7 @@ class ShippedFilesSatisfyTheirDeclaration(unittest.TestCase): # A variant carries its hash after the extension # (cdimono1.zip.e6714b3d), so the name is not the test. with contextlib.suppress(zipfile.BadZipFile, OSError): - digests["md5"].append(common.md5_composite(str(blob_path))) + digests["md5"].append(md5_composite(str(blob_path))) # A declared MD5 can be shorter than 32 characters: compare by prefix. satisfied = any( all( @@ -165,8 +170,8 @@ class ProfileContradictionsAreKnown(unittest.TestCase): database = ROOT / "database.json" if not database.is_file(): self.skipTest("database.json not built") - db = common.load_database(str(database)) - profiles = common.load_emulator_profiles(str(ROOT / "emulators")) + db = load_database(str(database)) + profiles = load_emulator_profiles(str(ROOT / "emulators")) unsatisfied = [] for name, profile in sorted(profiles.items()): if profile.get("type") in ("alias", "launcher"): @@ -180,7 +185,7 @@ class ProfileContradictionsAreKnown(unittest.TestCase): continue if not _declared_digests(entry): continue - path, status = common.resolve_local_file( + path, status = resolve_local_file( entry, db, dest_hint=entry.get("path", "") ) if path and status == "hash_mismatch": @@ -220,7 +225,7 @@ class ArchiveNamesDesignateArchives(unittest.TestCase): database = ROOT / "database.json" if not database.is_file(): self.skipTest("database.json not built") - db = common.load_database(str(database)) + db = load_database(str(database)) loose = [] for name, ids in db["indexes"]["by_name"].items(): if not name.lower().endswith(".zip"): diff --git a/tests/test_site_availability.py b/tests/test_site_availability.py index f61ba4d6c..583084182 100644 --- a/tests/test_site_availability.py +++ b/tests/test_site_availability.py @@ -15,7 +15,7 @@ from pathlib import Path import yaml -from common import load_database +from model.database import load_database from generate_site import _availability_check, _file_badges REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_site_built_gate.py b/tests/test_site_built_gate.py index 8b0ad37ba..ad1c3370c 100644 --- a/tests/test_site_built_gate.py +++ b/tests/test_site_built_gate.py @@ -192,7 +192,7 @@ class EveryBuiltPage(unittest.TestCase): class TheIntegrationItems(unittest.TestCase): def test_a_platform_page_draws_its_logo_beside_the_title(self): - from common import load_platform_registry + from model.registry import load_platform_registry registry = load_platform_registry(str(REPO_ROOT / "platforms")) with_logo = [key for key, entry in registry.items() if entry.get("logo")] diff --git a/tests/test_site_components.py b/tests/test_site_components.py index ecbc7ea63..71f80f397 100644 --- a/tests/test_site_components.py +++ b/tests/test_site_components.py @@ -32,7 +32,7 @@ import zlib import html import sys -from common import list_release_pack_platforms +from model.registry import list_release_pack_platforms REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_site_cores.py b/tests/test_site_cores.py index f22a75477..3fcf5e14a 100644 --- a/tests/test_site_cores.py +++ b/tests/test_site_cores.py @@ -14,12 +14,10 @@ import unittest from pathlib import Path import generate_site -from common import ( - list_registered_platforms, - load_emulator_profiles, - load_platform_config, - resolve_platform_cores, -) +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 REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_site_emulators.py b/tests/test_site_emulators.py index ff5713eab..3295c06cb 100644 --- a/tests/test_site_emulators.py +++ b/tests/test_site_emulators.py @@ -55,7 +55,7 @@ def _profile(name: str) -> dict: member's required from its groups (DuckStation's ps-bios), which the raw YAML no longer writes on the files.""" if not _LOADED: - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles _LOADED.update(load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False)) return _LOADED[name] diff --git a/tests/test_site_entry.py b/tests/test_site_entry.py index 8d64da2c4..4811dbf4e 100644 --- a/tests/test_site_entry.py +++ b/tests/test_site_entry.py @@ -47,7 +47,8 @@ import generate_site import release_record import siteguides import sitemarkup -from common import load_platform_config, load_platform_registry +from model.platforms import load_platform_config +from model.registry import load_platform_registry from tests import sitepages REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py index 5ff9cc1f3..4b3ad1f09 100644 --- a/tests/test_site_exports.py +++ b/tests/test_site_exports.py @@ -678,7 +678,7 @@ class AHashFindsEveryPageThatNamesIt(unittest.TestCase): import json as _json import generate_site - from common import load_platform_config + from model.platforms import load_platform_config from cross_reference import FileConsumers from core.ziptools import build_zip_contents_index diff --git a/tests/test_site_funnel.py b/tests/test_site_funnel.py index 4002fb458..be70b8dda 100644 --- a/tests/test_site_funnel.py +++ b/tests/test_site_funnel.py @@ -17,7 +17,8 @@ from pathlib import Path import generate_site from tests import sitepages -from common import list_registered_platforms, load_platform_config, load_platform_registry +from model.registry import list_registered_platforms, load_platform_registry +from model.platforms import load_platform_config from siteguides import DEVICE_GROUPS, GROUP_ANCHORS, GUIDES REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_site_handheld.py b/tests/test_site_handheld.py index 970f8c6fb..772844125 100644 --- a/tests/test_site_handheld.py +++ b/tests/test_site_handheld.py @@ -21,7 +21,7 @@ from pathlib import Path from unittest import mock import build_port -import common +from model.registry import list_registered_platforms import sitehandheld REPO_ROOT = Path(__file__).resolve().parents[1] @@ -96,7 +96,7 @@ class TheSiteServesTheLaunchers(unittest.TestCase): class WhereEachSystemFindsItsFile(unittest.TestCase): def test_each_platform_page_is_a_registered_platform(self): - registered = set(common.list_registered_platforms(PLATFORMS)) + registered = set(list_registered_platforms(PLATFORMS)) self.assertLessEqual(set(sitehandheld.PLATFORM_OF.values()), registered) self.assertNotIn(sitehandheld.GROUP_PAGE, registered) diff --git a/tests/test_site_images.py b/tests/test_site_images.py index bb137f000..ab580b92e 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -103,7 +103,9 @@ class DiagramsMatchTheData(unittest.TestCase): self.assertIn(display, text) def test_each_example_platform_runs_its_emulator(self): - from common import load_emulator_profiles, load_platform_config, resolve_platform_cores + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from resolve.cores import resolve_platform_cores profiles = load_emulator_profiles(str(ROOT / "emulators"), skip_aliases=False) for platform, emulator in sitediagrams.CHAIN_EXAMPLES: diff --git a/tests/test_site_integration.py b/tests/test_site_integration.py index 86ffefe94..372e18efd 100644 --- a/tests/test_site_integration.py +++ b/tests/test_site_integration.py @@ -118,7 +118,7 @@ class NodeCompileCache(unittest.TestCase): class SourcePathsFreshness(unittest.TestCase): def test_the_committed_record_is_current(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) finding = check_freshness.check_source_paths(profiles) diff --git a/tests/test_site_nav.py b/tests/test_site_nav.py index 63c10aae8..fe64815c0 100644 --- a/tests/test_site_nav.py +++ b/tests/test_site_nav.py @@ -35,11 +35,8 @@ from html import unescape import generate_site import sitestarlight -from common import ( - list_registered_platforms, - load_platform_config, - load_platform_registry, -) +from model.registry import list_registered_platforms, load_platform_registry +from model.platforms import load_platform_config from siteguides import DEVICE_GROUPS @@ -169,7 +166,7 @@ class EmulatorsOneLevelDeep(unittest.TestCase): def test_every_initial_has_its_section_on_the_index(self): """A letter in the sidebar lands on the section of that letter.""" - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) anchors = _index_anchors(generate_site.generate_emulators_index(profiles)) @@ -179,7 +176,7 @@ class EmulatorsOneLevelDeep(unittest.TestCase): self.assertIn(sitestarlight.toc_slug(label), anchors) def test_every_initial_holds_pages(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles nav = generate_site._emulator_nav(load_emulator_profiles(str(REPO_ROOT / "emulators"))) for group in nav[1:]: diff --git a/tests/test_site_platform_density.py b/tests/test_site_platform_density.py index e3723b1c9..b0d5da100 100644 --- a/tests/test_site_platform_density.py +++ b/tests/test_site_platform_density.py @@ -186,7 +186,7 @@ class NothingIsLost(unittest.TestCase): @classmethod def setUpClass(cls) -> None: - from common import load_database + from model.database import load_database from generate_readme import compute_coverage db = load_database(str(REPO_ROOT / "database.json")) @@ -249,7 +249,7 @@ _SITE = REPO_ROOT / "website" / "dist" / "platforms" @unittest.skipUnless(_SITE.is_dir(), "website/dist not built") class VisibleWordsStayUnderTheirCeiling(unittest.TestCase): def test_platform_pages(self): - from common import list_registered_platforms + from model.registry import list_registered_platforms mains = set(list_registered_platforms(str(REPO_ROOT / "platforms"))) for page in sorted(_SITE.glob("*/index.html")): diff --git a/tests/test_site_reference.py b/tests/test_site_reference.py index 73faca5ab..af236adf2 100644 --- a/tests/test_site_reference.py +++ b/tests/test_site_reference.py @@ -54,12 +54,9 @@ import urllib.error import generate_site import sitewanted import siterender -from common import ( - list_registered_platforms, - load_emulator_profiles, - load_platform_config, - list_release_pack_platforms, -) +from model.registry import list_registered_platforms, list_release_pack_platforms +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config from resolve.reconcile import HASH_FIELDS, _hash_values from resolve.categories import EntryCategories from sitesources import launcher_ref_markdown, list_source @@ -609,7 +606,8 @@ class TheContractsValidate(unittest.TestCase): except ImportError: self.skipTest("jsonschema is a tooling dependency") - from common import list_registered_platforms, load_platform_config + from model.registry import list_registered_platforms + from model.platforms import load_platform_config schema = json.loads((REPO_ROOT / "schemas" / "platform.schema.json").read_text()) validator = Draft202012Validator(schema) @@ -915,7 +913,7 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase): tree of its repository holds.""" if not sitesources.TREE_CACHE.is_dir(): raise unittest.SkipTest("no cached tree listings") - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles link = re.compile(r"\(https://github\.com/([^/]+/[^/]+)/blob/([0-9a-f]{40})/([^#)]+)") checked, wrong = 0, [] diff --git a/tests/test_site_render.py b/tests/test_site_render.py index c16a5c0f7..8df608ce9 100644 --- a/tests/test_site_render.py +++ b/tests/test_site_render.py @@ -107,7 +107,8 @@ class BundledFilesAreNotToSource(unittest.TestCase): """cdbios.bin, read by standalone BlastEm only and never on RetroBat, was badged retroarch, lakka and retrobat.""" import generate_site - from common import load_platform_config, resolve_platform_cores + from model.platforms import load_platform_config + from resolve.cores import resolve_platform_cores root = Path(__file__).resolve().parents[1] profile = yaml.safe_load((root / "emulators" / "blastem.yml").read_text(encoding="utf-8")) @@ -198,7 +199,9 @@ class DirectoryMembersNameTheirEmulator(unittest.TestCase): @classmethod def setUpClass(cls) -> None: - from common import build_zip_contents_index, load_database, load_emulator_profiles + from core.ziptools import build_zip_contents_index + from model.database import load_database + from model.profiles import load_emulator_profiles from cross_reference import FileConsumers cls.db = load_database(str(REPO_ROOT / "database.json")) @@ -504,7 +507,8 @@ class AMemberIsReadInItsArchive(unittest.TestCase): import json import generate_site as gs - from common import archive_entry, resolve_local_file + from resolve.archives import archive_entry + from resolve.localfile import resolve_local_file from cross_reference import FileConsumers db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8")) diff --git a/tests/test_site_search.py b/tests/test_site_search.py index 7662fbe19..6161cf024 100644 --- a/tests/test_site_search.py +++ b/tests/test_site_search.py @@ -34,7 +34,8 @@ import generate_site as gs import sitestarlight import validate_site import generate_site -from common import list_registered_platforms, load_emulator_profiles +from model.registry import list_registered_platforms +from model.profiles import load_emulator_profiles from tests.test_site_nav import ANCHORS, _nav, _present REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_site_system_links.py b/tests/test_site_system_links.py index 4e2c195c7..e60c36367 100644 --- a/tests/test_site_system_links.py +++ b/tests/test_site_system_links.py @@ -40,7 +40,8 @@ class LinksFollowContent(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) - from common import load_database, load_platform_config + from model.database import load_database + from model.platforms import load_platform_config db = load_database("database.json") config = load_platform_config("misterfpga") @@ -214,7 +215,8 @@ class ACopyFiledByEmulatorDoesNotMoveAMachine(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) - from common import load_database, load_emulator_profiles + from model.database import load_database + from model.profiles import load_emulator_profiles db = load_database("database.json") manufacturers = gs._group_by_manufacturer(db) @@ -279,9 +281,10 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase): import siterender import sitestarlight - from common import ( - list_registered_platforms, load_database, load_emulator_profiles, load_platform_config, - ) + 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 db = load_database(str(REPO_ROOT / "database.json")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) diff --git a/tests/test_site_system_names.py b/tests/test_site_system_names.py index 823767a0f..c6120de57 100644 --- a/tests/test_site_system_names.py +++ b/tests/test_site_system_names.py @@ -17,11 +17,9 @@ import unittest from pathlib import Path import siterender -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 from generate_site import _group_by_manufacturer REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_site_system_sections.py b/tests/test_site_system_sections.py index acb6e623e..06aa6afca 100644 --- a/tests/test_site_system_sections.py +++ b/tests/test_site_system_sections.py @@ -59,7 +59,7 @@ UNLINKED: dict[str, str] = { def _accepts(fe: dict, local: str | None, status: str) -> bool: """A resolution that proves the entry's content or its full path.""" - from common import resolution_is_hash_exact + from resolve.localfile import resolution_is_hash_exact if not local: return False @@ -111,7 +111,7 @@ def _held_sections( ids: Iterable[str], entries: dict[str, list[dict]], board_sections: dict, db: dict ) -> dict[str, set[tuple[str, str]]]: """Id -> the (manufacturer, console) sections holding its files.""" - from common import resolve_local_file + from resolve.localfile import resolve_local_file # Where each content has a card. places: dict[str, set[tuple[str, str, str]]] = {} @@ -147,11 +147,9 @@ class SystemLinks(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) try: - 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 from generate_site import _group_by_manufacturer, arcade_board_sections with open("database.json", encoding="utf-8") as handle: @@ -323,7 +321,7 @@ class AnEntryListingSystemsIsFiledUnderEach(unittest.TestCase): def test_the_site_reads_the_common_rule(self): import generate_site as gs - from common import entry_system_ids + from model.profiles import entry_system_ids entry = {"name": "ym2608.zip", "systems": ["arcade", "pc80"]} self.assertEqual(gs._entry_systems("mame", entry), ["arcade", "pc80"]) diff --git a/tests/test_site_wanted.py b/tests/test_site_wanted.py index a5aea0577..678b50e5c 100644 --- a/tests/test_site_wanted.py +++ b/tests/test_site_wanted.py @@ -28,7 +28,7 @@ import generate_site import sitewanted import validate_pr import yaml -from common import load_database +from model.database import load_database from tests.test_site_pronouns import pronouns REPO_ROOT = Path(__file__).resolve().parent.parent @@ -653,7 +653,7 @@ class ThePublishedList(unittest.TestCase): def test_no_game_data_and_nothing_the_emulator_installs(self): """Each emulator a row names declares that file as firmware it does not install itself: pak0.pk3, game data for every profile, is gone.""" - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from resolve.validation import installed_with_emulator profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) diff --git a/tests/test_site_wiki.py b/tests/test_site_wiki.py index 66ed87d1f..34f70bfb9 100644 --- a/tests/test_site_wiki.py +++ b/tests/test_site_wiki.py @@ -246,7 +246,7 @@ class SetupCount(unittest.TestCase): """C2: the home page said 15 more, the diagram 14 more, from two counts.""" def test_one_count(self): - from common import list_registered_platforms + from model.registry import list_registered_platforms self.assertEqual(len(sitediagrams.setups()), len(list_registered_platforms(str(REPO_ROOT / "platforms")))) diff --git a/tests/test_slots.py b/tests/test_slots.py index 686726316..98943a7b3 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -779,13 +779,11 @@ class ManifestFollowsTheArbitration(unittest.TestCase): os.chdir(repo) self.addCleanup(os.chdir, previous) import generate_pack - from common import ( - build_zip_contents_index, - load_data_dir_registry, - load_database, - load_emulator_profiles, - load_platform_config, - ) + from core.ziptools import build_zip_contents_index + from model.registry import load_data_dir_registry + from model.database import load_database + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config db = load_database(str(repo / "database.json")) config = load_platform_config("retroarch", str(repo / "platforms")) diff --git a/tests/test_slots_shipped_file.py b/tests/test_slots_shipped_file.py index 06ffc3751..b328d9d79 100644 --- a/tests/test_slots_shipped_file.py +++ b/tests/test_slots_shipped_file.py @@ -19,7 +19,8 @@ import os import unittest from pathlib import Path -from common import load_database, load_platform_config +from model.database import load_database +from model.platforms import load_platform_config import slots REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_source_ref_targets.py b/tests/test_source_ref_targets.py index cb10d5f78..e2d33f783 100644 --- a/tests/test_source_ref_targets.py +++ b/tests/test_source_ref_targets.py @@ -20,7 +20,7 @@ from unittest import mock import sitesources import upstream -from common import load_emulator_profiles +from model.profiles import load_emulator_profiles from sourceref import ref_role, source_ref_values, split_source_ref REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_split_extras.py b/tests/test_split_extras.py index fbbf5f840..ad7a26c5c 100644 --- a/tests/test_split_extras.py +++ b/tests/test_split_extras.py @@ -17,7 +17,9 @@ from pathlib import Path import yaml -from common import build_zip_contents_index, compute_hashes, load_emulator_profiles +from core.ziptools import build_zip_contents_index +from core.hashing import compute_hashes +from model.profiles import load_emulator_profiles from generate_pack import PackRecord, generate_pack, generate_split_packs REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_split_names.py b/tests/test_split_names.py index 7550a7156..81dd24e0a 100644 --- a/tests/test_split_names.py +++ b/tests/test_split_names.py @@ -19,8 +19,9 @@ from pathlib import Path import yaml -import common -from common import build_zip_contents_index, compute_hashes +from model.platforms import _platform_config_cache +from core.ziptools import build_zip_contents_index +from core.hashing import compute_hashes from generate_pack import generate_split_packs @@ -72,7 +73,7 @@ class SplitPartNames(unittest.TestCase): }, } (self.platforms / "longplat.yml").write_text(yaml.dump(config)) - common._platform_config_cache.clear() + _platform_config_cache.clear() def _split(self, group_by: str) -> list[str]: return generate_split_packs( diff --git a/tests/test_standalone_links.py b/tests/test_standalone_links.py index 43c054cc2..d49cade55 100644 --- a/tests/test_standalone_links.py +++ b/tests/test_standalone_links.py @@ -18,16 +18,15 @@ import textwrap import unittest from pathlib import Path -from common import ( +from resolve.layout import ( entry_launch_systems, - load_emulator_profiles, - load_platform_config, - platform_layouts, standalone_bindings_for, standalone_destination, - standalone_set, system_file_index, ) +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from resolve.standalone import platform_layouts, standalone_set from resolve.launchers import ( SEARCHED_FILES, bound_path, @@ -728,7 +727,7 @@ class AmiberryBuildEachPlatformShips(unittest.TestCase): cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) def resolved(self, platform: str) -> set[str]: - from common import resolve_platform_cores + from resolve.cores import resolve_platform_cores cfg = load_platform_config(platform, str(REPO_ROOT / "platforms")) return {p for p in resolve_platform_cores(cfg, self.profiles) if p.startswith("amiberry")} @@ -739,7 +738,7 @@ class AmiberryBuildEachPlatformShips(unittest.TestCase): self.assertEqual(self.resolved(platform), own) def test_no_standalone_amiberry_is_the_buildbot_revision(self) -> None: - from common import list_registered_platforms + from model.registry import list_registered_platforms for platform in list_registered_platforms(str(REPO_ROOT / "platforms")): cfg = load_platform_config(platform, str(REPO_ROOT / "platforms")) @@ -750,7 +749,8 @@ class AmiberryBuildEachPlatformShips(unittest.TestCase): self.assertEqual([standalone for _view, standalone in layouts], [False]) def test_the_buildbot_core_runs_where_retroarch_installs_it(self) -> None: - from common import load_target_config, resolve_platform_cores + from model.targets import load_target_config + from resolve.cores import resolve_platform_cores for platform in ("retroarch", "lakka", "batocera"): with self.subTest(platform=platform): diff --git a/tests/test_standalone_mode.py b/tests/test_standalone_mode.py index db8afc062..7cb48baad 100644 --- a/tests/test_standalone_mode.py +++ b/tests/test_standalone_mode.py @@ -93,7 +93,7 @@ class CrossReferenceReadsTheBuildThePlatformRuns(unittest.TestCase): def test_a_platform_running_both_builds(self): # The dual layout keyed seen files by (path, slot) and then looked # the pair up in the slot table: KeyError on Batocera's dolphin. - from common import DUAL_MODE_PREFIX + from resolve.layout import DUAL_MODE_PREFIX self.assertEqual( self._gaps({"dual", DUAL_MODE_PREFIX + "dual"}), diff --git a/tests/test_system_ids.py b/tests/test_system_ids.py index add96cec6..9570e2a3c 100644 --- a/tests/test_system_ids.py +++ b/tests/test_system_ids.py @@ -14,7 +14,8 @@ import tests import unittest from pathlib import Path -from common import SYSTEM_ALIASES, _norm_system_id, load_emulator_profiles +from model.systems import SYSTEM_ALIASES, _norm_system_id +from model.profiles import load_emulator_profiles from packextras import _names_content, _slug_for REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index ce0a7bc59..c524bc54f 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -20,7 +20,11 @@ import tempfile import unittest from pathlib import Path -import common +from core.cli import suggest_names +from model.cliargs import list_system_ids +from model.database import load_database +from model.platforms import load_platform_config +from model.profiles import _emulator_profiles_cache, load_emulator_profiles, profiles_for_systems import generate_pack as builder from tests.scratchtree import scratch_checkout, snapshot @@ -29,9 +33,9 @@ REPO_ROOT = Path(__file__).resolve().parent.parent class SpellingsAgree(unittest.TestCase): def test_both_spellings_select_the_same_profiles(self): - profiles = common.load_emulator_profiles(str(REPO_ROOT / "emulators")) - dashed = common.profiles_for_systems(profiles, ["atari-2600"]) - underscored = common.profiles_for_systems(profiles, ["atari_2600"]) + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) + dashed = profiles_for_systems(profiles, ["atari-2600"]) + underscored = profiles_for_systems(profiles, ["atari_2600"]) self.assertEqual(dashed, underscored) self.assertIn("stella2014", dashed) self.assertIn("gopher2600", dashed) @@ -50,13 +54,13 @@ class TheListingCountsLikeTheSelection(unittest.TestCase): out = io.StringIO() with contextlib.redirect_stdout(out): - common.list_system_ids(str(REPO_ROOT / "emulators")) + list_system_ids(str(REPO_ROOT / "emulators")) lines = {line.split()[0]: line for line in out.getvalue().splitlines() if line.strip()} - profiles = common.load_emulator_profiles(str(REPO_ROOT / "emulators")) + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) for spellings in (("3do", "panasonic-3do"), ("atari-2600", "atari_2600")): listed = [s for s in spellings if s in lines] self.assertEqual(len(listed), 1, f"{spellings}: one line per system") - count = len(common.profiles_for_systems(profiles, [spellings[0]])) + count = len(profiles_for_systems(profiles, [spellings[0]])) self.assertIn(f"({count} emulator", lines[listed[0]]) @@ -67,8 +71,8 @@ class StandaloneNeedsAStandaloneBuild(unittest.TestCase): Path(tmp, "emulators", "handy.yml").write_text( "emulator: Handy\ntype: libretro\nsystems: [atari-lynx]\nfiles:\n - name: lynxboot.img\n" ) - common._emulator_profiles_cache.clear() - self.addCleanup(common._emulator_profiles_cache.clear) + _emulator_profiles_cache.clear() + self.addCleanup(_emulator_profiles_cache.clear) db = {"files": {}, "indexes": {"by_md5": {}, "by_crc32": {}, "by_name": {}}} result = builder.generate_md5_pack( [("md5", "d8f1206299c48946e6ec5ef96d014eaa")], db, tmp, tmp, @@ -134,7 +138,7 @@ class AMistypedPlatformIsNamed(unittest.TestCase): def test_the_names_the_site_prints_are_accepted(self): """`--platform RetroArch` and `--platform "MiSTer FPGA"` were refused by verify and generate_pack while install.py took them.""" - from common import platform_arg + from model.cliargs import platform_arg previous = os.getcwd() os.chdir(REPO_ROOT) @@ -474,7 +478,7 @@ class VerifyReportsTheRequiredOnlyPack(unittest.TestCase): from verify import verify_emulator - db = common.load_database("database.json") + db = load_database("database.json") for name in ("beetle_psx", "dolphin", "fbneo", "geolith", "mame"): with self.subTest(emulator=name): record = builder.PackRecord() @@ -559,13 +563,13 @@ class ATypoGetsTheNearestNames(unittest.TestCase): sony-playstaton was answered with 3do to apple-iie.""" def test_suggestions_follow_the_typed_name(self): - hint = common.suggest_names(["sony-playstaton"], + hint = suggest_names(["sony-playstaton"], ["3do", "apple-ii", "sony-playstation"], "--list-systems") self.assertEqual(hint, "Close matches: sony-playstation. --list-systems lists all 3.") - self.assertEqual(common.suggest_names(["zzz"], ["3do"], "--list-systems"), + self.assertEqual(suggest_names(["zzz"], ["3do"], "--list-systems"), "Known: 3do.") many = [f"system-{i}" for i in range(40)] - self.assertEqual(common.suggest_names(["zzz"], many, "--list-systems"), + self.assertEqual(suggest_names(["zzz"], many, "--list-systems"), "--list-systems lists all 40.") @@ -581,7 +585,7 @@ class EmulatorVerifyReadsNoArchiveItDoesNotNeed(unittest.TestCase): if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not generated") - db = common.load_database(str(REPO_ROOT / "database.json")) + db = load_database(str(REPO_ROOT / "database.json")) with mock.patch.object(verify, "build_zip_contents_index", side_effect=AssertionError("index built")): result = verify.verify_emulator(["handy"], str(REPO_ROOT / "emulators"), db) @@ -598,12 +602,12 @@ class CoverageWithoutProfilesMatchesTheCli(unittest.TestCase): if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not generated") - db = common.load_database(str(REPO_ROOT / "database.json")) - config = common.load_platform_config("retroarch", str(REPO_ROOT / "platforms")) + db = load_database(str(REPO_ROOT / "database.json")) + config = load_platform_config("retroarch", str(REPO_ROOT / "platforms")) emulators = str(REPO_ROOT / "emulators") bare = verify.verify_platform(config, db, emulators) full = verify.verify_platform(config, db, emulators, - common.load_emulator_profiles(emulators)) + load_emulator_profiles(emulators)) def discrepancies(result): return sorted(d["name"] for d in result["details"] if d.get("discrepancy")) @@ -625,7 +629,7 @@ class ASystemPackHoldsThatSystem(unittest.TestCase): import yaml from verify import verify_system - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) @@ -679,7 +683,7 @@ class ATreeHoldsAPathForAnotherProfile(unittest.TestCase): import yaml from verify import verify_emulator - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) diff --git a/tests/test_target_names.py b/tests/test_target_names.py index 714650cf7..edf5dbeb6 100644 --- a/tests/test_target_names.py +++ b/tests/test_target_names.py @@ -15,7 +15,7 @@ import tempfile import unittest from pathlib import Path -from common import canonical_target_name +from model.targets import canonical_target_name REPO_ROOT = Path(__file__).resolve().parent.parent @@ -29,13 +29,10 @@ class EveryBuildbotCoreIsNamed(unittest.TestCase): def test_retroarch_names_every_buildbot_core(self): import yaml - from common import ( - load_emulator_profiles, - load_platform_config, - load_target_config, - resolve_platform_cores, - upstream_profile_index, - ) + from model.profiles import load_emulator_profiles, upstream_profile_index + from model.platforms import load_platform_config + from model.targets import load_target_config + from resolve.cores import resolve_platform_cores platforms = str(REPO_ROOT / "platforms") profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -144,7 +141,7 @@ class OneTruthModelPerTarget(unittest.TestCase): rebuilt the same slug by hand to find it.""" def test_aliases_share_a_directory(self): - from common import truth_target_dir + from model.targets import truth_target_dir platforms = str(REPO_ROOT / "platforms") dirs = { @@ -173,7 +170,7 @@ class TheListingCountsWhatTheFilterUses(unittest.TestCase): filters on 187 once _overrides.yml removes machine variants and launchers.""" def test_every_listed_count_is_the_filtered_set(self): - from common import list_available_targets, load_target_config + from model.targets import list_available_targets, load_target_config platforms = str(REPO_ROOT / "platforms") checked = 0 @@ -198,12 +195,10 @@ class ASingleTargetFiltersNothing(unittest.TestCase): import yaml - from common import ( - load_emulator_profiles, - load_platform_config, - load_target_config, - resolve_platform_cores, - ) + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from model.targets import load_target_config + from resolve.cores import resolve_platform_cores platforms = str(REPO_ROOT / "platforms") profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 275d16e75..93b7a9486 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -271,7 +271,7 @@ class CoreDownloaderReach(unittest.TestCase): downloader_disabled("", {"a/retroarch.cfg": 'core_updater_buildbot_cores_url = ""\n'}) def test_a_board_that_downloads_gets_the_buildbot_list(self): - from common import load_target_config + from model.targets import load_target_config root = str(REPO_ROOT / "platforms") x86 = set(load_target_config("retroarch", "linux-x86_64", root) or ()) @@ -284,7 +284,7 @@ class CoreDownloaderReach(unittest.TestCase): def test_the_platform_names_what_its_boards_install(self): import yaml - from common import load_target_config + from model.targets import load_target_config root = str(REPO_ROOT / "platforms") for platform in ("batocera", "knulli"): @@ -306,7 +306,9 @@ class CoreDownloaderReach(unittest.TestCase): """Batocera runs amiberry standalone, and its x86_64 boards fetch amiberry_libretro: removing every name the image builds lost the libretro core to the name it shares with the standalone package.""" - from common import DUAL_MODE_PREFIX, resolve_platform_cores, standalone_set + from resolve.layout import DUAL_MODE_PREFIX + from resolve.cores import resolve_platform_cores + from resolve.standalone import standalone_set from scraper.batocera_scraper import installable_cores from scraper.targets.batocera_targets_scraper import BuildSelection @@ -340,7 +342,8 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase): @classmethod def setUpClass(cls): - from common import load_emulator_profiles, load_platform_config + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) cls.config = load_platform_config("batocera", str(REPO_ROOT / "platforms")) @@ -349,7 +352,8 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase): """Batocera lists higan_sfc_balanced and nside_sfc_balanced, and the buildbot offers the second: reading the first alone dropped the core from x86_64.""" - from common import load_target_config, resolve_platform_cores + from model.targets import load_target_config + from resolve.cores import resolve_platform_cores root = str(REPO_ROOT / "platforms") x86 = load_target_config("batocera", "x86_64", root) diff --git a/tests/test_target_systems.py b/tests/test_target_systems.py index 105688938..fc36ac5d5 100644 --- a/tests/test_target_systems.py +++ b/tests/test_target_systems.py @@ -13,7 +13,7 @@ import tests import unittest -from common import filter_systems_by_target +from resolve.cores import filter_systems_by_target PROFILES = { "ep128emu_core": { diff --git a/tests/test_target_verify.py b/tests/test_target_verify.py index 5897a91de..5ca9010fb 100644 --- a/tests/test_target_verify.py +++ b/tests/test_target_verify.py @@ -20,7 +20,7 @@ import tempfile import unittest from pathlib import Path -from common import build_target_cores_cache +from model.targets import build_target_cores_cache from generate_pack import _target_cores_for REPO_ROOT = Path(__file__).resolve().parent.parent @@ -94,9 +94,9 @@ class ASystemTheTargetDropsIsNamedAsSuch(unittest.TestCase): PLATFORMS = str(REPO_ROOT / "platforms") def test_both_tools_read_one_scope(self): - from common import ( - load_emulator_profiles, load_platform_config, platform_scope_systems, - ) + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from resolve.cores import platform_scope_systems config = load_platform_config("retroarch", self.PLATFORMS) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -106,7 +106,7 @@ class ASystemTheTargetDropsIsNamedAsSuch(unittest.TestCase): self.assertEqual(list(platform_scope_systems(config, profiles, None, wanted)), wanted) def test_the_message_names_the_target(self): - from common import system_scope_error + from resolve.cores import system_scope_error config = {"systems": {"sony-playstation-2": {}, "sony-playstation": {}}} self.assertEqual( @@ -137,7 +137,7 @@ class ASplitBuildsOnlyTheTargetsSystems(unittest.TestCase): from unittest import mock import generate_pack - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles platforms = str(REPO_ROOT / "platforms") profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -172,7 +172,7 @@ class APlatformWithoutTheSystemIsOutOfScope(unittest.TestCase): import argparse import generate_pack - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles values = {"platforms_dir": str(REPO_ROOT / "platforms"), "target": None, "all": True} diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index b68fd2ab1..f649ca409 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -15,7 +15,11 @@ import unittest from pathlib import Path from unittest import mock -import common +from core.cli import SourceUnreadable +from core.github import github_token, _gh_cli_token +from model.profiles import select_emulator_profiles, ProfileSelectionError +from model.registry import list_registered_platforms +from model.targets import load_target_config, build_target_cores_cache import diff_truth import pipeline from resolve import truth @@ -37,17 +41,17 @@ class ABuildbotNameSelectsItsProfile(unittest.TestCase): } def test_a_core_name_serves_the_profile(self): - selected = common.select_emulator_profiles(["pcfx"], self.PROFILES) + selected = select_emulator_profiles(["pcfx"], self.PROFILES) self.assertEqual([name for name, _profile in selected], ["beetle_pcfx"]) def test_a_name_two_profiles_claim_names_both(self): - with self.assertRaises(common.ProfileSelectionError) as caught: - common.select_emulator_profiles(["shared"], self.PROFILES) + with self.assertRaises(ProfileSelectionError) as caught: + select_emulator_profiles(["shared"], self.PROFILES) self.assertIn("a, b", str(caught.exception)) def test_an_unknown_name_still_gets_a_hint(self): - with self.assertRaises(common.ProfileSelectionError) as caught: - common.select_emulator_profiles(["pcsx3"], self.PROFILES) + with self.assertRaises(ProfileSelectionError) as caught: + select_emulator_profiles(["pcsx3"], self.PROFILES) self.assertIn("Close match", str(caught.exception)) def test_cross_reference_reports_the_resolved_profile(self): @@ -79,7 +83,7 @@ class AMistypedTargetGetsTheClosestName(unittest.TestCase): "p:\n targets:\n nintendo-switch:\n aliases: [switch]\n" ) with self.assertRaises(ValueError) as caught: - common.load_target_config("p", "swich", tmp) + load_target_config("p", "swich", tmp) message = str(caught.exception) self.assertIn("Close matches: switch.", message) self.assertIn("lists all 31", message) @@ -146,7 +150,7 @@ class ADamagedProfileNamesItself(unittest.TestCase): def test_a_damaged_file_is_not_an_absent_one(self): """Ten callers skip a platform whose file is absent (except FileNotFoundError): a damaged one has to stop them instead.""" - self.assertFalse(issubclass(common.SourceUnreadable, FileNotFoundError)) + self.assertFalse(issubclass(SourceUnreadable, FileNotFoundError)) class TheVerdictClosesARedirectedReport(unittest.TestCase): @@ -158,7 +162,7 @@ class TheVerdictClosesARedirectedReport(unittest.TestCase): program = ( "import sys\n" "sys.path.insert(0, 'scripts')\n" - "from common import run_cli\n" + "from core.cli import run_cli\n" "def main():\n" " print('report')\n" " print('ERROR: verdict', file=sys.stderr)\n" @@ -238,10 +242,10 @@ class AMistypedTargetAcrossAllPlatforms(unittest.TestCase): INFO lines, two of which held the suggestion.""" def test_the_refusal_suggests_and_names_the_platforms(self): - platforms = common.list_registered_platforms(str(REPO_ROOT / "platforms")) + platforms = list_registered_platforms(str(REPO_ROOT / "platforms")) out = io.StringIO() with contextlib.redirect_stdout(out), self.assertRaises(ValueError) as caught: - common.build_target_cores_cache( + build_target_cores_cache( platforms, "swich", str(REPO_ROOT / "platforms"), is_all=True ) self.assertIn("Close matches: switch (", str(caught.exception)) @@ -544,7 +548,7 @@ class APlatformWithoutTargetsSaysSo(unittest.TestCase): for name in ("retroarch", "batocera", "_overrides"): (Path(tmp) / "targets" / f"{name}.yml").write_text("targets: {}\n") with self.assertRaises(FileNotFoundError) as caught: - common.load_target_config("misterfpga", "switch", tmp) + load_target_config("misterfpga", "switch", tmp) self.assertEqual( str(caught.exception), "misterfpga has no hardware targets: drop --target " @@ -806,7 +810,7 @@ class NoScriptReadsTheTokenOnItsOwn(unittest.TestCase): READS = ('environ.get("GITHUB_TOKEN"', "environ['GITHUB_TOKEN']", 'environ["GITHUB_TOKEN"]', 'environ.get("GH_TOKEN"') - OWNERS = {"scripts/common.py", "scripts/download.py"} + OWNERS = {"scripts/core/github.py", "scripts/download.py"} def test_every_reader_asks_github_token(self): for path in sorted((REPO_ROOT / "scripts").rglob("*.py")): @@ -825,8 +829,8 @@ class TheGitHubTokenComesFromGh(unittest.TestCase): scrapers went anonymous for a maintainer logged in to gh.""" def setUp(self): - common._gh_cli_token.cache_clear() - self.addCleanup(common._gh_cli_token.cache_clear) + _gh_cli_token.cache_clear() + self.addCleanup(_gh_cli_token.cache_clear) env = {k: v for k, v in os.environ.items() if k not in ("GITHUB_TOKEN", "GH_TOKEN", "RETROBIOS_OFFLINE")} patcher = mock.patch.dict(os.environ, env, clear=True) @@ -842,27 +846,27 @@ class TheGitHubTokenComesFromGh(unittest.TestCase): def test_gh_answers_when_the_variable_is_unset(self): with self._gh(): - self.assertEqual(common.github_token(), "gho_fromgh") + self.assertEqual(github_token(), "gho_fromgh") # Subprocesses of the run inherit it. self.assertEqual(os.environ.get("GITHUB_TOKEN"), "gho_fromgh") def test_the_variable_wins(self): os.environ["GITHUB_TOKEN"] = "set" with self._gh() as run: - self.assertEqual(common.github_token(), "set") + self.assertEqual(github_token(), "set") run.assert_not_called() def test_no_gh_means_anonymous(self): with mock.patch("subprocess.run", side_effect=FileNotFoundError("gh")): - self.assertEqual(common.github_token(), "") + self.assertEqual(github_token(), "") with self._gh("", 1): - common._gh_cli_token.cache_clear() - self.assertEqual(common.github_token(), "") + _gh_cli_token.cache_clear() + self.assertEqual(github_token(), "") def test_offline_runs_never_ask(self): os.environ["RETROBIOS_OFFLINE"] = "1" with self._gh() as run: - self.assertEqual(common.github_token(), "") + self.assertEqual(github_token(), "") run.assert_not_called() def test_every_api_caller_reads_it(self): @@ -927,7 +931,7 @@ class CitedCommandsRunWhenPasted(unittest.TestCase): targets.mkdir() (targets / "p.yml").write_text("targets:\n switch:\n cores: [a]\n") with self.assertRaises(ValueError) as caught: - common.load_target_config("p", "swich", tmp) + load_target_config("p", "swich", tmp) self.assertIn("python scripts/verify.py --platform p --list-targets", str(caught.exception)) diff --git a/tests/test_twin_declaration_status.py b/tests/test_twin_declaration_status.py index 6f0c2c8d2..96a564a44 100644 --- a/tests/test_twin_declaration_status.py +++ b/tests/test_twin_declaration_status.py @@ -21,7 +21,7 @@ from pathlib import Path import yaml -import common +from model.platforms import _platform_config_cache import generate_db import generate_pack as builder from verify import Status, verify_platform @@ -49,7 +49,7 @@ class TwinDeclarationStatus(unittest.TestCase): Path("platforms/_registry.yml").write_text( yaml.dump({"platforms": {"twin": {"config": "twin.yml"}}}) ) - self.addCleanup(common._platform_config_cache.clear) + self.addCleanup(_platform_config_cache.clear) def tearDown(self): os.chdir(self._cwd) @@ -66,7 +66,7 @@ class TwinDeclarationStatus(unittest.TestCase): }, } Path("platforms/twin.yml").write_text(yaml.dump(config)) - common._platform_config_cache.clear() + _platform_config_cache.clear() return config def _check(self, config: dict) -> None: diff --git a/tests/test_twin_declarations.py b/tests/test_twin_declarations.py index ca1892bb0..e1cf6a916 100644 --- a/tests/test_twin_declarations.py +++ b/tests/test_twin_declarations.py @@ -17,7 +17,7 @@ import tempfile import unittest from pathlib import Path -import common +from model.profiles import _emulator_profiles_cache import generate_db from verify import verify_platform @@ -45,10 +45,10 @@ class TwinDeclarations(unittest.TestCase): self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} self.emulators = Path(self._tmp.name) / "emulators" self.emulators.mkdir() - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() def tearDown(self): - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() os.chdir(self._cwd) self._tmp.cleanup() diff --git a/tests/test_unplaced_extras.py b/tests/test_unplaced_extras.py index 7ec9848c2..b039b8c0b 100644 --- a/tests/test_unplaced_extras.py +++ b/tests/test_unplaced_extras.py @@ -18,7 +18,8 @@ from pathlib import Path import yaml -import common +from model.platforms import _platform_config_cache, load_platform_config +from model.profiles import load_emulator_profiles, _emulator_profiles_cache import generate_db import generate_pack as builder from packextras import platform_region_groups @@ -75,13 +76,13 @@ class SlugPlatform(unittest.TestCase): yaml.dump({"platforms": {"slugs": {"config": "slugs.yml"}}}) ) (self.emulators / "dosbox.yml").write_text(PROFILE) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - self.profiles = common.load_emulator_profiles("emulators") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + self.profiles = load_emulator_profiles("emulators") def tearDown(self): - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() os.chdir(self._cwd) self._tmp.cleanup() @@ -138,8 +139,8 @@ class RegionKeysForEveryClaimant(unittest.TestCase): f"emulator: {name}\ntype: libretro\nsystems: [sys]\ncores: [{name}]\n" f"files:\n - name: jp.bin\n region: [japan]\n{extra}" ) - common._emulator_profiles_cache.clear() - profiles = common.load_emulator_profiles("emulators") + _emulator_profiles_cache.clear() + profiles = load_emulator_profiles("emulators") config = {"platform": "P", "version": "2.1", "verification_mode": "existence", "cores": ["one", "two"], "systems": {"sys": {"files": []}}} _groups, extra_dests = platform_region_groups( @@ -197,12 +198,12 @@ class FlatFirmwareFolder(unittest.TestCase): yaml.dump({"platforms": {"flat": entry}}) ) Path("emulators/psx.yml").write_text(self.PROFILE) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() - profiles = common.load_emulator_profiles("emulators") + _platform_config_cache.clear() + _emulator_profiles_cache.clear() + profiles = load_emulator_profiles("emulators") if report: return verify_platform( - common.load_platform_config("flat", "platforms"), db, + load_platform_config("flat", "platforms"), db, "emulators", profiles, ) return builder.generate_manifest( @@ -210,8 +211,8 @@ class FlatFirmwareFolder(unittest.TestCase): emulators_dir="emulators", emu_profiles=profiles, offline=True, ) finally: - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() os.chdir(previous) def test_a_nested_file_is_omitted_with_its_reason(self): @@ -267,8 +268,8 @@ class UserProvidedIsNeverTakenFromTheCollection(unittest.TestCase): "emulator: Fake\ntype: libretro\nsystems: [psx]\ncores: [fake]\n" "files:\n - name: scph5501.bin\n storage: user_provided\n" ) - common._emulator_profiles_cache.clear() - self.addCleanup(common._emulator_profiles_cache.clear) + _emulator_profiles_cache.clear() + self.addCleanup(_emulator_profiles_cache.clear) result = verify_emulator(["fake"], "emulators", db) statuses = [d["status"] for d in result["details"] if d["name"] == "scph5501.bin"] self.assertEqual(statuses, [Status.MISSING]) @@ -298,9 +299,9 @@ class OnePathCountsOnce(unittest.TestCase): f"emulator: {core}\ntype: libretro\nsystems: [amiga]\ncores: [{core}]\n" f"files:\n - name: rom.key\n required: false\n{region}" ) - common._emulator_profiles_cache.clear() - self.addCleanup(common._emulator_profiles_cache.clear) - profiles = common.load_emulator_profiles("emulators") + _emulator_profiles_cache.clear() + self.addCleanup(_emulator_profiles_cache.clear) + profiles = load_emulator_profiles("emulators") config = {"platform": "P", "version": "2.1", "verification_mode": "existence", "cores": ["one", "two"], "systems": {"amiga": {"files": []}}} report = verify_platform(config, db, "emulators", profiles) diff --git a/tests/test_upstream_index.py b/tests/test_upstream_index.py index 2cd623fe5..cf15e2be2 100644 --- a/tests/test_upstream_index.py +++ b/tests/test_upstream_index.py @@ -14,11 +14,8 @@ import re import unittest from pathlib import Path -from common import ( - preferred_profile, - resolve_platform_cores, - upstream_profile_index, -) +from model.profiles import preferred_profile, upstream_profile_index +from resolve.cores import resolve_platform_cores REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_validated_choice.py b/tests/test_validated_choice.py index 4ea5049e5..973535351 100644 --- a/tests/test_validated_choice.py +++ b/tests/test_validated_choice.py @@ -153,7 +153,8 @@ class ManifestsServeWhatTheCoreAccepts(unittest.TestCase): def test_no_served_core_file_fails_its_check_beside_a_passing_variant(self): import json - from common import load_emulator_profiles, load_platform_config + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config from generate_pack import _platform_cores from resolve.validation import check_file_validation @@ -228,7 +229,7 @@ class DolphinForksJudgeTheirOwnDspTable(unittest.TestCase): FREE_V031 = REPO_ROOT / "bios" / "Nintendo" / "GameCube" / "Sys" / "GC" / "dsp_rom.bin" def test_each_fork_accepts_its_own_free_rom(self): - from common import load_emulator_profiles + from model.profiles import load_emulator_profiles from resolve.validation import check_file_validation if not self.FREE_V04.is_file() or not self.FREE_V031.is_file(): diff --git a/tests/test_verify_emulator_evidence.py b/tests/test_verify_emulator_evidence.py index 9ffd4b990..2b33db6d2 100644 --- a/tests/test_verify_emulator_evidence.py +++ b/tests/test_verify_emulator_evidence.py @@ -78,12 +78,12 @@ class HashMismatchIsNotCoverage(unittest.TestCase): self.rom = self.root / "shared.rom" self.rom.write_bytes(b"THE BYTES THE REPO ACTUALLY HOLDS") self.db = _db(self.rom, "shared.rom") - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() def tearDown(self): - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() self._tmp.cleanup() @@ -202,12 +202,12 @@ class ArchiveHashMismatchIsNotCoverage(unittest.TestCase): with zipfile.ZipFile(self.archive, "w") as zf: zf.writestr("inner.rom", b"THE MEMBER THE EMULATOR LOADS") self.db = _db(self.archive, "romset.zip") - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() def tearDown(self): - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() self._tmp.cleanup() @@ -303,12 +303,12 @@ class UnsourceableIsNotAGap(unittest.TestCase): self.db = {"files": {}, "indexes": { "by_name": {}, "by_md5": {}, "by_sha256": {}, "by_crc32": {}, "by_path_suffix": {}}} - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() def tearDown(self): - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() self._tmp.cleanup() @@ -363,13 +363,11 @@ class RepositoryWideEvidence(unittest.TestCase): """The real collection, so the fix is measured and not just asserted.""" def test_no_profile_entry_is_reported_ok_on_a_contradicted_hash(self): - from common import ( - build_zip_contents_index, - load_data_dir_registry, - load_database, - load_emulator_profiles, - resolve_local_file, - ) + from core.ziptools import build_zip_contents_index + from model.registry import load_data_dir_registry + from model.database import load_database + from model.profiles import load_emulator_profiles + from resolve.localfile import resolve_local_file db_path = REPO_ROOT / "database.json" if not db_path.is_file(): @@ -426,12 +424,12 @@ class StandaloneSlotsFollowThePack(unittest.TestCase): " path: bios/a.rom\n" " standalone_path: B/a.rom\n" ) - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() def tearDown(self): - from common import _emulator_profiles_cache + from model.profiles import _emulator_profiles_cache _emulator_profiles_cache.clear() self._tmp.cleanup() diff --git a/tests/test_verify_release_asset.py b/tests/test_verify_release_asset.py index 10dcc6282..d29bd85f8 100644 --- a/tests/test_verify_release_asset.py +++ b/tests/test_verify_release_asset.py @@ -23,7 +23,8 @@ from unittest import mock import yaml -import common +from model.platforms import _platform_config_cache +from model.profiles import _emulator_profiles_cache import generate_db import generate_pack as builder import packresolve @@ -63,8 +64,8 @@ class ReleaseAssetNotCached(unittest.TestCase): Path("platforms/_registry.yml").write_text( yaml.dump({"platforms": {"big": {"config": "big.yml"}}}) ) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() patches = ( mock.patch("model.largefiles.load_registered_paths", return_value=REGISTERED), mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), @@ -76,7 +77,7 @@ class ReleaseAssetNotCached(unittest.TestCase): packresolve.set_offline(False) def tearDown(self): - common._platform_config_cache.clear() + _platform_config_cache.clear() os.chdir(self._cwd) self._tmp.cleanup() @@ -138,8 +139,8 @@ class CoreExtraReleaseAssetNotCached(ReleaseAssetNotCached): "files": [{"name": "big.bin", "required": True, "sha1": SHA1}], }} Path("emulators/bigcore.yml").write_text(yaml.dump(self.profiles["bigcore"])) - common._platform_config_cache.clear() - common._emulator_profiles_cache.clear() + _platform_config_cache.clear() + _emulator_profiles_cache.clear() def _report(self) -> dict: return verify_platform(self.config, self.db, "emulators", self.profiles) @@ -188,10 +189,10 @@ class EmulatorReleaseAssetNotCached(ReleaseAssetNotCached): "files": [{"name": "big.bin", "required": True, "sha1": SHA1}], } Path("emulators/bigcore.yml").write_text(yaml.dump(self.profile)) - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() def _report(self) -> dict: - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() return verify_emulator(["bigcore"], "emulators", self.db, platforms_dir="platforms") def _entry(self) -> dict: diff --git a/tests/test_version_basis.py b/tests/test_version_basis.py index 44f8cca33..0ebeb0582 100644 --- a/tests/test_version_basis.py +++ b/tests/test_version_basis.py @@ -26,7 +26,7 @@ import yaml import profile_sync import upstream import version_basis -from common import load_emulator_profiles +from model.profiles import load_emulator_profiles from profile_sync import ProfileReport, bump_commit ROOT = Path(__file__).resolve().parent.parent @@ -131,14 +131,14 @@ class ReadsTheRecordedSourceOffline(unittest.TestCase): return int(exc.code or 0) return 0 - import common + from model.profiles import _emulator_profiles_cache - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self.assertEqual(run(), 0) stale = emulators / "snes9x.yml" stale.write_text(stale.read_text(encoding="utf-8").replace("1.63", "1.61"), encoding="utf-8") - common._emulator_profiles_cache.clear() + _emulator_profiles_cache.clear() self.assertEqual(run(), 1) diff --git a/tests/test_zipped_member.py b/tests/test_zipped_member.py index 24429e7ae..32dc94b9c 100644 --- a/tests/test_zipped_member.py +++ b/tests/test_zipped_member.py @@ -16,7 +16,7 @@ from pathlib import Path import yaml -from common import build_zip_contents_index +from core.ziptools import build_zip_contents_index from generate_pack import generate_pack REPO_ROOT = Path(__file__).resolve().parent.parent