diff --git a/scripts/auto_fetch.py b/scripts/auto_fetch.py index 8cf9c7d44..bf491e3f1 100644 --- a/scripts/auto_fetch.py +++ b/scripts/auto_fetch.py @@ -84,7 +84,8 @@ def find_missing(config: dict, db: dict) -> list[dict]: the cores need that no platform lists. """ from resolve.nativemode import reads_file_contents - from verify import Status, verify_platform + from packs.verdicts import Status + from packs.coverage import verify_platform result = verify_platform(config, db) hashed = reads_file_contents(config.get("verification_mode", "existence")) diff --git a/scripts/build_port.py b/scripts/build_port.py index 692cd12cc..3488d1135 100644 --- a/scripts/build_port.py +++ b/scripts/build_port.py @@ -144,7 +144,7 @@ def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]: 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 + from packs.naming import _name_part, _platform_pack_stem platforms_dir = str(root / "platforms") pool = list_release_pack_platforms(platforms_dir) @@ -176,7 +176,7 @@ def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path: ) # The packs' member writer: imported here, as it loads the whole # pack builder, which a caller reading ARCHIVES does not need. - from generate_pack import _add_pack_member + from packs.archive import _add_pack_member members = archive_members(name, root) output.parent.mkdir(parents=True, exist_ok=True) diff --git a/scripts/bundled_only.py b/scripts/bundled_only.py index 73961641a..fea5376f7 100644 --- a/scripts/bundled_only.py +++ b/scripts/bundled_only.py @@ -24,7 +24,7 @@ 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 +from packs.crossref import FileConsumers def _entries(profile: dict, db: dict) -> list[dict]: diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index e4673c9d5..7caba2795 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -60,7 +60,7 @@ from exporter.originals import ( wanted_sources, ) import pin_installer -import refresh_data_dirs +from packs import datadirs from core import upstream from core.cli import InputMissing, require_directory, suggest_names from model.targets import apply_target_overrides @@ -1027,10 +1027,10 @@ def check_coreinfo( def check_data(offline: bool) -> list[Finding]: if offline: return [Finding("data", "_data_dirs.yml", SKIPPED, detail="offline")] - registry = refresh_data_dirs.load_registry(str(REPO_ROOT / "platforms" / "_data_dirs.yml")) + registry = datadirs.load_registry(str(REPO_ROOT / "platforms" / "_data_dirs.yml")) sink = io.StringIO() with contextlib.redirect_stdout(sink): - results = refresh_data_dirs.refresh_all(registry, dry_run=True) + results = datadirs.refresh_all(registry, dry_run=True) findings = [] for key, result in sorted(results.items()): if result is None: diff --git a/scripts/core/gitclone.py b/scripts/core/gitclone.py new file mode 100644 index 000000000..4ea3d8db8 --- /dev/null +++ b/scripts/core/gitclone.py @@ -0,0 +1,61 @@ +"""The project's own clone: git output lines and the project's main line.""" + +from __future__ import annotations + +import re +import subprocess + + + +def _git_lines(*args: str) -> list[str] | None: + """Output lines of a git command, or None when git refuses it.""" + result = subprocess.run(["git", *args], capture_output=True, text=True, check=False) + if result.returncode != 0: + return None + return [line for line in result.stdout.splitlines() if line] + + +PROJECT_URLS = ( + "https://github.com/Abdess/retrobios", + "https://github.com/Abdess/retroarch_system", +) + + +def _repo_key(url: str) -> str: + """owner/name of a clone URL, whatever its scheme.""" + path = url.strip().rstrip("/").removesuffix(".git") + return "/".join(re.split(r"[/:]", path)[-2:]).casefold() + + +def _project_main_line() -> str | None: + """The project's main line, fetched when this clone does not hold it. + + A fork's clone has origin alone. Once the commit is pushed to the fork's + main, origin/main is HEAD and the diff against it was empty, so --changed + found nothing and exited 0. A remote added as CONTRIBUTING says and never + fetched did the same: upstream/main did not exist and origin/main won. + None leaves the upstream/ and origin/ lines in charge when the clone has + no remote at all and only its uncommitted files can be read. + """ + remotes = _git_lines("remote") or [] + if not remotes: + return None + project = {_repo_key(url) for url in PROJECT_URLS} + source = PROJECT_URLS[0] + for remote in remotes: + urls = _git_lines("remote", "get-url", "--all", remote) or [] + if any(_repo_key(url) in project for url in urls): + if _git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"): + return f"{remote}/main" + source = remote + break + fetched = subprocess.run( + ["git", "fetch", "--quiet", "--no-tags", source, "main"], + capture_output=True, text=True, check=False, + ) + if fetched.returncode != 0: + raise RuntimeError( + f"this clone does not hold the main of {PROJECT_URLS[0]}, and " + f"fetching its main from {source} failed: {fetched.stderr.strip()}" + ) + return "FETCH_HEAD" diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index 7158772c5..72788c854 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -13,1385 +13,51 @@ Usage: from __future__ import annotations import argparse -import hashlib import json import os import sys -import zipfile -import zlib -from collections import Counter -import dataclasses from dataclasses import dataclass -from pathlib import Path -from typing import TYPE_CHECKING, TypedDict +from typing import TYPE_CHECKING sys.path.insert(0, os.path.dirname(__file__)) -from model.alternatives import set_keys, set_requirements, settle_sets -from model.declarations import OUTER_ROOTS -from resolve.layout import 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.database import 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 core.paths import REPO_ROOT 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.standalone import standalone_set from resolve.launchers import ( LauncherLayer, - bound_launchers, - catalogued_model_files, declared_destinations, - held_record, launcher_unproven, - name_settings, - set_by, - setting_readers, - suffixed_stem, -) -from resolve.launchers import _directories as launcher_directories -from resolve.launchers import _names as launcher_names -from resolve.validation import ( - case_folded_slots, - declaration_settles, - inner_rom_check, - installed_with_emulator, - outside_gap_scope, - read_from_save_dir, - unread_on, - with_archive_members, ) if TYPE_CHECKING: - from typing_extensions import Unpack + pass +from packs.crossref import ( + DEFAULT_PLATFORMS_DIR, + _build_supplemental_index, + cross_reference, + declared_names, + folded_declared_slots, + launcher_reads_not_held, + load_platform_files, + profile_breakdown, +) yaml = require_yaml() DEFAULT_EMULATORS_DIR = "emulators" -DEFAULT_PLATFORMS_DIR = "platforms" DEFAULT_DB = "database.json" -def load_platform_files( - platforms_dir: str, - platforms: list[str] | None = None, -) -> tuple[dict[str, set[str]], dict[str, set[str]]]: - """Collect declared filenames + data_directories per system. - - Restricted to *platforms* when given, otherwise every registered platform. - Keyed by the normalized system ID: a profile writes `sega-megacd` where - RetroArch writes `sega-mega-cd`, and an exact match called 924 declared - files undeclared. - """ - declared: dict[str, set[str]] = {} - platform_data_dirs: dict[str, set[str]] = {} - for platform_name in platforms or list_registered_platforms( - platforms_dir - ): - config = load_platform_config(platform_name, platforms_dir) - for sys_id, system in config.get("systems", {}).items(): - for fe in system.get("files", []): - name = fe.get("name", "") - if name: - declared.setdefault(_norm_system_id(sys_id), set()).add(name) - for dd in system.get("data_directories", []): - ref = dd.get("ref", "") - if ref: - platform_data_dirs.setdefault(_norm_system_id(sys_id), set()).add(ref) - return declared, platform_data_dirs - - -def declared_names( - platforms_dir: str, platforms: list[str] | None, db: dict -) -> dict[str, list[tuple[int | None, str]]]: - """Every name the platforms declare, with each declaration's size and slot. - - The report judged "undeclared" per normalized system id, which does not - bring bk and elektronika-bk, or nintendo-sgb and nintendo-super-game-boy, - together: 646 entries whose exact name a platform declares were counted - undeclared, while verify and the site read one flat index. - """ - from model.declarations import merged_platform_declarations - - return merged_platform_declarations( - [ - load_platform_config(platform_name, platforms_dir) - for platform_name in platforms or list_registered_platforms( - platforms_dir - ) - ], - db, - ) - - -def folded_declared_slots( - platforms_dir: str, platforms: list[str] | None, db: dict -) -> frozenset[str]: - """The slots platforms whose filesystem folds case fill, any spelling. - - 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 model.declarations import platform_declarations - - slots: set[str] = set() - for platform_name in platforms or list_registered_platforms( - platforms_dir - ): - config = load_platform_config(platform_name, platforms_dir) - slots |= case_folded_slots(config, platform_declarations(config, db)) - return frozenset(slots) - - -def _build_supplemental_index( - data_root: str = "data", bios_root: str = "bios" -) -> set[str]: - """Build a set of filenames and directory names in data/ and inside bios/ ZIPs. - - A directory is indexed only with its trailing slash: a bare name matched a - file entry of the same name, and BasiliskII's required `ROM` read as held - because cpcemu keeps a directory called ROM. - """ - names: set[str] = set() - root_path = Path(data_root) - if root_path.is_dir(): - for fpath in root_path.rglob("*"): - if fpath.name.startswith("."): - continue - if fpath.is_file(): - names.add(fpath.name) - names.add(fpath.name.lower()) - else: - names.add(fpath.name + "/") - names.add(fpath.name.lower() + "/") - if fpath.is_dir(): - # Also index relative path from data/subdir/ for directory entries - parts = fpath.relative_to(root_path).parts - if len(parts) > 1: - rel = "/".join(parts[1:]) - names.add(rel + "/") - names.add(rel.lower() + "/") - bios_path = Path(bios_root) - if bios_path.is_dir(): - # Index directory names for directory-type entries (e.g., "nestopia/samples/moepro/") - for dpath in bios_path.rglob("*"): - if dpath.is_dir() and not dpath.name.startswith("."): - names.add(dpath.name + "/") - names.add(dpath.name.lower() + "/") - names |= _zip_member_names(bios_path) - return names - - -def _zip_member_names(bios_path: Path) -> set[str]: - """Basenames of the files inside every ZIP under bios/, both cases.""" - import zipfile - - names: set[str] = set() - for zpath in bios_path.rglob("*.zip"): - try: - with zipfile.ZipFile(zpath) as zf: - members = [m for m in zf.namelist() if not m.endswith("/")] - except (zipfile.BadZipFile, OSError) as exc: - print(f" WARNING: unreadable archive {zpath}: {exc}", file=sys.stderr) - continue - for member in members: - basename = member.rsplit("/", 1)[-1] - names.update((basename, basename.lower())) - return names - - -def _resolve_source( - fname: str, - by_name: dict[str, list], - by_name_lower: dict[str, str], - data_names: set[str] | None = None, - by_path_suffix: dict | None = None, - file_entry: dict | None = None, - db_files: dict | None = None, - bios_dir: str | None = None, -) -> str | None: - """Return the source category for a file, or None if not found. - - Returns ``"bios"`` (in database.json / bios/), ``"data"`` (in data/), - or ``None`` (not available anywhere). - - A name hit whose size contradicts a size the emulator verifies is not the - file, so it does not count as available. Nor is one whose bytes carry - none of the hashes the entry declares: a name never wins over a declared - hash, and zquestclassic's ending.mid read as held because Hydra Castle - Labyrinth has another file of that name. - - Another casing of the name in another emulator's tree proves nothing, as - in resolve_local_file's case-insensitive step: dosbox-x's et4000.bin read - as held through pcem's et4000.BIN, which the pack and the installer - refuse it. - """ - declared = _declared_content(file_entry or {}) - owners = _owner_tokens(file_entry or {}) - - def _can_be(sha1s: list | str) -> bool: - if not file_entry or db_files is None: - return True - if not isinstance(sha1s, list): - sha1s = [sha1s] - return any( - name_match_size_ok(file_entry, db_files.get(sha1, {}).get("size")) - and content_fits(file_entry, db_files.get(sha1, {}).get("path", "")) - and _record_carries(sha1, db_files.get(sha1, {}), declared) - for sha1 in sha1s - ) - - def _name_hit(name: str) -> bool: - """Whether the files indexed under *name* can be this entry.""" - return _can_be(by_name.get(name) or []) - - def _folded_hit(name: str) -> bool: - """_name_hit for a name matched in another casing.""" - return _can_be([ - sha1 for sha1 in by_name.get(name) or [] - if db_files is None - or not _foreign_tree(db_files.get(sha1, {}).get("path", ""), owners) - ]) - - # bios/ via database.json by_name - if fname in by_name and _name_hit(fname): - return "bios" - stripped = fname.rstrip("/") - basename = stripped.rsplit("/", 1)[-1] if "/" in stripped else None - if basename and basename in by_name and _name_hit(basename): - return "bios" - key = fname.lower() - if key in by_name_lower and _folded_hit(by_name_lower[key]): - return "bios" - if basename and basename.lower() in by_name_lower and _folded_hit( - by_name_lower[basename.lower()] - ): - return "bios" - # bios/ via by_path_suffix (regional variants) - if by_path_suffix and fname in by_path_suffix and _can_be(by_path_suffix[fname]): - return "bios" - # bios/ under the canonical MAME set name, as resolve_local_file does: - # a renamed archive is held once, under the name the dedup kept. - canonical = get_mame_clone_map(bios_dir).get(fname) - if canonical and canonical != fname: - if canonical in by_name and _name_hit(canonical): - return "bios" - if canonical.lower() in by_name_lower and _folded_hit( - by_name_lower[canonical.lower()] - ): - return "bios" - if data_names and _data_hit(fname, basename, file_entry, data_names): - return "data" - return None - - -def _data_hit( - fname: str, basename: str | None, file_entry: dict | None, data_names: set[str] -) -> bool: - """Whether data/ or a ZIP holds the name: a directory entry looks for a - directory, a file entry for a file. A file entry that declares a hash is - held only by a copy carrying it: touchhle's LiberationMono-Regular.ttf - read as held because idtech4a++'s extras.zip has another font of that - name.""" - looked_up = [fname, fname.lower()] + ([basename, basename.lower()] if basename else []) - if fname.endswith("/") or (file_entry or {}).get("type") == "directory": - looked_up = [name.rstrip("/") + "/" for name in looked_up] - return any(name in data_names for name in looked_up) - if not any(name in data_names for name in looked_up): - return False - declared = _declared_content(file_entry or {}) - if not declared: - return True - return any( - _content_matches(location, declared) - for location in _supplemental_locations().get((basename or fname).lower(), ()) - ) - - -_HASH_FIELDS = ("sha1", "md5", "sha256", "crc32") - - -def _record_carries(sha1: str, record: dict, declared: dict[str, set[str]]) -> bool: - """Whether a database record has one of the declared hashes, or none is declared.""" - if not declared: - return True - actual = { - "sha1": sha1.lower(), - **{field: str(record.get(field) or "").lower() for field in ("md5", "sha256", "crc32")}, - } - return any( - actual[field] and actual[field] in values - for field, values in declared.items() - ) - - -def _declared_content(file_entry: dict) -> dict[str, set[str]]: - """The hashes an entry declares, lowercased, by algorithm.""" - declared: dict[str, set[str]] = {} - for field in _HASH_FIELDS: - found = set(parse_hash_list(file_entry.get(field))) - if found: - declared[field] = found - return declared - - -_locations_cache: dict[tuple[str, str], dict[str, list[tuple[str, str]]]] = {} - - -def _supplemental_locations( - data_root: str = "data", bios_root: str = "bios" -) -> dict[str, list[tuple[str, str]]]: - """Where each name of the supplemental index sits: a data/ file, or a - member of a ZIP under bios/, keyed by lowercased basename.""" - key = (data_root, bios_root) - if key in _locations_cache: - return _locations_cache[key] - found: dict[str, list[tuple[str, str]]] = {} - root = Path(data_root) - if root.is_dir(): - for path in root.rglob("*"): - if path.is_file() and not path.name.startswith("."): - found.setdefault(path.name.lower(), []).append((str(path), "")) - for zpath in Path(bios_root).rglob("*.zip") if Path(bios_root).is_dir() else (): - try: - with zipfile.ZipFile(zpath) as zf: - members = [m for m in zf.namelist() if not m.endswith("/")] - except (zipfile.BadZipFile, OSError) as exc: - print(f" WARNING: unreadable archive {zpath}: {exc}", file=sys.stderr) - continue - for member in members: - found.setdefault(member.rsplit("/", 1)[-1].lower(), []).append( - (str(zpath), member) - ) - _locations_cache[key] = found - return found - - -def _content_matches(location: tuple[str, str], declared: dict[str, set[str]]) -> bool: - """Whether the file or member at *location* carries a declared hash.""" - path, member = location - try: - if member: - with zipfile.ZipFile(path) as zf: - if set(declared) == {"crc32"}: - return f"{zf.getinfo(member).CRC:08x}" in declared["crc32"] - data = zf.read(member) - else: - data = Path(path).read_bytes() - except (zipfile.BadZipFile, KeyError, OSError) as exc: - print(f" WARNING: cannot read {path} {member}: {exc}", file=sys.stderr) - return False - actual = { - "sha1": hashlib.sha1(data).hexdigest(), - "md5": hashlib.md5(data).hexdigest(), - "sha256": hashlib.sha256(data).hexdigest(), - "crc32": f"{zlib.crc32(data) & 0xFFFFFFFF:08x}", - } - return any(actual[field] in values for field, values in declared.items()) - - -_tree_cache: dict[tuple[str, str], list[str]] = {} - - -def _trees(data_root: str, bios_root: str) -> list[str]: - """Every directory under data/ and bios/, as a path with a trailing slash.""" - key = (data_root, bios_root) - if key not in _tree_cache: - _tree_cache[key] = sorted( - f"{path.as_posix()}/" - for root in (data_root, bios_root) if Path(root).is_dir() - for path in Path(root).rglob("*") - if path.is_dir() - and not any(p.startswith(".") for p in path.relative_to(root).parts) - ) - return _tree_cache[key] - - -def held_copy( - entry: dict, data_root: str = "data", bios_root: str = "bios" -) -> tuple[str, str] | None: - """The data/ file, directory or bios/ ZIP member holding an entry. - - The database indexes the files under bios/, and an entry held otherwise - (specmate.rom as a member of spectrum_opus.zip, Dolphin's fonts in its - data directory) read as held with no word of where. Returns (path, - member), the member empty for a file or a directory. A file entry that - declares a hash is held only by a copy carrying it, as _data_hit judges. - """ - names = [entry.get("name", ""), entry.get("path") or "", *(entry.get("aliases") or [])] - names = [str(n) for n in names if n] - if entry.get("type") == "directory" or any(n.endswith("/") for n in names[:1]): - for name in names: - tail = "/" + name.strip("/") + "/" - for tree in _trees(data_root, bios_root): - if tree.endswith(tail): - return tree, "" - return None - declared = _declared_content(entry) - locations = _supplemental_locations(data_root, bios_root) - for name in names: - for location in locations.get(name.rsplit("/", 1)[-1].lower(), ()): - if not declared or _content_matches(location, declared): - return location - return None - - -class FileConsumers: - """Who reads each collected file, joined through the resolver. - - The site joined database files to emulators and platforms by bare name: - each of the four pak0.pk3 of four games was attributed to every engine - reading a pak0.pk3. A consumer here is an entry that resolves to the - file by the evidence the pack uses, so a homonym is nobody's file. - """ - - def __init__( - self, db: dict, zip_contents: dict | None = None, - data_dir_registry: dict | None = None, - ) -> None: - self._db = db - self._zip_contents = zip_contents - # The builder resolves with the data trees: Dolphin's codehandler.bin - # comes from data/dolphin-sys, and without them the name step gave it - # Dolphin-MMJR's copy, which the site then said Dolphin reads. - self._data_dir_registry = ( - data_dir_registry if data_dir_registry is not None - else load_data_dir_registry( - str(REPO_ROOT / DEFAULT_PLATFORMS_DIR) - ) - ) - self._sha1_by_path = { - path: sha1 - for sha1, entry in db.get("files", {}).items() - for path in {entry.get("path", ""), *entry.get("paths", [])} - if path - } - self.platforms: dict[str, set[str]] = {} - # Under which of its systems each platform declares a file, so a - # link can land on that section rather than the page top. - self.platform_systems: dict[str, dict[str, set[str]]] = {} - # Where each platform puts the file in its BIOS directory. - self.platform_destinations: dict[str, dict[str, set[str]]] = {} - self.emulators: dict[str, set[str]] = {} - # The entry that reads each file, by its position in the profile's - # files: a link lands on that entry's card, not the page top. - self.emulator_entries: dict[str, dict[str, int]] = {} - self.emulator_files: dict[str, list] = {} - # Where each platform's pack installs the file, its cores' files - # included: the platform's own list names a fraction of them. - self.installed: dict[str, dict[str, set[str]]] = {} - - def sha1_of(self, entry: dict, dest: str = "", owner: str = "") -> str | None: - """The collected file an entry resolves to, or None. - - A profile entry names its owner, as the builder does: without it the - name step chose another tree's copy, and the page credited the file - the pack does not ship. - """ - if not entry.get("name"): - return None - if owner: - entry = {**entry, "source_profile": owner} - path, status = resolve_local_file( - entry, self._db, self._zip_contents, dest_hint=dest, - data_dir_registry=self._data_dir_registry, - ) - if not path or status == "not_found": - return None - # Batocera pins naomi2.zip by the md5 of a ROM inside it: the resolver - # hands back the archive as a mismatch, and the member settles it as - # the builder does. - if status == "hash_mismatch" and not ( - entry.get("zipped_file") and inner_rom_check(entry, path) == "ok" - ): - return None - return self._sha1_by_path.get(path) - - def add_platforms(self, configs: dict[str, dict]) -> None: - for name, config in configs.items(): - for system_id, system in config.get("systems", {}).items(): - for entry in system.get("files", []): - # No destination hint, as the builder, the manifest and - # verify resolve a declaration: with one, RetroBat's 63 - # mame/hash lists credited another revision than the one - # its manifest installs. - sha1 = self.sha1_of(entry) - if sha1: - self.platforms.setdefault(sha1, set()).add(name) - self.platform_systems.setdefault(sha1, {}).setdefault( - name, set() - ).add(system_id) - where = str(entry.get("destination") or entry["name"]) - # EmuDeck matches by md5 alone: its entries carry a - # system:md5 key, not a place in the folder. - if ":" not in where: - self.platform_destinations.setdefault(sha1, {}).setdefault( - name, set() - ).add(where) - - def add_manifests(self, install_dir: str | Path) -> None: - """Read what each install manifest places, alternatives included.""" - for path in sorted(Path(install_dir).glob("*.json")): - try: - manifest = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - print(f"WARNING: {path}: {exc}", file=sys.stderr) - continue - platform = str(manifest.get("platform") or path.stem) - for entry in manifest.get("files") or []: - for sha1 in {entry.get("sha1"), *( - alt.get("sha1") for alt in entry.get("alternatives") or [] - )} - {None, ""}: - self.installed.setdefault(sha1, {}).setdefault( - platform, set()).add(str(entry.get("dest", ""))) - - def sha1_at(self, path: str) -> str | None: - """The file the database records at a collection path.""" - return self._sha1_by_path.get(path) - - def path_of(self, sha1: str) -> str: - """The collection path the database records for a file.""" - return str(self._db.get("files", {}).get(sha1, {}).get("path", "")) - - def directory_members(self, entry: dict) -> dict[str, str]: - """{destination: sha1} of the files a ``type: directory`` entry reads.""" - if entry.get("type") != "directory": - return {} - return { - member["path"]: member["sha1"] - for member in expand_directory_entries([entry], self._db) - if member is not entry - } - - def add_emulators(self, profiles: dict[str, dict]) -> None: - """Each file a profile entry resolves to, a directory's members included. - - A directory entry was resolved by its own name and found nothing: - 11,976 files under alephone's Plugins/, cdogs' and thextech's trees - named no emulator on their card. - """ - for name, profile in profiles.items(): - if profile.get("type") == "alias": - continue - files = profile.get("files") or [] - self.emulator_files[name] = files - # A file a profile names keeps its own entry over the directory - # that also holds it. - order = sorted( - (i for i, entry in enumerate(files) if isinstance(entry, dict)), - key=lambda i: files[i].get("type") == "directory", - ) - for index in order: - entry = files[index] - members = self.directory_members(entry) - if members: - found = [ - self.sha1_of({**entry, "name": dest, "path": dest, "sha1": sha1}, - dest, owner=name) - for dest, sha1 in members.items() - ] - else: - found = [self.sha1_of(*entry_target(entry, files), owner=name)] - for sha1 in found: - if sha1: - self.emulators.setdefault(sha1, set()).add(name) - self.emulator_entries.setdefault(sha1, {}).setdefault(name, index) - - -def entry_target(entry: dict, files: list[dict]) -> tuple[dict, str]: - """The entry a profile entry resolves through, and its destination. - - A ROM read inside an archive is the archive: FBNeo opens sm1.sm1 in - neogeo.zip, and resolved by its crc32 it credited a loose copy FBNeo - never opens, while no neogeo.zip card named FBNeo. The archive - members the profile reads decide between same-named copies, as in - the emulator pack and verify. - """ - if entry.get("archive"): - return archive_entry(entry["archive"], files), "" - return with_archive_members(entry, files), entry.get("path") or "" - - -def entry_source(f: dict, index: dict) -> str | None: - """Where the collection holds a profile entry, or None. - - By name, path and alias, then by any hash the entry declares. The gap - report and the site pages read this one function, so a file is held or - missing in the same way on both. - """ - by_name, by_name_lower = index["by_name"], index["by_name_lower"] - data_names, by_path_suffix = index.get("data_names"), index["by_path_suffix"] - db_files = index["db_files"] - fname = f.get("name", "") - path_field = f.get("path") or "" - # A directory is held when the collection holds files under it, the rule - # the pack and verify --emulator expand it by: a bare-name lookup missed - # cdogs' .wolf3d/, whose 695 files every pack carries. - if f.get("type") == "directory" and directory_members( - {"indexes": {"by_path_suffix": by_path_suffix}}, path_field or fname - ): - return "bios" - found = None - for candidate in [fname, *([path_field] if path_field != fname else []), - *(f.get("aliases") or [])]: - if not candidate: - continue - source = _resolve_source( - candidate, by_name, by_name_lower, data_names, by_path_suffix, f, db_files, - index.get("bios_dir"), - ) - if source == "bios": - return source - found = found or source - - def values(field: str) -> list[str]: - return parse_hash_list(f.get(field)) - - # The declared content anywhere in bios/ comes before a data/ copy, as in - # the resolver: the hash steps run before the data directories. - held = ( - any(index["by_md5"].get(v) for v in parse_md5_list(f.get("md5"))) - or any(v in db_files for v in values("sha1")) - # rust_dos names its SC-55 ROMs by sha256 alone - or any(v in index["by_sha256"] for v in values("sha256")) - or any(index["by_crc32"].get(v) for v in values("crc32")) - ) - return "bios" if held else found - - -def _resolve_archive_source( - archive_name: str, - by_name: dict[str, list], - by_name_lower: dict[str, str], - data_names: set[str] | None = None, - by_path_suffix: dict | None = None, -) -> str: - """Resolve source for an archive (ZIP) name, returning a source category string.""" - result = _resolve_source( - archive_name, by_name, by_name_lower, data_names, by_path_suffix, - ) - return result if result is not None else "missing" - - -def _first_hash(entry: dict) -> str: - """The first hash an entry declares, strongest first, or ''.""" - for field in ("sha1", "sha256", "md5", "crc32"): - value = entry.get(field) - if isinstance(value, list): - value = value[0] if value else "" - if value: - return f"{field}:{str(value).lower()}" - return "" - - -def slot_key(f: dict, standalone: bool = False) -> tuple: - """The slot a profile entry fills: its entries on one slot are the - versions its code accepts there, and holding any of them fills it. - - The path is the one the running build reads: b2's standalone build - reads MOS 3.20 and 3.50 from two directories, two slots, while the - entries share a name and no `path:`.""" - fname = f.get("name", "") - where = (f.get("standalone_path") if standalone else None) or f.get("path") - return ( - fname, - f.get("archive"), - system_dir_path(f, where or fname), - f.get("system"), - f.get("selection_slot"), - f.get("mode", "both"), - read_from_save_dir(f, standalone), - ) - - -# Why an entry is left out of the comparison, in the order they are printed. -SET_ASIDE = { - "other_versions": "other versions of a slot", - "not_read": "not read on this platform", - "outside_scope": "outside the pack", - "launcher": "filled by the platform's launcher", -} - - -def profile_breakdown(data: dict) -> str: - """Where each entry of a profile went, adding up to its file count. - - The heading said 261 files, 7 declared and 238 undeclared, and the 16 - others were nowhere: the versions a slot accepts, the entries the - platform never opens and the ones no pack carries. - """ - # A report built without the per-entry tally (a fixture, a saved --json - # of an earlier run) falls back to its row counts. - parts = [f"{data.get('declared_files', data['platform_covered'])} declared by platforms", - f"{data.get('undeclared_files', data['gaps'])} undeclared"] - unsourceable = data.get("unsourceable_files", len(data.get("unsourceable") or [])) - if unsourceable: - parts.append(f"{unsourceable} unsourceable") - aside = data.get("set_aside") or {} - detail = [f"{aside[key]} {label}" for key, label in SET_ASIDE.items() if aside.get(key)] - if detail: - parts.append(f"{sum(aside.values())} set aside ({', '.join(detail)})") - return ", ".join(parts) - - -def _effective_path(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: - # The destination the running build reads, as find_undeclared_files - # takes it: Batocera's standalone Cemu reads keys.txt at - # standalone_path, and the libretro Cemu/keys.txt reported here - # settled the declaration on a slot the platform never fills. - if is_standalone: - return f.get("standalone_path") or f.get("path") or fname - if save_root: - return f.get("path") or fname - return system_dir_path(f, f.get("path") or fname) - - -@dataclass -class _ProfileComparison: - """One profile's entries against the platforms' declarations.""" - - emu_name: str - profile: dict - index: dict - platform_names: set[str] - platform: str - layouts: list - versions: dict[tuple, list[dict]] = dataclasses.field(default_factory=dict) - position: dict[int, int] = dataclasses.field(default_factory=dict) - gaps: list[dict] = dataclasses.field(default_factory=list) - covered: list[dict] = dataclasses.field(default_factory=list) - unsourceable_list: list[dict] = dataclasses.field(default_factory=list) - archive_gaps: dict[tuple, dict] = dataclasses.field(default_factory=dict) - seen_files: set[tuple] = dataclasses.field(default_factory=set) - fates: dict[int, str] = dataclasses.field(default_factory=dict) - # Grouped entries met, as (set keys, entry, fills, the list holding - # its row, the row): settled once the profile is read. - set_records: list[tuple[tuple, dict, bool, list | None, dict | None]] = dataclasses.field( - default_factory=list - ) - archive_rows: list[dict] = dataclasses.field(default_factory=list) - - def fate(self, f: dict, what: str) -> None: - key = self.position[id(f)] - current = self.fates.get(key) - if current is None or (current in SET_ASIDE and what not in SET_ASIDE): - self.fates[key] = what - - def compare(self, f: dict, is_standalone: bool) -> None: - """File one entry of one build: declared, a gap, or set aside.""" - fname = f.get("name", "") - platform = self.platform - save_root = read_from_save_dir(f, is_standalone) - effective_path = _effective_path(f, fname, is_standalone, save_root) - slot = slot_key(f, is_standalone) - seen_key = slot - if len(self.layouts) > 1: - # One file read at one path by both builds counts once. - seen_key = (effective_path.casefold(), seen_key) - if not fname: - self.fate(f, "outside_scope") - return - if seen_key in self.seen_files: - self.fate(f, "other_versions") - return - if unread_on(f, platform): - self.fate(f, "not_read") - return - - # Collect unsourceable files separately (documented, not a gap) - unsourceable_reason = f.get("unsourceable", "") - keys = set_keys((self.emu_name, is_standalone), f) - if unsourceable_reason: - self.seen_files.add(seen_key) - self.fate(f, "unsourceable") - row = { - "name": fname, - "required": f.get("required", False), - "reason": unsourceable_reason, - "source_ref": f.get("source_ref", ""), - } - self.unsourceable_list.append(row) - self.set_records.append((keys, f, False, self.unsourceable_list, row)) - return - - if outside_gap_scope(f, is_standalone): - self.fate(f, "outside_scope") - return - - archive = f.get("archive") - - # Check platform declaration: by name, by an alias the core answers - # to (RetroArch lists amiberry's cd32.rom as kick40060.CD32), or by - # archive. - # A platform declares files of its BIOS tree: none answers for one - # the core reads below the save directory. - in_platform = not save_root and f.get("root") not in OUTER_ROOTS and declaration_settles( - f, fname, self.platform_names, effective_path, - self.index.get("folded_slots", frozenset()), - self.index.get("declared_contents"), - ) - - if in_platform: - self.seen_files.add(seen_key) - self.fate(f, "declared") - self.set_records.append((keys, f, True, None, None)) - self.covered.append({ - "name": fname, - "path": effective_path, - "required": f.get("required", False), - "in_platform": True, - }) - return - - self.seen_files.add(seen_key) - self.fate(f, "undeclared") - - if archive: - self._archive_gap(f, archive, is_standalone) - return - self._loose_gap(f, fname, is_standalone, save_root, effective_path, slot, keys) - - def _archive_gap(self, f: dict, archive: str, is_standalone: bool) -> None: - archive_key = ( - archive, - f.get("system"), - f.get("selection_slot"), - f.get("mode", "both"), - ) - if archive_key not in self.archive_gaps: - source = _resolve_archive_source( - archive, self.index["by_name"], self.index["by_name_lower"], - self.index["data_names"], self.index["by_path_suffix"], - ) - self.archive_gaps[archive_key] = { - "name": archive, - "path": archive, - "required": False, - "note": "", - "source_ref": "", - "in_platform": False, - "in_repo": source != "missing", - "source": source, - "archive": archive, - "archive_file_count": 0, - "archive_required_count": 0, - } - entry = self.archive_gaps[archive_key] - if entry["archive_file_count"] == 0: - # The archive's own declaration names its sets: an archive - # is a member like a loose file (Kronos' stvbios.zip). - own = archive_entry(archive, self.profile.get("files", [])) - self.set_records.append(( - set_keys((self.emu_name, is_standalone), own), own, - entry["in_repo"], self.archive_rows, entry, - )) - self.archive_rows.append(entry) - entry["archive_file_count"] += 1 - if f.get("required", False): - entry["archive_required_count"] += 1 - entry["required"] = True - if not entry["source_ref"] and f.get("source_ref"): - entry["source_ref"] = f["source_ref"] - - def _loose_gap( - self, f: dict, fname: str, is_standalone: bool, save_root: bool, - effective_path: str, slot: tuple, keys: tuple, - ) -> None: - emu_name = self.emu_name - platform = self.platform - # --- resolve source provenance --- - # A release asset is held when the database records it, as any other - # file: storage says where the bytes are served from, not that the - # collection has them (kenji-nx's user-picked firmware package). - source = next( - ( - found for version in self.versions[slot] - if (found := entry_source( - {**version, "source_profile": emu_name}, self.index, - )) is not None - ), - "missing", - ) - if source != "missing" and f.get("storage", "") in ("release", "large_file"): - source = "large_file" - - in_repo = source != "missing" - - entry = { - "name": fname, - "path": effective_path, - "required": f.get("required", False), - "bundled": installed_with_emulator(f, platform), - "note": f.get("note", ""), - "source_ref": f.get("source_ref", ""), - "in_platform": False, - "in_repo": in_repo, - "source": source, - # What tells this file from a homonym another emulator wants. - "identity": _first_hash(f), - } - if save_root: - entry["root"] = "save" - elif f.get("unplaced"): - entry["unplaced"] = f["unplaced"] - elif f.get("root") in OUTER_ROOTS: - entry["root"] = f["root"] - elif self.index.get("launcher_candidates") is not None: - # What verify hands the launcher layer for the same entry. - probe = { - **f, - "profile": emu_name, - "emulator": self.profile.get("emulator", emu_name), - "path": effective_path, - "in_repo": in_repo, - "bundled": entry["bundled"], - } - self.index["launcher_candidates"].append( - (emu_name, is_standalone, f, probe, entry) - ) - self.gaps.append(entry) - self.set_records.append((keys, f, in_repo, self.gaps, entry)) - - def settle(self) -> None: - # One need per set: a member another one fills is not a gap, and a set - # nobody holds is one gap under its first member (alternatives.py), as - # verify and the packs count it. - # Archive units rank first among equals, as the builder orders them. - grouped = sorted( - (r for r in self.set_records if r[0]), key=lambda r: r[3] is not self.archive_rows - ) - requirements = set_requirements(self.profile) - excused, standing = settle_sets( - [(keys, f, fills) for keys, f, fills, _l, _r in grouped], - lambda key: requirements.get(key[1], True), - ) - for at, (_keys, member, _fills, rows, set_row) in enumerate(grouped): - if set_row is None or rows is None: - continue - if at in standing: - set_row["alternatives"] = standing[at].others - set_row["required"] = standing[at].required - if at in excused: - rows.remove(set_row) - if id(member) in self.position: - self.fates[self.position[id(member)]] = "other_versions" - - for ag in sorted(self.archive_gaps.values(), key=lambda e: e["name"]): - if any(ag is row for row in self.archive_rows): - self.gaps.append(ag) - - def summary(self) -> dict: - tally = Counter(self.fates.values()) - profile = self.profile - return { - "emulator": profile.get("emulator", self.emu_name), - "systems": profile.get("systems", []), - "total_files": len(profile.get("files", [])), - "platform_covered": len(self.covered), - **_gap_counts(self.gaps), - "gap_details": self.gaps, - "unsourceable": self.unsourceable_list, - # Entries, not rows: an archive's members are one gap row. - "declared_files": tally["declared"], - "undeclared_files": tally["undeclared"], - "unsourceable_files": tally["unsourceable"], - "set_aside": {key: tally[key] for key in SET_ASIDE}, - } - - -def _cross_reference_profile( - emu_name: str, - profile: dict, - declared: dict[str, set[str]], - report: dict, - index: dict, - standalone_cores: set[str] | None = None, - platform: str = "", -) -> None: - """Compare one emulator profile against what the platforms declare. - - *platform* is the platform key under --platform, empty for the whole - tree. It decides, through the functions verify reads, which entries the - platform's launcher never opens and which ones its emulator package - already installs. - - Split out of cross_reference, where it was a 200-line loop body that - carried the whole function's branching: every file is resolved by name, - by path, by hash and by archive membership before it can be called a - gap. *index* carries the database lookups those steps share. - """ - all_declared = index["all_declared"] - systems = profile.get("systems", []) - - # Skip filename-agnostic profiles (BIOS detected without fixed names) - if profile.get("bios_mode") == "agnostic": - return - - if all_declared is not None: - platform_names = all_declared - else: - platform_names = set() - for sys_id in systems: - platform_names.update(declared.get(_norm_system_id(sys_id), set())) - - # The build a platform runs decides which entries it reads, as in - # find_undeclared_files: without a platform, the libretro build. - layouts = platform_layouts(emu_name, profile, standalone_cores or set()) - comparison = _ProfileComparison(emu_name, profile, index, platform_names, platform, layouts) - # Each file under each layout the platform gives the emulator: both, for - # one it launches as a libretro core and standalone. - layout_files = [(f, standalone) for view, standalone in layouts for f in view.get("files", [])] - - # The entries of one profile on one slot are the versions its code - # accepts there (raze's ten DUKE3D.GRP): holding any of them fills the - # slot, as verify --emulator credits it. - for f, is_standalone in layout_files: - comparison.versions.setdefault(slot_key(f, is_standalone), []).append(f) - - # What became of each entry, so the heading adds up: a file a platform - # declares, one it does not, or one set aside and why. An entry read by - # two builds keeps the first answer that compares it. Each layout lists - # the profile's entries in their order, so a position names one entry. - comparison.position = { - id(f): i for view, _ in layouts for i, f in enumerate(view.get("files", [])) - } - - for f, is_standalone in layout_files: - comparison.compare(f, is_standalone) - comparison.settle() - report[emu_name] = comparison.summary() - - -def _gap_counts(gaps: list[dict]) -> dict[str, int]: - """The per-source tallies of a profile's gap rows.""" - return { - "gaps": len(gaps), - "gap_in_repo": sum(1 for g in gaps if g["in_repo"]), - "gap_missing": sum(1 for g in gaps if g["source"] == "missing"), - "gap_bios": sum(1 for g in gaps if g["source"] == "bios"), - "gap_data": sum(1 for g in gaps if g["source"] == "data"), - "gap_large_file": sum(1 for g in gaps if g["source"] == "large_file"), - } - - -def _settle_launcher_places( - report: dict, - candidates: list[tuple[str, bool, dict, dict, dict]], - layer: LauncherLayer, - db: dict, -) -> None: - """Apply the platform's launcher places as find_undeclared_files does. - - Batocera's DuckStation generator fills the PAL slot with scph5502.bin, - yet the report listed duckstation's scph1002a.bin as a file the pack - carries, which neither the pack nor the manifest does. - """ - added, settled = layer.settle( - [(emu, standalone, f, probe) for emu, standalone, f, probe, _ in candidates], - lambda probe: held_record(probe, db), - ) - for emu, _standalone, _f, probe, gap in candidates: - if id(probe) not in settled: - continue - data = report[emu] - data["gap_details"] = [g for g in data["gap_details"] if g is not gap] - data["undeclared_files"] -= 1 - data["set_aside"]["launcher"] += 1 - for entry in added: - data = report[entry["profile"]] - data["gap_details"].append({ - "name": entry["name"], - "path": entry["path"], - "required": entry.get("required", False), - "bundled": False, - "note": "", - "source_ref": "", - "in_platform": False, - "in_repo": True, - "source": "bios", - "identity": entry.get("sha1") or "", - "launcher": entry["launcher"], - "launcher_of": entry["launcher_of"], - }) - for data in report.values(): - data.update(_gap_counts(data["gap_details"])) - - # The --json key of the launcher reads category, beside the emulator keys. LAUNCHER_READS_KEY = "_launcher_reads_not_held" # The --json key of the launcher records a config file does not prove. LAUNCHER_UNPROVEN_KEY = "_launcher_unproven" -# A package record names no file: it records what a package builds. -_NAMELESS_KINDS = frozenset({"package"}) - -# The folder of the platform's own launcher, as its scraper spells it: a -# program the launcher runs from there (RetroBat's xbox-iso-vfs.exe) is part -# of the platform, never a file to collect. -PLATFORM_OWN_FOLDERS = frozenset({""}) - - -def launcher_file_names(record: dict) -> list[str]: - """The concrete file names a launcher record reads, in code order. - - The names are read as the launcher layer reads them (`launchers._names`): - a label after the name is dropped ("neocd_z.rom (CDZ)"), and a name with - `<` or without an extension is not a file name (a folder the record - links, an option value such as hatari2014's "default"). A name with a - `{X}` placeholder is a template: Batocera's hatari tries tos{L}.img for - every language and ROCKNIX links one memory card per slot and region, - so its expansions say which variants the code accepts, not which file is - owed. A wildcard is a pattern the emulator matches. `search_dir` is a - folder and never a name, whatever the kind. - """ - if record.get("kind") in _NAMELESS_KINDS: - return [] - return [ - name for name in launcher_names({**record, "expands": {}}) if "*" not in name - ] - - -def _profile_names(profiles: dict[str, dict]) -> tuple[dict[str, list[dict]], dict[str, list[dict]]]: - """Profile entries by each name and alias they answer to, exact and folded.""" - exact: dict[str, list[dict]] = {} - folded: dict[str, list[dict]] = {} - for profile in profiles.values(): - if profile.get("type") in ("launcher", "alias"): - continue - for entry in profile.get("files") or []: - names = {str(entry.get("name") or "")} | {str(a) for a in entry.get("aliases") or []} - for name in names - {""}: - base = name.rsplit("/", 1)[-1] - exact.setdefault(base, []).append(entry) - folded.setdefault(base.casefold(), []).append(entry) - return exact, folded - - -class _NameHolder: - """Whether the collection holds a file under a launcher name. - - A name is held when database.json carries a file under it or under an - alias it indexes, when a profile entry that answers to the name (as its - name or an alias) resolves, or when resolve_local_file finds it in a data - directory. The database answers for files kept as release assets, absent - from a checkout. A copy known only under another casing is returned - apart: a launcher that matches names exactly does not open it. - """ - - def __init__( - self, db: dict, profiles: dict[str, dict], data_dir_registry: dict | None - ) -> None: - self.db = db - self.registry = data_dir_registry - files = db.get("files", {}) - self.by_name = { - name: sha1s - for name, sha1s in db.get("indexes", {}).get("by_name", {}).items() - if any(sha1 in files for sha1 in sha1s) - } - self.by_name_folded: dict[str, list[str]] = {} - for name in self.by_name: - self.by_name_folded.setdefault(name.casefold(), []).append(name) - self.exact, self.folded = _profile_names(profiles) - self._cache: dict[str, tuple[str, bool] | None] = {} - - def _entry_held(self, entry: dict) -> bool: - names = [str(entry.get("name") or "")] + [str(a) for a in entry.get("aliases") or []] - if any(n.rsplit("/", 1)[-1] in self.by_name for n in names if n): - return True - path, _status = resolve_local_file(entry, self.db, data_dir_registry=self.registry) - return path is not None - - def held(self, name: str) -> tuple[str, bool] | None: - """The name the collection holds *name* under, and whether its casing is exact.""" - if name in self._cache: - return self._cache[name] - base = name.rsplit("/", 1)[-1] - found: tuple[str, bool] | None = None - stem = suffixed_stem(base) - if base in self.by_name or any(map(self._entry_held, self.exact.get(base, []))) or stem is not None and any(map(self._entry_held, self.exact.get(stem, []))): - found = (base, True) - else: - path, _status = resolve_local_file( - {"name": name}, self.db, data_dir_registry=self.registry - ) - if path is not None: - found = (Path(path).name, Path(path).name == base) - elif base.casefold() in self.by_name_folded: - found = (self.by_name_folded[base.casefold()][0], False) - else: - entry = next( - (e for e in self.folded.get(base.casefold(), []) if self._entry_held(e)), - None, - ) - if entry is not None: - found = (str(entry.get("name") or ""), False) - self._cache[name] = found - return found - - -def _held_by_setting( - name: str, - settings: dict, - readers: list[str], - profiles: dict[str, dict], - holder: _NameHolder, - db: dict, -) -> bool: - """Whether the setting the name is written to reads a held file. - - A placeholder read from the setting takes the held dump the - catalogues name after the model the launcher's name spells. - """ - entries = [ - entry - for key in readers - for entry in profiles[key].get("files") or [] - if settings[name] and set_by(entry, settings[name]) - ] - return any(holder._entry_held(entry) for entry in entries) or any( - "<" in str(entry.get("name", "")) - and any( - name_match_size_ok(entry, found.get("size")) - for found in catalogued_model_files(name, db) - ) - for entry in entries - ) - - -def _unsourceable_names(readers: list[str], profiles: dict[str, dict]) -> dict[str, str]: - return { - str(n).rsplit("/", 1)[-1]: str(entry["unsourceable"]) - for key in readers - for entry in profiles[key].get("files") or [] - if entry.get("unsourceable") - for n in (entry.get("name"), *(entry.get("aliases") or [])) - if n - } - - -def _add_name_row( - by_key: dict[str, dict], - platform: str, - name: str, - found: tuple[str, bool] | None, - folds: bool, - reader: dict, - unsourceable: dict[str, str], -) -> None: - """Add a launcher record to the row of a name the collection lacks.""" - key = name.casefold() if folds else name - row = by_key.get(key) - if row is None: - row = by_key[key] = { - "platform": platform, - "name": name, - "emulators": [], - "readers": [], - } - if found: - row["held_as"] = found[0] - reason = unsourceable.get(name.rsplit("/", 1)[-1]) - if reason and "unsourceable" not in row: - row["unsourceable"] = reason - if reader["emulator"] not in row["emulators"]: - row["emulators"].append(reader["emulator"]) - if reader not in row["readers"]: - row["readers"].append(reader) - - -def launcher_reads_not_held( - configs: dict[str, dict], - db: dict, - profiles: dict[str, dict], - data_dir_registry: dict | None = None, - emulator: str = "", -) -> list[dict]: - """The file names a platform's launch code reads that the collection lacks. - - One row per platform and name, with every record that reads it. A - launcher that matches case-insensitively, or runs on a filesystem that - folds case, is satisfied by a copy under another casing. Elsewhere such - a copy is reported with `held_as`, since the launcher does not open it - under the name it asks for. *emulator* keeps the records whose emulator - name designates that profile. - - Three records ask for nothing the collection lacks. A search keeps the - first name it finds, so one held name fills it: RetroBat's Amiberry - launcher returns the first of kick34005.A500, kick34005.A500.rom and - amiga-os-130.rom that exists (Amiberry.Generator.cs:674-699). A copy - whose source lies outside the BIOS directory brings a file the platform - installs itself, from its own package or written by its own script - (RetroPie's lr-vecx copies $md_inst/system.bin), and so does a program - the launcher runs from its own folder. A file handed to the - setting a reader's profile entry is read from is that entry's file, - which the pack places under the launcher's name. - """ - holder = _NameHolder(db, profiles, data_dir_registry) - every_profile = set(profiles) - rows: list[dict] = [] - for platform, config in configs.items(): - by_key: dict[str, dict] = {} - # A record resting on a config file it cannot prove reads nothing - # yet: it is reported apart (launcher_unproven). - for record in bound_launchers(config, profiles): - names = launcher_file_names(record) - if not names: - continue - readers = sorted({ - key - for part in str(record.get("emulator", "")).split(",") - for key in LauncherLayer._profiles_named(part.strip(), profiles, every_profile) - }) - if not readers: - # RetroDECK names its frontend and the core option names the core. - readers = setting_readers( - str(record.get("passes_to") or ""), profiles, every_profile - ) - if emulator and emulator not in readers: - continue - folds = bool(record.get("case_insensitive") or config.get("case_insensitive_fs")) - base = str(config.get("base_destination") or "bios") - if record.get("kind") == "copies" and not launcher_directories(record, base): - continue - if str(record.get("search_dir") or "") in PLATFORM_OWN_FOLDERS: - continue - settings = name_settings(record, names) - by_model = { - name for name in names - if _held_by_setting(name, settings, readers, profiles, holder, db) - } - if record.get("kind") == "names_searched" and any( - (found := holder.held(name)) and (found[1] or folds) for name in names - ): - continue - reader = { - "emulator": str(record.get("emulator", "")), - "build": str(record.get("build", "")), - "kind": str(record.get("kind", "")), - "source_ref": str(record.get("source_ref", "")), - "profiles": readers, - } - # A name a reader's entry declares unsourceable is no gap: its - # row carries the reason and is counted apart. - unsourceable = _unsourceable_names(readers, profiles) - for name in names: - found = holder.held(name) - if found and (found[1] or folds) or name in by_model: - continue - _add_name_row(by_key, platform, name, found, folds, reader, unsourceable) - rows.extend(by_key[key] for key in sorted(by_key, key=str.casefold)) - return rows - def print_launcher_unproven(rows: list[dict]) -> None: """The launcher records resting on a config file the code does not prove. @@ -1448,85 +114,6 @@ def print_launcher_reads(rows: list[dict]) -> None: ) -class ReportScope(TypedDict, total=False): - """What a cross_reference run compares against and answers for.""" - - all_declared: dict[str, list[tuple[int | None, str]]] | None - standalone_cores: set[str] | None - folded_slots: frozenset[str] - platform: str - launcher_layer: LauncherLayer | None - declared_contents: dict[str, set[str]] | None - - -def cross_reference( - profiles: dict[str, dict], - declared: dict[str, set[str]], - db: dict, - platform_data_dirs: dict[str, set[str]] | None = None, - data_names: set[str] | None = None, - **scope: Unpack[ReportScope], -) -> dict: - """Compare emulator profiles against platform declarations. - - Returns a report with gaps (files emulators need but platforms don't list) - and coverage stats. Each gap entry carries a ``source`` field indicating - where the file is available: ``"bios"`` (bios/ via database.json), - ``"data"`` (data/ directory), ``"large_file"`` (GitHub release asset), - or ``"missing"`` (not available anywhere). - - The boolean ``in_repo`` is derived: ``source != "missing"``. - - When *all_declared* is provided (every filename declared by any platform - for any system, with its sizes and slots), it is used for the ``in_platform`` check - instead of the per-system lookup. This is appropriate for the global - gap analysis page where "undeclared" means "no platform declares it at all". - """ - unknown = sorted(set(scope) - set(ReportScope.__annotations__)) - if unknown: - raise TypeError(f"cross_reference() got an unexpected keyword argument '{unknown[0]}'") - all_declared = scope.get("all_declared") - standalone_cores = scope.get("standalone_cores") - folded_slots = scope.get("folded_slots", frozenset()) - platform = scope.get("platform", "") - launcher_layer = scope.get("launcher_layer") - declared_contents = scope.get("declared_contents") - platform_data_dirs = platform_data_dirs or {} - by_name = db.get("indexes", {}).get("by_name", {}) - by_name_lower = {k.lower(): k for k in by_name} - by_md5 = db.get("indexes", {}).get("by_md5", {}) - by_crc32 = db.get("indexes", {}).get("by_crc32", {}) - by_sha256 = db.get("indexes", {}).get("by_sha256", {}) - by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {}) - db_files = db.get("files", {}) - report: dict[str, dict] = {} - - index = { - "by_name": by_name, - "by_name_lower": by_name_lower, - "by_md5": by_md5, - "by_crc32": by_crc32, - "by_sha256": by_sha256, - "by_path_suffix": by_path_suffix, - "db_files": db_files, - "data_names": data_names, - "all_declared": all_declared, - "folded_slots": folded_slots, - "declared_contents": declared_contents, - "bios_dir": db.get("bios_dir"), - "launcher_candidates": [] if launcher_layer else None, - } - for emu_name, profile in profiles.items(): - _cross_reference_profile( - emu_name, profile, declared, report, index, standalone_cores, - platform, - ) - if launcher_layer: - _settle_launcher_places(report, index["launcher_candidates"], launcher_layer, db) - - return report - - def print_report( report: dict, scope: str = "all emulators", show_clean: bool = False ) -> None: @@ -1724,7 +311,7 @@ def main() -> None: import contextlib - from refresh_data_dirs import hold_data_dirs + from packs.datadirs import hold_data_dirs # Files resolve against data/: the trees stay put until the process # ends, which releases the hold. diff --git a/scripts/dedup.py b/scripts/dedup.py index a03fe77da..14cdfbdb3 100644 --- a/scripts/dedup.py +++ b/scripts/dedup.py @@ -31,52 +31,10 @@ sys.path.insert(0, os.path.dirname(__file__)) from core.hashing import compute_hashes from core.cli import require_directory from core.artifacts import write_text_atomic +from model.nodedup import _in_nodedup_dir DEFAULT_BIOS_DIR = "bios" -# Directories where deduplication must NOT be applied. -NODEDUP_DIRS = { - "RPG Maker", - "ScummVM", - # A zoneinfo tree is addressed by zone name and its aliases are equal - # files by design: US/Samoa is Pacific/Midway. - "tzdata", - # VICE data is addressed by machine directory: C64, C64DTV and SCPU64 - # share one keymap, C64 and CBM-II one palette. With the copies removed - # the name step served the C128 keymap to all of them. - "c64-emu", - # PinMAME reads a sound-only parent (gts80s) as its own archive, equal - # byte for byte to the base set. Folding them into the clone map would - # key gts1.zip twice, once for MAME's set and once for PinMAME's. - "PinMAME", - # BBK dictionary ROMs are addressed by model directory, and the OS ROM - # the A4988 folder needs is the one the gam4980 core is given. - "BBK", - # Engine data trees read by path: one sound or one sprite sits under - # several characters, campaigns or episodes, and each copy is opened - # where it lies. - "C-Dogs SDL", - "Ikemen GO", - "Theme Hospital", - "TheXTech", - # Aleph One opens each scenario's Physics Models and the Splitwolf mod - # tree its sounds and maps by path: Marathon 2 and Infinity share one - # Standard.phyA, lwmp/ repeats 182 files across its levels. - "Bungie", - "splitwolf", - # CatacombGL reads each game's folder by name and compares sizes only: - # the Armageddon and Apocalypse intro shapes SHP1, SHP9 to SHP13 are the - # Abyss shareware bytes under the retail names, and each game opens - # its own copy. - "Softdisk", - # MAME's support trees (hash, plugins) are read by path as a whole, and - # two MAME versions share most of their software lists byte for byte. - "mame", - # The Tyrian 2.1 distribution ships netset.pcx and tyrset.pcx with the - # same bytes, and EmuELEC places both names under ports/opentyrian/. - "opentyrian", -} - def path_priority(path: str) -> tuple: """Lower score = better candidate to keep as canonical. @@ -90,11 +48,6 @@ def path_priority(path: str) -> tuple: return (is_variant, is_mame, is_arcade, len(parts), path) -def _in_nodedup_dir(path: str) -> bool: - parts = Path(path).parts - return any(nodedup in parts for nodedup in NODEDUP_DIRS) - - def _is_mame_dir(path: str) -> bool: """Check if a path is in a MAME-specific directory.""" parts = Path(path).parts diff --git a/scripts/export_native.py b/scripts/export_native.py index 709f881b3..f173d0846 100644 --- a/scripts/export_native.py +++ b/scripts/export_native.py @@ -136,7 +136,7 @@ def main() -> None: if not args.refresh_cache: import contextlib - from refresh_data_dirs import hold_data_dirs + from packs.datadirs import hold_data_dirs # Removal candidates are proved against data/: a refresh swapping a # tree mid-walk listed entries only that tree holds as removable. diff --git a/scripts/exporter/doubled.py b/scripts/exporter/doubled.py index 30d857160..8cfa9d076 100644 --- a/scripts/exporter/doubled.py +++ b/scripts/exporter/doubled.py @@ -19,7 +19,7 @@ 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.collisions import _accepted_by_all, _lists_hashes, find_collisions from resolve.validation import opens_by_name, outside_gap_scope diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 49c708d10..b22bd9198 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -19,39 +19,20 @@ import sys if sys.version_info < (3, 9): sys.exit(f"generate_pack.py needs Python 3.9 or newer, this is {sys.version.split()[0]}") -from collections.abc import Callable, Iterable, Iterator, Mapping +from collections.abc import Iterator -from core.artifacts import _build_timestamp, set_plain_mode import argparse import contextlib -import functools -import hashlib -import io import json import os -import re -import shutil -import tempfile -import zipfile -from pathlib import Path, PurePosixPath -from dataclasses import dataclass, field -from typing import TYPE_CHECKING, TypedDict +from pathlib import Path +from dataclasses import dataclass +from typing import TYPE_CHECKING sys.path.insert(0, os.path.dirname(__file__)) -from model.alternatives import core_file_spares, settle_sets, slot_set_keys from resolve.cores import resolve_platform_cores as _platform_cores -from model.declarations import ROMS_ROOT, OUTER_ROOTS, outer_layout -from resolve.layout import core_system_dirs -from resolve.contentlayout import TARGET_KEY, _core_key, content_folder_boards from model.profiles import ( - installed_data_refs, - 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, @@ -61,24 +42,15 @@ from model.cliargs import ( print_platform_listing, list_system_ids, ) -from core.cli import require_directory, suggest_names +from core.cli import require_directory 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, artifact_lock, @@ -86,16 +58,10 @@ from core.artifacts import ( ArtifactLockBusy, ) 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, platform_scope_systems, system_scope_error, without_profile_blind, - downloadable_on, - downloaded_only_profiles, - system_core_reach, ) from resolve.grouping import group_identical_platforms from model.registry import ( @@ -106,2865 +72,64 @@ from model.registry import ( 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 REPO_ROOT, sanitize_pack_path -import packresolve -from refresh_data_dirs import cache_lock, hold_data_dirs +from resolve import packfiles as packresolve +from packs.datadirs import hold_data_dirs from model import region -from resolve import regions as resolve_regions -from manifestselect import SelectionIndex -from resolve import slot as slot_mod -import slots -import split_pack -from resolve.gamedata import ( - GAME_DATA, - GameDataCut, - is_game_data, - platform_game_data, - without_game_data, -) -from core.deterministic_zip import _FIXED_DATE_TIME -from model.largefiles import asset_name, load_registered_paths, published_asset_name -from resolve.nativemode import digest_algorithm, hash_mismatch_excludes_file, reads_file_contents -from resolve.validation import ( - baseline_verdict, - existence_discrepancy, - destination_owners, - validated_choice, - agnostic_substitute, - _build_validation_index, - _parse_validation, - deliverable, - read_from_system_dir, - with_archive_members, - extra_alternatives, -) -from packpaths import ( - MEDIA_MARKER, - lands_on_android, - _archive_destination, - _has_path_conflict, - _register_path, - _flat, - _resolve_destination, - placement_block, - save_layout, -) -from packextras import ( - ExtraResolver, - extra_full_destination, - extra_region_key, - prefixed_destination, - save_entry_fields, - save_manifest_dest, - _detect_extras_prefix, - _collect_emulator_extras, - _extra_system_ids, - extras_for_systems as _extras_for_systems, - platform_region_groups, - emulator_region_drops, - emulator_required_spares, +from packs.extras import ( _emulator_region_group as _emulator_region_group, - expand_agnostic_entries, - undeclared_report, ) -from packreadme import ( - _build_readme, - _build_agnostic_rename_readme, - save_place, -) -from packverify import ( +from packs.integrity import ( _check_member_hash as _check_member_hash, _hash_matches as _hash_matches, _intentional_hash_exclusion as _intentional_hash_exclusion, verify_pack_against_platform, - verify_pack, - generate_sha256sums, ) # _OFFLINE is deliberately not re-exported: importing a value copies it, so a # facade name would keep saying False after set_offline() changed the flag. -from packresolve import ( +from resolve.packfiles import ( ACCEPTED_HASHES, - sha1_for_hash, - preferred_entries as _preferred_entries, parse_hash_input, parse_hash_file, lookup_hashes, - resolve_declaration, - resolve_file, - download_external, ) if TYPE_CHECKING: - from typing_extensions import Unpack + pass +from packs.archive import DamagedArchiveError +from packs.bysystem import generate_split_packs +from packs.datatrees import _MISSING_DATA_DIRS +from packs.emulatorpack import generate_emulator_pack, generate_system_pack +from packs.finalize import _baseline_shortfall, verify_and_finalize_packs +from packs.manifest import generate_install_list, generate_manifest +from packs.md5pack import generate_md5_pack +from packs.naming import ( + _expected_pack_names, + _narrowings, + _pack_variant, + _platform_pack_stem, + _platform_target, + _system_tag, +) +from packs.platformpack import generate_pack +from packs.scope import pack_systems, platform_list_version +from packs.standalone import STANDALONE_DIR, _standalone_copies +from packs.targets import generate_target_manifests, target_list -if TYPE_CHECKING: - # How a manifest settles a platform declaration: the copy served, or None - # and why not. - _Settle = Callable[[dict, str, str, "str | None"], "tuple[str | None, str]"] - -if TYPE_CHECKING: - # What a destination came to: its entries, whether it was filled, and the - # report to make if no other member of its set fills it. - _Outcome = tuple[list[dict], bool, "Callable[[], None] | None"] yaml = require_yaml() DEFAULT_PLATFORMS_DIR = "platforms" -def _reject_unknown(function: str, options: Mapping[str, object], known: frozenset[str]) -> None: - """Refuse a keyword the options do not declare, as a named parameter would.""" - for key in options: - if key not in known: - raise TypeError(f"{function}() got an unexpected keyword argument '{key}'") - - DEFAULT_DB_FILE = "database.json" DEFAULT_OUTPUT_DIR = "dist" DEFAULT_BIOS_DIR = "bios" - -# Formats that are already compressed: deflating them again took 28 s of the -# RetroArch build for 2.1 GB of members and saved 9.6 MB (0.45 %), 16 GB and -# about 72 MB across all packs. Measured per extension on the 2026-10-20 -# packs; .pk3 (3 %), .jpg (6 %), .avi (44 %) and .jar (60 %) still shrink -# and stay deflated. Chosen by name alone, so a pack stays a function of its -# inputs. -_STORED_EXTENSIONS = frozenset({".7z", ".chd", ".ogg", ".pk4", ".png", ".zip"}) - - -def _member_compression(arcname: str) -> int: - """ZIP_STORED for a member whose format is already compressed.""" - if os.path.splitext(arcname)[1].lower() in _STORED_EXTENSIONS: - return zipfile.ZIP_STORED - return zipfile.ZIP_DEFLATED - - -class PackRecord: - """A pack build kept in memory: the paths it writes, no archive. - - ``members`` is every path written, ``files`` the ones the build counts as - the profile's files (archives and loose files, not trees or notes), and - ``trees`` the members a platform pack takes from its data directories. - The pipeline builds every emulator pack and every narrowed platform pack - this way and compares them with what verify credits, without reading or - compressing a byte. - """ - - def __init__(self) -> None: - self.members: list[str] = [] - self.files: list[str] = [] - self.trees: list[str] = [] - # The collection file each copied member comes from: a split part - # writes a file only where the full pack writes the same bytes. - self.sources: dict[str, str] = {} - - -def _add_pack_member( - zf: zipfile.ZipFile | PackRecord, source_path: str, arcname: str -) -> None: - """Add a file to the pack with metadata that does not depend on the build. - - ZipFile.write copies the source file's mtime into the member. For a file - this build just produced in tmp/ that is the wall clock, and for a file - from the collection it is whenever the clone was checked out, so a pack - rebuilt from identical inputs differed from the last one although every - byte of content matched: 348 members of the Recalbox pack moved between - two consecutive builds. The content is streamed rather than read whole, - because some members are firmware images of several hundred megabytes. - """ - if isinstance(zf, PackRecord): - zf.members.append(arcname) - zf.sources[arcname] = source_path - return - info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME) - info.compress_type = _member_compression(arcname) - # The executable bit is the one permission worth carrying: the RetroDECK - # pack ships the two Voxatron engine binaries, and a user who extracts - # them at 644 cannot run them. Git records the bit, so reading it from - # the source keeps the pack the same from any clone. Nothing else about - # the source's mode reaches the archive. - stat_result = os.stat(source_path) - mode = 0o755 if stat_result.st_mode & 0o111 else 0o644 - info.external_attr = (0o100000 | mode) << 16 - size = stat_result.st_size - info.file_size = size - with open(source_path, "rb") as source, zf.open( - info, "w", force_zip64=size >= 1 << 31 - ) as target: - shutil.copyfileobj(source, target, 1024 * 1024) - - -def _write_generated_member( - zf: zipfile.ZipFile | PackRecord, arcname: str, text: str -) -> None: - """Write a pack member the builder composes rather than copies. - - READMEs, instruction notes and the manifest are produced at build time, - so writestr would stamp them with the wall clock and give the same pack - a different hash on every run. Pinning them to the epoch the archive - rebuilder already uses makes a pack a function of its inputs alone. - """ - if isinstance(zf, PackRecord): - zf.members.append(arcname) - return - info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME) - info.compress_type = zipfile.ZIP_DEFLATED - info.external_attr = 0o100644 << 16 - zf.writestr(info, text) - - -def _narrowings( - source: str, - regions: list[str] | None, - target_name: str | None, - one_per_slot: bool, - required_only: bool, - standalone: bool = False, - no_game_data: bool = False, -) -> list[tuple[str, str]]: - """Every dimension that narrows a pack, as (filename tag, plain label). - - The pack name and the pack README are both built from this list, so a new - way of narrowing a pack cannot reach users nameless or unannounced. Order - is the filename order and must not change: it is what existing archives - are called. - """ - applied: list[tuple[str, str]] = [] - if source == "platform": - applied.append(("_Platform", "only what the platform declares")) - elif source == "truth": - applied.append(("_Truth", "only what emulator profiles require")) - if regions: - pretty = ", ".join( - " ".join(w.title() for w in slug.split("-")) for slug in regions - ) - applied.append( - (f"_{region.region_tag(regions)}", f"region priority {pretty}") - ) - if target_name: - applied.append( - (f"_{_target_tag(target_name)}", f"cores available on {target_name}") - ) - if one_per_slot: - applied.append(("_OnePerSlot", "one BIOS per system and region")) - if standalone: - applied.append(("_Standalone", "standalone mode files only")) - if required_only: - applied.append(("_Required", "required files only")) - if no_game_data: - applied.append(("_NoGameData", "firmware only, game data left out")) - return applied - - -@contextlib.contextmanager -def _writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]: - """A pack written beside its final name, swapped in once complete. - - Opened on the final name, a rebuild truncated the previous pack at once, - and a build that raised half way still wrote a central directory: a - readable ZIP holding part of the files, which the run then checked and - summed as the pack. - """ - directory = os.path.dirname(zip_path) or "." - fd, scratch = tempfile.mkstemp( - prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory - ) - os.close(fd) - try: - with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as zf: - yield zf - set_plain_mode(scratch) - os.replace(scratch, zip_path) - except BaseException: - Path(scratch).unlink(missing_ok=True) - raise - - -def _target_tag(target_name: str) -> str: - """Filename tag for a hardware target. - - Without it a targeted pack takes the same name as the full one and - overwrites it. - """ - return "".join( - part.title() for part in re.split(r"[-_\s]+", target_name.strip()) if part - ) - - -def _platform_target( - platform_name: str, target: str | None, platforms_dir: str -) -> str | None: - """The target as this platform files it, the name its artifacts carry. - - Named once for the whole run, a target two platforms file differently - (rpi4: Batocera's bcm2711, Recalbox's rpi4_64) kept the typed name under - --all and took the platform's own under --platform, so --verify-packs - looked for a pack the --all build had named otherwise. A platform that - does not file the target is packed whole under --all, and its name - claims no narrowing: BizHawk_..._Switch_BIOS_Pack.zip was the full pack. - """ - if not target or not platform_files_target(platform_name, target, platforms_dir): - return None - return canonical_target_name([platform_name], target, platforms_dir) - - -def _system_tag(system_filter: list[str] | None) -> str: - """Filename tag for a pack limited to some systems, empty for all.""" - if not system_filter: - return "" - display_parts = [] - for sid in system_filter: - s = sid.lower().replace("_", "-") - for prefix in MANUFACTURER_PREFIXES: - if s.startswith(prefix): - s = s[len(prefix) :] - break - display_parts.append("_".join(p.title() for p in s.split("-") if p)) - return "_" + _bounded_join(display_parts, system_filter) - - -# A system list long enough to push a pack name past this falls back to the -# first system, a count and a digest of the list. -MAX_SYSTEM_TAG_BYTES = 120 - - -def _bounded_join(parts: list[str], keys: list[str]) -> str: - """Parts joined while they fit, else the first, a count and a digest. - - Thirty systems joined made a 261-byte file name and the ZIP could not - be opened. The digest keeps two different selections apart. The joiner - is one no part holds: with "_", sega-dreamcast + arcade and - sega-dreamcast-arcade both named Dreamcast_Arcade, and the second build - replaced the first. - """ - joined = "+".join(parts) - if len(joined.encode("utf-8")) <= MAX_SYSTEM_TAG_BYTES: - return joined - digest = hashlib.sha1("\n".join(sorted(keys)).encode("utf-8")).hexdigest()[:8] - return f"{parts[0]}_and_{len(parts) - 1}_more_{digest}" - - -_UNSAFE_IN_NAME = re.compile(r'[/\\:*?"<>|]') - - -def _name_part(text: str, space: str = "") -> str: - """A display name made safe to stand in a file name. - - 'FinalBurn Neo (CPS-1/CPS-2)' named a directory that did not exist, and a - Windows user cannot write ':' or '?' either. - """ - return _UNSAFE_IN_NAME.sub("-", text.replace(" ", space)) - - -def _platform_pack_stem( - group_platforms: list[str], representative: str, platforms_dir: str -) -> str: - """Platform part of a pack name, version included. - - A group of identical platforms shares one pack named after all of them, - and the builder and --verify-packs both read the name from here. - """ - rep_cfg = load_platform_config(representative, platforms_dir) - version = rep_cfg.get("version", rep_cfg.get("dat_version", "")) - version_tag = f"_{_name_part(str(version))}" if version else "" - return platform_pack_prefix(group_platforms, representative, platforms_dir) + version_tag - - -def platform_pack_prefix( - group_platforms: list[str], representative: str, platforms_dir: str -) -> str: - """Platform part of a pack name without the version. - - The site reads a pack's version back by removing this prefix: a version - may hold an underscore (AmberELEC prerelease-20261019_1835). - """ - if len(group_platforms) <= 1: - rep_cfg = load_platform_config(representative, platforms_dir) - return _name_part(rep_cfg.get("platform", representative), "_") - names = [ - load_platform_config(p, platforms_dir).get("platform", p) - for p in group_platforms - ] - return "_".join(_name_part(n) for n in names) - - -def platform_list_version(config: dict, platform: str) -> str: - """The version of the list a platform's YAML transcribes: the release - tag the scraper read, or for a list kept on a branch with no release, - the date of the commit it pinned. load_platform_config never passes a - parent's version to a child, Lakka is not RetroArch v1.22.2. - - The installer compares it with the version a machine runs, so a missing - value is refused rather than written as a stand-in. - """ - version = str(config.get("version") or "").strip() - if not version: - raise ValueError( - f"{platform}: the platform YAML records no version of its own" - ) - return version - - -# What the builder writes into a platform pack beside the files it carries. -PACK_DOCUMENTS = ("README.txt", "manifest.json") - - -def pack_markers( - platform_name: str, target_name: str | None, platforms_dir: str -) -> 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 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 () - - -def core_data_trees( - config: dict, - profiles: dict[str, dict], - platform_name: str, - data_registry: dict | None, - target_cores: set[str] | None = None, -) -> list[dict]: - """The data directories the platform's cores read, as tree references. - - A profile's ``data_directories`` reach the pack of every platform that - runs the core as a libretro core, below the system directory it hands - the core (and the build's own folder, ``pack_structure``), as the - emulator pack lays them out. Left out: a tree the platform's package - installs, for this core or another reading the same tree - (``installed_data_refs``), one the build bundles or the platform never - opens (``deliverable``), and one whose registry entry names the - platforms it serves (``for_platforms``) without this one. A standalone build reads its data below its own folder, which a - tree's destination does not describe, so its trees stay out, as does a - tree read beside the content (``load_from``). - - Each reference carries the profile's systems (``source_systems``, as a - core extra does), which --system and --split narrow on. - """ - if not data_registry: - return [] - installed = installed_data_refs(platform_name) - handed = standalone_set(config) - # Relative to base_destination, which the members are written under. A - # platform with none writes its BIOS folder into every destination, and - # the trees go there as the core extras do. - root = declared_root(config) - trees: list[dict] = [] - seen: dict[tuple[str, str], int] = {} - for core in sorted(_platform_cores(config, profiles, target_cores)): - profile = profiles[core] - if all(standalone for _view, standalone in platform_layouts(core, profile, handed)): - continue - declared = [t for t in profile.get("data_directories") or [] if isinstance(t, dict)] - directories = core_system_dirs(core, profile, handed) - structure = str((profile.get("pack_structure") or {}).get("libretro") or "") - for tree in deliverable(declared, False, platform_name): - if not read_from_system_dir(tree): - continue - ref = str(tree.get("ref") or "") - entry = data_registry.get(ref) - if entry is None or ref in installed: - continue - allowed = entry.get("for_platforms") - if allowed and platform_name not in allowed: - continue - for directory in [""] if directories is None else directories: - destination = prefixed_destination("/".join( - part.strip("/") - for part in (directory, structure, str(tree.get("destination") or "")) - if part.strip("/") - ), root) or root - if (ref, destination) in seen: - # One tree, read by a second core: the manifest says both - # (tree_readers), the pack writes it once. - first = trees[seen[(ref, destination)]] - if core not in first["readers"]: - first["readers"].append(core) - continue - seen[(ref, destination)] = len(trees) - trees.append({ - "ref": ref, - "destination": destination, - "required": tree.get("required"), - "core": core, - "readers": [core], - "source_systems": entry_system_ids(tree, profile), - }) - return trees - - -def _in_data_cache(path: str, data_registry: dict | None) -> bool: - """Whether a resolved file lies in one of the data directory caches.""" - real = os.path.realpath(path) - return any( - real.startswith(os.path.realpath(entry["local_cache"]) + os.sep) - for entry in (data_registry or {}).values() - if entry.get("local_cache") - ) - - -def _tree_references( - pack_systems: dict, core_trees: Iterable[dict], -) -> Iterator[tuple[tuple[str, ...], dict]]: - """(systems, reference) for each tree a pack carries: those its systems - declare, then those its cores read.""" - for sys_id, system in sorted(pack_systems.items()): - for dd in system.get("data_directories", []): - yield (sys_id,), dd - for tree in core_trees: - yield tuple(tree["source_systems"]), tree - - -class _TreeWalkOptions(TypedDict, total=False): - """The keyword options of _data_directory_members.""" - - refs_out: dict | None - required_only: bool - core_trees: Iterable[dict] - reclaim: dict[str, str] | None - - -def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> str | None: - """The cache folder of a tree reference the pack carries, or None.""" - ref_key = dd.get("ref", "") - if not ref_key or not data_registry or ref_key not in data_registry: - return None - if ref_key in installed_data_refs(platform_name): - return None - entry = data_registry[ref_key] - allowed = entry.get("for_platforms") - if allowed and platform_name not in allowed: - return None - local_path = entry.get("local_cache", "") - if not local_path or not os.path.isdir(local_path): - print( - f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)" - ) - _MISSING_DATA_DIRS.add(ref_key) - return None - return local_path - - -def _tree_files(local_path: str, dd_prefix: str) -> Iterator[tuple[str, str]]: - """(source, destination) of every file of a cached tree.""" - for root, _dirs, filenames in os.walk(local_path): - for fname in filenames: - src = os.path.join(root, fname) - rel = os.path.relpath(src, local_path) - yield src, f"{dd_prefix}/{rel}" if dd_prefix else rel - - -def _data_directory_members( - pack_systems: dict, - data_registry: dict | None, - platform_name: str, - base_dest: str, - case_insensitive: bool, - seen_destinations: set, - seen_lower: set, - seen_parents: set, - **options: Unpack[_TreeWalkOptions], -) -> Iterator[tuple[str, str]]: - """Yield (source, destination) for the cached data directories a - platform's systems declare, then those its cores read (``core_trees``, - from core_data_trees). - - ``reclaim`` maps a destination already taken to the cache file it was - resolved to: the manifest found the platform's entry there and cannot - list it as a file, so the tree yields it once more and the installer - gets it from the tree's archive. - - ``refs_out``, when given, maps each yielded destination to - (registry key, system ids, directory destination, whether the core - needs the tree), for the manifest. - - These are not BIOS and carry no hash of their own: they are whole - trees an emulator reads, refreshed from upstream, so what ships is - whatever the cache holds. The pack and the install manifest both read - this, the first to write the files and the second to count them. - ``required_only`` leaves out a tree declared ``required: false``, one the - core runs without, as it leaves out such a file. - """ - _reject_unknown("_data_directory_members", options, _TreeWalkOptions.__optional_keys__) - refs_out = options.get("refs_out") - reclaim = options.get("reclaim") - required_only = options.get("required_only", False) - core_trees = options.get("core_trees", ()) - # Data directories from _data_dirs.yml - for systems, dd in _tree_references(pack_systems, core_trees): - needed = dd.get("required") is not False - if required_only and not needed: - continue - local_path = _carried_tree(dd, data_registry, platform_name) - if local_path is None: - continue - ref_key = dd.get("ref", "") - dd_dest = dd.get("destination", "") - dd_prefix = f"{base_dest}/{dd_dest}" if base_dest and dd_dest else base_dest or dd_dest - # Held while the caller writes what is yielded: a refresh swapping - # the tree waits until the walk is done. - with cache_lock(local_path, shared=True): - for src, full in _tree_files(local_path, dd_prefix): - if reclaim and full in reclaim and ( - os.path.normpath(reclaim[full]) == os.path.normpath(src) - ): - del reclaim[full] - elif full in seen_destinations or ( - full.lower() in seen_lower and case_insensitive - ) or _has_path_conflict(full, seen_destinations, seen_parents): - continue - else: - seen_destinations.add(full) - _register_path(full, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(full.lower()) - if refs_out is not None: - refs_out[full] = (ref_key, systems, dd_prefix, needed) - yield src, full - - -def _case_twin_pairs( - twins: list[str], seen_destinations: set[str], base_dest: str, flatten: bool, -) -> list[tuple[str, str]]: - """Each spelling left out, with the spelling the pack holds.""" - held = { - _flat(dest, base_dest, flatten).lower(): _flat(dest, base_dest, flatten) - for dest in seen_destinations - } - return sorted({(twin, held[twin.lower()]) for twin in twins if twin.lower() in held}) - - -def _report_pack_counts( - zip_path: str, - file_status: dict, - total_files: int, - core_count: int, - source: str, - verification_mode: str, - tree_count: int = 0, -) -> None: - """Print the line the pipeline's consistency check reads. - - The check compares these counts against what verify.py reports for - the same platform, so the wording is a contract: parse_pack_counts - in pipeline.py matches on it. - """ - files_ok = sum(1 for s in file_status.values() if s == "ok") - files_untested = sum(1 for s in file_status.values() if s == "untested") - files_excluded = sum(1 for s in file_status.values() if s == "excluded") - files_miss = sum(1 for s in file_status.values() if s == "missing") - total_checked = len(file_status) - - parts = [f"{files_ok}/{total_checked} files OK"] - if files_untested: - parts.append(f"{files_untested} untested") - if files_excluded: - parts.append(f"{files_excluded} unsafe excluded") - if files_miss: - parts.append(f"{files_miss} missing") - if source == "platform": - print( - f" {zip_path}: {total_files} files packed (platform baseline only), " - f"{', '.join(parts)} [{verification_mode}]" - ) - elif source == "truth": - print( - f" {zip_path}: {total_files} files packed (ground truth only), " - f"{core_count} from emulator profiles [{verification_mode}]" - ) - else: - baseline = total_files - core_count - tree_count - trees = f"{tree_count} in core data trees + " if tree_count else "" - print( - f" {zip_path}: {total_files} files packed ({baseline} baseline + " - f"{trees}{core_count} from cores), {', '.join(parts)} [{verification_mode}]" - ) - -class _VariantOptions(TypedDict, total=False): - """The keyword options of _select_variants.""" - - regions: list[str] | None - one_per_slot: bool - required_only: bool - undeclared: list[dict] | None - zip_contents: dict | None - data_registry: dict | None - slot_overrides: dict[str, str] | None - - -def _select_variants( - config: dict, - pack_systems: dict, - emulators_dir: str, - db: dict, - base_dest: str, - emu_profiles: dict | None, - target_cores: set[str] | None, - source: str, - **options: Unpack[_VariantOptions], -) -> tuple[set, list, list]: - """Which regional and slot alternatives this pack leaves out. - - Both reductions are decided once, over the platform baseline and the - core extras together: deciding them separately is how the report and - the pack came to withdraw different files for the same request. - Returns the destinations to drop, the groups kept only as a - fallback, and the slots no profile puts in order. - """ - _reject_unknown("_select_variants", options, _VariantOptions.__optional_keys__) - regions = options.get("regions") - one_per_slot = options.get("one_per_slot", False) - region_drops: set[str] = set() - region_fallbacks: list[str] = [] - # One grouping for both passes: a file judged in its own system by one - # pass must not land in every system of its profile for the other. - region_groups: dict[str, list[tuple[str, str]]] = {} - held: set[str] = set() - if regions or one_per_slot: - region_groups, _extra_dests = platform_region_groups( - config, - pack_systems, - emulators_dir, - db, - base_dest, - emu_profiles, - target_cores=target_cores, - include_extras=(source != "platform"), - include_all=(source == "truth"), - required_only=options.get("required_only", False), - held_out=held, - undeclared=options.get("undeclared"), - zip_contents=options.get("zip_contents"), - data_registry=options.get("data_registry"), - slot_overrides=options.get("slot_overrides"), - ) - if regions: - region_index = resolve_regions.platform_region_index( - config, emu_profiles or {}, target_cores - ) - region_drops = resolve_regions.resolve_region_drops( - region_groups, region_index, regions, held - ) - region_fallbacks = resolve_regions.fallback_groups( - region_groups, region_index, regions - ) - - slot_undecidable: list[str] = [] - if one_per_slot: - slot_drops, slot_undecidable = _slot_drops( - config, emu_profiles, target_cores, region_groups, region_drops, held - ) - region_drops = region_drops | slot_drops - if slot_undecidable: - print( - f" {len(slot_undecidable)} slot(s) with no declared order: " - f"every candidate kept" - ) - - return region_drops, region_fallbacks, slot_undecidable - - -def _slot_drops( - config: dict, - emu_profiles: dict | None, - target_cores: set[str] | None, - region_groups: dict[str, list[tuple[str, str]]], - region_drops: set[str], - held: set[str], -) -> tuple[set[str], list[str]]: - """What --one-per-slot withdraws once the regions have, and the slots no - declared order decides. The pack and the manifest both read it.""" - slot_groups = { - sys_id: [(d, n) for d, n in members if d not in region_drops] - for sys_id, members in region_groups.items() - } - return slot_mod.resolve_slot_drops( - slot_groups, - slot_mod.platform_slot_index(config, emu_profiles or {}, target_cores), - held, - ) - - -def _platform_pack_name( - platform_name: str, - platforms_dir: str, - narrowings: list[tuple[str, str]], - system_filter: list[str] | None, - pack_name: str | None = None, -) -> str: - """File name of a platform pack: stem, narrowing tags, system tag. - - A caller naming the pack itself (a --split part) is taken at its word. - """ - if pack_name: - return pack_name - stem = _platform_pack_stem([platform_name], platform_name, platforms_dir) - tags = "".join(tag for tag, _label in narrowings) - return f"{stem}{tags}_BIOS_Pack{_system_tag(system_filter)}.zip" - - -def _matches_an_alternative(fe: dict, local_path: str, profiles: dict) -> bool: - """Whether the copy is another version the same profile accepts there. - - A profile lists every version its code takes under one name (each GRP - of Raze's table, eduke32's demo and retail NWINTER.GRP). The extra - carries the first, and the held copy matching a sibling is no mismatch. - """ - siblings = extra_alternatives(fe, profiles) - if len(siblings) < 2: - return False - # A sibling the code takes without a check (Raze's "BLOOD: Unknown - # Version") accepts whatever copy fills the slot. - if any(not _parse_validation(entry.get("validation")) for entry in siblings): - return True - actual = compute_hashes(local_path, frozenset({"sha1", "md5", "crc32"})) - for entry in siblings: - for algorithm in ("sha1", "md5", "crc32"): - declared = entry.get(algorithm) - values = declared if isinstance(declared, list) else [declared] - if any(v and str(v).lower() == actual.get(algorithm, "") for v in values): - return True - return False - - -def _report_left_out(cut: GameDataCut, systems: set[str], cores: bool) -> None: - """Name the game data a --no-game-data build left out, and why. - - ``systems`` limits the platform layer to the systems this pack covers, - and ``cores`` says whether this pack collected the core files itself: - a split part does not, its run names them once. - """ - kept = [ - item for item in cut.left_out - if (item.layer == "platform" and item.system in systems) - or (item.layer == "core" and cores) - ] - for line in GameDataCut(cut.config, cut.profiles, kept).report_lines(): - print(f" {line}") - - -class PackNarrowing(TypedDict, total=False): - """How a platform pack is narrowed, shared by a pack and its split parts.""" - - emulators_dir: str - zip_contents: dict | None - data_registry: dict | None - emu_profiles: dict | None - target_cores: set[str] | None - required_only: bool - source: str - regions: list[str] | None - target_name: str | None - one_per_slot: bool - offline: bool | None - no_game_data: bool - - -class _PartScope(TypedDict, total=False): - """What one split part keeps of the platform.""" - - system_filter: list[str] | None - precomputed_extras: list[dict] | None - extras_only: bool - - -class PackOptions(PackNarrowing, _PartScope, total=False): - """The keyword options of generate_pack.""" - - flatten: bool - pack_name: str | None - record: PackRecord | None - within: dict[str, str] | None - - -@dataclass(frozen=True) -class _PackSettings: - """PackOptions with their defaults.""" - - emulators_dir: str = "emulators" - zip_contents: dict | None = None - data_registry: dict | None = None - emu_profiles: dict | None = None - target_cores: set[str] | None = None - required_only: bool = False - system_filter: list[str] | None = None - precomputed_extras: list[dict] | None = None - extras_only: bool = False - source: str = "full" - flatten: bool = True - regions: list[str] | None = None - target_name: str | None = None - one_per_slot: bool = False - offline: bool | None = None - pack_name: str | None = None - no_game_data: bool = False - record: PackRecord | None = None - within: dict[str, str] | None = None - - -@dataclass -class _Placed: - """The destinations a build has taken, and the folders they open. - - ``fold`` is whether a case twin of a taken path counts as taken. - """ - - fold: bool - destinations: set[str] = field(default_factory=set) - lower: set[str] = field(default_factory=set) # only used when fold=True - parents: set[str] = field(default_factory=set) # parent dirs of added files (path conflict detection) - - def take(self, dest: str) -> None: - self.destinations.add(dest) - _register_path(dest, self.destinations, self.parents) - if self.fold: - self.lower.add(dest.lower()) - - def holds(self, dest: str) -> bool: - return dest in self.destinations or (self.fold and dest.lower() in self.lower) - - def conflicts(self, dest: str) -> bool: - return _has_path_conflict(dest, self.destinations, self.parents) - - def block(self, dest: str) -> str | None: - return placement_block(dest, self.destinations, self.lower, self.parents, self.fold) - - -@dataclass -class _PlatformPlan: - """What a platform pack is built from, settled before its first member.""" - - platform_name: str - platforms_dir: str - db: dict - bios_dir: str - opts: _PackSettings - config: dict - emu_profiles: dict - zip_contents: dict - cut: GameDataCut | None - narrowings: list[tuple[str, str]] - zip_path: str - validation_index: dict - platform_profiles: dict[str, dict] - validation_owners: dict - slot_overrides: dict[str, str] - pack_systems: dict - preferred_entries: dict[str, int] = field(default_factory=dict) - undeclared: list[dict] | None = None - region_drops: set[str] = field(default_factory=set) - region_fallbacks: list = field(default_factory=list) - slot_undecidable: list[str] = field(default_factory=list) - - @property - def verification_mode(self) -> str: - return self.config.get("verification_mode", "existence") - - @property - def platform_display(self) -> str: - return self.config.get("platform", self.platform_name) - - @property - def base_dest(self) -> str: - return self.config.get("base_destination", "") - - @property - def case_insensitive(self) -> bool: - # Case-insensitive dedup only for platforms targeting Windows/macOS. - # Linux-only platforms (Batocera, Recalbox, RetroDECK, Lakka, RomM) - # are case-sensitive and may have distinct files like DISK.ROM vs disk.rom. - return self.config.get("case_insensitive_fs", False) - - -def _plan_platform_pack( - platform_name: str, - platforms_dir: str, - db: dict, - bios_dir: str, - output_dir: str, - opts: _PackSettings, -) -> _PlatformPlan | None: - """The configuration, scope and checks a platform pack reads, or None - when the systems asked for leave nothing to build.""" - config = load_platform_config(platform_name, platforms_dir) - if opts.target_name: - config = {**config, TARGET_KEY: opts.target_name} - zip_contents = {} if opts.zip_contents is None else opts.zip_contents - emu_profiles = opts.emu_profiles - if emu_profiles is None: - # The pipeline always passes them, but a caller that does not must get the - # same pack, not one built without validation, slots or agnostic cores. - emu_profiles = load_emulator_profiles(opts.emulators_dir) - # Cut from the full config and profiles: the category of a platform - # entry is read from the profiles' game data entries. - cut = ( - without_game_data(config, emu_profiles, opts.data_registry, opts.target_cores) - if opts.no_game_data else None - ) - if cut is not None: - config, emu_profiles = cut.config, cut.profiles - - narrowings = _narrowings( - opts.source, opts.regions, opts.target_name, opts.one_per_slot, opts.required_only, - no_game_data=opts.no_game_data, - ) - zip_path = os.path.join( - output_dir, - _platform_pack_name( - platform_name, platforms_dir, narrowings, opts.system_filter, opts.pack_name - ), - ) - if opts.record is None: - os.makedirs(output_dir, exist_ok=True) - - # Build emulator-level validation index from the platform's own - # emulators (same scope as verify.py) - from resolve.cores import resolve_platform_cores - - validation_index = {} - platform_profiles: dict[str, dict] = {} - if emu_profiles: - platform_profiles = { - name: emu_profiles[name] - for name in resolve_platform_cores(config, emu_profiles) - } - validation_index = _build_validation_index(platform_profiles) - validation_owners = destination_owners(platform_profiles) - slot_overrides = slots.pack_overrides( - config, emu_profiles or {}, db, zip_contents, opts.data_registry, - target_cores=opts.target_cores, source=opts.source, - ) - - pack_systems = platform_scope_systems( - config, emu_profiles or {}, opts.target_cores, opts.system_filter - ) - if opts.system_filter and not pack_systems: - reason = system_scope_error(config, platform_name, opts.system_filter, opts.target_name) - print(f" WARNING: {reason}") - return None - if opts.extras_only: - # The part of a split that carries the core extras no platform system - # owns: the platform's own files and trees went to the other parts. - pack_systems = {} - - plan = _PlatformPlan( - platform_name, platforms_dir, db, bios_dir, opts, config, emu_profiles, - zip_contents, cut, narrowings, zip_path, validation_index, platform_profiles, - validation_owners, slot_overrides, pack_systems, - ) - _settle_pack_choices(plan) - return plan - - -def _settle_pack_choices(plan: _PlatformPlan) -> None: - """The declaration each destination takes and the variants left out.""" - opts = plan.opts - if opts.source != "truth": - # Decided among the declarations this pack keeps: a preferred entry - # that --required-only drops must not silence its required twin, or - # the destination leaves the pack without a trace (RetroDECK's four - # Atari 5200 ROMs, optional under atari-400-800 and required under - # atari-5200). No data directories: the choice is about the baseline. - plan.preferred_entries = _preferred_entries( - plan.pack_systems, plan.db, plan.bios_dir, plan.base_dest, opts.required_only, - plan.zip_contents, opts.offline, - ) - - # Region selection is decided once, over both the platform baseline and the - # core extras, so the two phases below consult a single set. Grouping uses a - # dedicated extras pass with an empty seen set: it only needs group - # membership, never destinations, and a superset of members is the safe - # direction. Runs only when --region is given. - # The gap report both extras passes read, computed once: the region - # grouping and the core complement below ask it the same question. - plan.undeclared = ( - undeclared_report( - plan.config, opts.emulators_dir, plan.db, plan.emu_profiles, opts.target_cores, - include_all=(opts.source == "truth"), - ) - if opts.source != "platform" and opts.precomputed_extras is None - else None - ) - plan.region_drops, plan.region_fallbacks, plan.slot_undecidable = _select_variants( - plan.config, plan.pack_systems, opts.emulators_dir, plan.db, plan.base_dest, - plan.emu_profiles, opts.target_cores, opts.source, regions=opts.regions, - one_per_slot=opts.one_per_slot, required_only=opts.required_only, - undeclared=plan.undeclared, zip_contents=plan.zip_contents, - data_registry=opts.data_registry, slot_overrides=plan.slot_overrides, - ) - - -_STATUS_LABELS = {"untested": "UNTESTED", "excluded": "EXCLUDED", "missing": "MISSING"} - - -@dataclass -class _PlatformPackBuild: - """One platform pack being written: its members and what each slot came to. - - The four lookups are bound by generate_pack, the one place that says how - a platform file and a core extra are found and judged. - """ - - plan: _PlatformPlan - zf: zipfile.ZipFile | PackRecord - resolve: Callable[[dict, str], tuple[str | None, str]] - verdict: Callable[[dict, str | None, str], tuple[str, str | None]] - judge: Callable[[dict, str | None, str], tuple[str | None, str | None]] - resolve_extra: Callable[[dict, str], tuple[str | None, str, str]] - placed: _Placed = field(init=False) - total_files: int = 0 - core_count: int = 0 - save_count: int = 0 - tree_count: int = 0 - # Per-destination status. ``excluded`` means a same-named local payload - # exists but contradicts the declaration and is intentionally not shipped. - # It is distinct from a genuine coverage gap (``missing``). - file_status: dict[str, str] = field(default_factory=dict) - file_reasons: dict[str, str] = field(default_factory=dict) - # Core extras whose local copy contradicts the profile hash: packed, - # reported, and never counted against the platform's own file total. - core_discrepancies: list[str] = field(default_factory=list) - # Spellings left out as case twins of a packed file, for the README. - case_twins: list[str] = field(default_factory=list) - - def __post_init__(self) -> None: - self.placed = _Placed(self.plan.case_insensitive) - - def _flat(self, path: str) -> str: - return _flat(path, self.plan.base_dest, self.plan.opts.flatten) - - def run(self) -> None: - if self.plan.opts.source != "truth": - for sys_id, system in sorted(self.plan.pack_systems.items()): - for file_entry in system.get("files", []): - self._pack_declared(sys_id, file_entry) - # Core requirements: files platform's cores need but YAML doesn't declare - self._pack_core_files() - self._pack_trees() - self._write_readme() - - def _judge_conflict(self, file_entry: dict, full_dest: str) -> None: - # Content ships under the conflicting shape (file vs dir, - # e.g. SGB1.sfc). verify.py resolves each declaration on - # its own, so this one is counted by what it resolves to: - # an unresolved one counted OK had the pack claim a file - # verify reports missing. - plan = self.plan - conflict_path, conflict_status = resolve_file( - file_entry, plan.db, plan.bios_dir, plan.zip_contents, - data_dir_registry=plan.opts.data_registry, offline=plan.opts.offline, - ) - # The verdict of the main path: a zipped_file archive is - # judged by the member inside, and a frontend that hashes - # one digest accepts a file another declared hash - # contradicts, as verify judges it. - conflict_status, refusal = baseline_verdict( - file_entry, conflict_path, conflict_status, plan.verification_mode, - plan.config.get("hash_rule", ""), - ) - if conflict_status == "not_found": - self.file_status[full_dest] = "missing" - self.file_reasons[full_dest] = "not found" - elif refusal: - self.file_status[full_dest] = "excluded" - self.file_reasons[full_dest] = refusal - else: - self.file_status.setdefault(full_dest, "ok") - - def _pack_declared(self, sys_id: str, file_entry: dict) -> None: - plan, opts = self.plan, self.plan.opts - if opts.required_only and file_entry.get("required") is False: - return - dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) - if plan.region_drops and dest in plan.region_drops: - return - if not dest: - self._judge_unnamed(sys_id, file_entry) - return - full_dest = f"{plan.base_dest}/{dest}" if plan.base_dest else dest - already_packed = self.placed.holds(full_dest) - - preferred = plan.preferred_entries.get(full_dest) - if preferred is not None and id(file_entry) != preferred: - return - if self.placed.conflicts(full_dest): - self._judge_conflict(file_entry, full_dest) - return - storage = file_entry.get("storage", "embedded") - if storage == "user_provided": - if not already_packed: - self._write_instructions(file_entry, full_dest) - return - - local_path, status = self.resolve(file_entry, full_dest) - if status == "external": - self._pack_external(file_entry, full_dest) - return - if status == "not_found": - local_path = self._agnostic_fallback(sys_id, file_entry, full_dest, already_packed) - if local_path is None: - return - status = "agnostic_fallback" - # Fall through to normal packing below - chosen = self._settle_declared(file_entry, full_dest, dest, local_path, status, already_packed) - if chosen is not None: - self._ship_declared(file_entry, full_dest, chosen, already_packed) - - def _judge_unnamed(self, sys_id: str, file_entry: dict) -> None: - # EmuDeck-style entries (system:md5 whitelist, no filename). - # Judged as verify judges it: resolved on disk, the md5 - # list parsed once (case, comma lists). - plan = self.plan - fkey = f"{sys_id}/{file_entry.get('name', '')}" - held, held_status = resolve_file( - file_entry, plan.db, plan.bios_dir, plan.zip_contents, - data_dir_registry=plan.opts.data_registry, offline=plan.opts.offline, - ) - if held_status == "not_found" or not held: - self.file_status[fkey] = "missing" - elif self.verdict(file_entry, held, held_status)[1]: - self.file_status[fkey] = "excluded" - else: - self.file_status.setdefault(fkey, "ok") - - def _write_instructions(self, file_entry: dict, full_dest: str) -> None: - base_dest = self.plan.base_dest - self.placed.take(full_dest) - self.file_status.setdefault(full_dest, "ok") - instructions = file_entry.get( - "instructions", "Please provide this file manually." - ) - instr_name = f"INSTRUCTIONS_{file_entry['name']}.txt" - instr_path = ( - f"{base_dest}/{instr_name}" if base_dest else instr_name - ) - _write_generated_member( - self.zf, - self._flat(instr_path), - f"File needed: {file_entry['name']}\n\n{instructions}\n", - ) - self.total_files += 1 - - def _pack_external(self, file_entry: dict, full_dest: str) -> None: - file_ext = os.path.splitext(file_entry["name"])[1] or "" - with tempfile.NamedTemporaryFile( - delete=False, suffix=file_ext, dir=packresolve.scratch_dir() - ) as tmp: - tmp_path = tmp.name - - # The slot is the platform's file whether the download - # arrives or not: verify cannot fetch, and a core file - # filling it on a failed download made the two differ. - self.placed.take(full_dest) - try: - if self.plan.opts.record is None and download_external(file_entry, tmp_path): - extract = file_entry.get("extract", False) - if extract and tmp_path.endswith(".zip"): - _extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf) - else: - _add_pack_member(self.zf, tmp_path, self._flat(full_dest)) - self.file_status.setdefault(full_dest, "ok") - self.total_files += 1 - else: - self.file_status[full_dest] = "missing" - self.file_reasons[full_dest] = "external download failed" - finally: - if os.path.exists(tmp_path): - os.unlink(tmp_path) - - def _agnostic_fallback( - self, sys_id: str, file_entry: dict, full_dest: str, already_packed: bool, - ) -> str | None: - # A filename-agnostic core takes any image of its system, - # renamed. Only an existence frontend accepts that. - plan = self.plan - found = None - if not reads_file_contents(plan.verification_mode): - found = agnostic_substitute(file_entry, sys_id, plan.db, plan.platform_profiles) - if not found or not found[0]: - if not already_packed: - self.file_status[full_dest] = "missing" - self.file_reasons[full_dest] = "not found" - return None - local_path, agnostic_path = found - original_name = os.path.basename(local_path) - dest_name = file_entry.get("name", "") - if original_name != dest_name and agnostic_path: - alt_names = [ - entry.get("name", "") - for entry in plan.db.get("files", {}).values() - if entry.get("path", "").startswith(agnostic_path) - and entry.get("name", "") and entry.get("name", "") != original_name - ] - readme_text = _build_agnostic_rename_readme(dest_name, original_name, alt_names) - readme_name = f"RENAMED_{dest_name}.txt" - readme_full = f"{plan.base_dest}/{readme_name}" if plan.base_dest else readme_name - if readme_full not in self.placed.destinations: - _write_generated_member(self.zf, self._flat(readme_full), readme_text) - self.placed.destinations.add(readme_full) - return local_path - - def _settle_declared( - self, - file_entry: dict, - full_dest: str, - dest: str, - local_path: str | None, - status: str, - already_packed: bool, - ) -> str | None: - """The copy a declaration ships once judged, or None when refused.""" - plan = self.plan - # The verdict the install manifest reads too: a member missing - # from a zipped_file archive, or a hash the frontend rejects. - status, refusal = self.verdict(file_entry, local_path, status) - if refusal: - # An earlier declaration of this path shipped a file this - # one refuses: it is in the pack, untested as verify - # counts it, not excluded. - self.file_status[full_dest] = "untested" if already_packed else "excluded" - self.file_reasons[full_dest] = refusal - return None - if not hash_mismatch_excludes_file(plan.verification_mode) and ( - status == "hash_mismatch" and local_path - ): - # Existence platforms accept any file at the declared path: - # their code never reads the bytes. An upstream hash that - # contradicts a local dump is reported, not acted on. - self.file_reasons.setdefault( - full_dest, - existence_discrepancy(file_entry, local_path, plan.platform_display), - ) - if self.file_status.get(full_dest) == "missing": - # An earlier declaration of this path found nothing, and this - # one fills it, as verify counts it. - del self.file_status[full_dest] - self.file_reasons.pop(full_dest, None) - self.file_status.setdefault(full_dest, "ok") - - # Emulator-level validation: informational only for platform packs. - # Platform verification (existence/md5) is the authority for pack status. - # Emulator checks are supplementary: logged but don't downgrade. - # When a discrepancy is found, try to find a file satisfying both. - if self.file_status.get(full_dest) == "ok": - local_path, disagreement = self.judge(file_entry, local_path, dest) - if disagreement: - self.file_reasons.setdefault( - full_dest, f"{plan.platform_display} says OK but {disagreement}" - ) - return local_path - - def _ship_declared( - self, file_entry: dict, full_dest: str, local_path: str, already_packed: bool, - ) -> None: - within = self.plan.opts.within - if already_packed: - if full_dest not in self.placed.destinations: - self.case_twins.append(self._flat(full_dest)) - return - if within is not None and not _same_bytes(local_path, within.get(self._flat(full_dest))): - # The full pack holds another system's file here. - return - if self.file_status.get(full_dest) == "excluded": - # An earlier declaration refused the file this one ships. - self.file_status[full_dest] = "untested" - self.placed.take(full_dest) - - extract = file_entry.get("extract", False) - flat_dest = self._flat(full_dest) - if extract and local_path.endswith(".zip"): - _extract_zip_to_archive(local_path, flat_dest, self.zf) - elif local_path.endswith(".zip"): - _add_zip_to_pack(local_path, flat_dest, self.zf, file_entry) - else: - _add_pack_member(self.zf, local_path, flat_dest) - self.total_files += 1 - - def _region_dropped(self, fe: dict) -> bool: - drops = self.plan.region_drops - return bool(drops) and extra_region_key(fe, declared_root(self.plan.config)) in drops - - def _spares(self, files: list[dict]) -> set[int]: - if not self.plan.opts.required_only: - return set() - return core_file_spares(files, self._region_dropped) - - def _core_files(self) -> list[dict]: - plan, opts = self.plan, self.plan.opts - if opts.source == "platform": - return [] - if opts.precomputed_extras is not None: - return opts.precomputed_extras - if opts.system_filter: - # The systems asked for, with what their cores need: the split - # packs get exactly this, and a full pack of one system had none. - return _extras_for_systems( - _collect_emulator_extras( - plan.config, opts.emulators_dir, plan.db, set(), plan.base_dest, - plan.emu_profiles, target_cores=opts.target_cores, - include_all=(opts.source == "truth"), undeclared=plan.undeclared, - ), - opts.system_filter, - ) - return _collect_emulator_extras( - plan.config, - opts.emulators_dir, - plan.db, - self.placed.destinations, - plan.base_dest, - plan.emu_profiles, - target_cores=opts.target_cores, - include_all=(opts.source == "truth"), - undeclared=plan.undeclared, - ) - - def _pack_core_files(self) -> None: - core_files = self._core_files() - spares = self._spares(core_files) - for fe in core_files: - if self.plan.opts.required_only and (fe.get("required") is False or id(fe) in spares): - continue - self._pack_core_file(fe) - - def _pack_core_file(self, fe: dict) -> None: - plan = self.plan - dest = sanitize_pack_path(fe.get("destination", fe["name"])) - if self._region_dropped(fe): - return - if not dest: - return - if fe.get("root") in OUTER_ROOTS: - # Read below the roms directory or in an emulator folder: the - # pack is extracted into the BIOS folder and cannot reach - # them, the installer places these files. - return - # Core extras: _collect_emulator_extras already adjusted - # destinations for slug-based platforms. Apply the effective - # prefix (base_dest, or inferred from YAML when base_dest is - # empty, as RetroDECK infers "bios"). A file read below the save - # directory goes to the pack's save folder instead. - full_dest = extra_full_destination( - fe, _detect_extras_prefix(plan.config, plan.base_dest) - ) - if not full_dest: - return - # Taken, a case twin on a case-insensitive filesystem, or a - # file/directory conflict (SGB1.sfc vs SGB1.sfc/): verify replays - # the same rule (packextras.hidden_extras). - block = self.placed.block(full_dest) - if block: - if block == "case_twin" and self.resolve_extra(fe, dest)[0]: - self.case_twins.append(self._flat(full_dest)) - return - - # The emulator's own check picks the copy, as for a declared file - # and in the emulator pack: the name led RetroArch's GC/dsp_rom.bin - # to Dolphin's obsolete v0.3.1 free ROM, beside Nintendo's coef - # ROM, a pair Dolphin warns about at every start. - local_path, status, disagreement = self.resolve_extra(fe, dest) - if not local_path: - return - self._note_core_discrepancy(fe, full_dest, local_path, status, disagreement) - - flat_dest = self._flat(full_dest) - within = plan.opts.within - if within is not None and not _same_bytes(local_path, within.get(flat_dest)): - return - if local_path.endswith(".zip"): - _add_zip_to_pack(local_path, flat_dest, self.zf, fe) - else: - _add_pack_member(self.zf, local_path, flat_dest) - if self.file_status.get(full_dest) in ("missing", "excluded"): - self._core_fills_declaration(fe, full_dest) - self.placed.take(full_dest) - self.core_count += 1 - if fe.get("root") == "save": - self.save_count += 1 - self.total_files += 1 - - def _note_core_discrepancy( - self, fe: dict, full_dest: str, local_path: str, status: str, disagreement: str, - ) -> None: - if disagreement: - self.core_discrepancies.append(f"{full_dest}: {disagreement}") - if status == "hash_mismatch" and not _matches_an_alternative( - fe, local_path, self.plan.emu_profiles or {} - ): - # The core's declared hash comes from its source, the local dump - # is what the collection holds. Shipping it keeps the emulator - # working when the code never reads the hash, and the divergence is - # reported so it can be resolved at the profile or the dump. - # file_status tracks platform declarations only, so the report - # goes to its own list and never moves the pack's own count. - self.core_discrepancies.append( - f"{full_dest}: declared hash of " - f"{fe.get('source_profile') or fe.get('source_emulator', 'core profile')}" - " does not match the packed copy" - ) - - def _core_fills_declaration(self, fe: dict, full_dest: str) -> None: - source_name = fe.get("source_profile") or fe.get( - "source_emulator", "core profile" - ) - if reads_file_contents(self.plan.verification_mode): - # The frontend hashes what sits at the path, and the core's - # copy is not the hash it declares: the file ships for the - # core, the platform's own check still fails, as verify says. - self.file_reasons[full_dest] = ( - "platform-declared hash unavailable; " - f"packed the validated {source_name} requirement, " - "which the platform check does not accept" - ) - else: - # An existence frontend is satisfied by any file at the path. - self.file_status[full_dest] = "ok" - self.file_reasons.pop(full_dest, None) - - def _pack_trees(self) -> None: - plan, opts = self.plan, self.plan.opts - # The trees the cores read follow them as their extras do: by the - # systems asked for, and those of no system in the part of their own. - core_trees = ( - [] if opts.source == "platform" - else core_data_trees( - plan.config, plan.emu_profiles, plan.platform_name, opts.data_registry, - opts.target_cores, - ) - ) - if opts.extras_only: - owned = list(platform_scope_systems(plan.config, plan.emu_profiles, opts.target_cores)) - core_trees = [t for t in core_trees if not _extras_for_systems([t], owned)] - elif opts.system_filter: - core_trees = _extras_for_systems(core_trees, opts.system_filter) - # Counted apart: the trees a core reads are not on the platform's - # list. MyMinUI declares nothing and its line read "6944 baseline". - self.total_files += self._pack_data_directories(plan.pack_systems, ()) - self.tree_count = self._pack_data_directories({}, core_trees) - self.total_files += self.tree_count - - def _pack_data_directories(self, pack_systems: dict, core_trees: Iterable[dict]) -> int: - """Add the data directories to the pack. Returns how many files went in.""" - plan = self.plan - required_only = plan.opts.required_only - seen_parents = self.placed.parents - added = 0 - for src, full in _data_directory_members( - pack_systems, plan.opts.data_registry, plan.platform_name, plan.base_dest, - self.placed.fold, self.placed.destinations, self.placed.lower, - seen_parents, required_only=required_only, - core_trees=core_trees, - ): - _add_pack_member(self.zf, src, self._flat(full)) - if isinstance(self.zf, PackRecord): - self.zf.trees.append(self._flat(full)) - added += 1 - return added - - def _unfolded_twins(self) -> None: - # The spellings a folded platform counts as declared never reach - # the extras: collected as the filesystem that keeps case sees - # them, as the manifest's case_variants are (Mesen-CE's bios.col - # beside the declared BIOS.col). - plan, opts = self.plan, self.plan.opts - unfolded = _collect_emulator_extras( - {**plan.config, "case_insensitive_fs": False}, opts.emulators_dir, plan.db, set(), - plan.base_dest, plan.emu_profiles, target_cores=opts.target_cores, - include_all=(opts.source == "truth"), - ) - if opts.system_filter: - unfolded = _extras_for_systems(unfolded, opts.system_filter) - prefix = _detect_extras_prefix(plan.config, plan.base_dest) - unfolded_spares = self._spares(unfolded) - for fe in unfolded: - if opts.required_only and (fe.get("required") is False or id(fe) in unfolded_spares): - continue - if self._region_dropped(fe): - continue - full = extra_full_destination(fe, prefix) - if ( - full and full not in self.placed.destinations and full.lower() in self.placed.lower - and self.resolve_extra( - fe, sanitize_pack_path(fe.get("destination", fe["name"])) - )[0] - ): - self.case_twins.append(self._flat(full)) - - def _write_readme(self) -> None: - # README.txt for users: personalized step-by-step per platform - plan, opts = self.plan, self.plan.opts - registry = _platform_registry(plan.platforms_dir).get(plan.platform_name, {}) - install = registry.get("install", {}) or {} - keeps_case = plan.case_insensitive and any( - d.get("os") not in CASE_FOLDING_OS for d in install.get("detect", []) - ) - if keeps_case and opts.source != "platform" and opts.precomputed_extras is None: - self._unfolded_twins() - save_count = self.save_count - readme_text = _build_readme( - plan.platform_name, plan.platform_display, plan.base_dest, self.total_files, - len(plan.pack_systems), - source=opts.source, - contributors=registry.get("contributed_by", []), - regions=opts.regions, - fallback_systems=plan.region_fallbacks, - one_per_slot=opts.one_per_slot, - undecidable_slots=plan.slot_undecidable, - narrowings=plan.narrowings, - system_filter=opts.system_filter, - detect=install.get("detect", []), - standalone_copies=install.get("standalone_copies", []), - launch_folders=len(plan.config.get("core_system_dirs") or {}), - save_folder=(save_layout(plan.config).in_pack if save_count else ""), - save_where=( - save_place( - str(registry.get("extract_to") or ""), - save_layout(plan.config).folder, plan.base_dest, - ) if save_count else "" - ), - save_by_system=bool(save_count and save_layout(plan.config).by_system), - case_twins=( - _case_twin_pairs( - self.case_twins, self.placed.destinations, plan.base_dest, opts.flatten - ) - if keeps_case else [] - ), - ) - _write_generated_member(self.zf, "README.txt", readme_text) - for marker in pack_markers(plan.platform_name, opts.target_name, plan.platforms_dir): - _write_generated_member( - self.zf, - self._flat(f"{plan.base_dest}/{marker}" if plan.base_dest else marker), - "", - ) - - def report(self) -> None: - plan, opts = self.plan, self.plan.opts - _report_pack_counts( - plan.zip_path, self.file_status, self.total_files, self.core_count, opts.source, - plan.verification_mode, tree_count=self.tree_count, - ) - if plan.cut is not None: - _report_left_out( - plan.cut, - systems=set(plan.pack_systems) if opts.source != "truth" else set(), - cores=opts.source != "platform" and opts.precomputed_extras is None, - ) - for key, reason in sorted(self.file_reasons.items()): - label = _STATUS_LABELS.get(self.file_status.get(key, ""), "DISCREPANCY") - print(f" {label}: {key}: {reason}") - for note in sorted(self.core_discrepancies): - print(f" DISCREPANCY: {note}") - - -def _platform_registry(platforms_dir: str) -> dict: - """The platforms of _registry.yml, or nothing when the file is absent.""" - registry_path = Path(platforms_dir) / "_registry.yml" - if not registry_path.exists(): - return {} - with open(registry_path) as f: - return (yaml_load(f) or {}).get("platforms", {}) - - -def generate_pack( - platform_name: str, - platforms_dir: str, - db: dict, - bios_dir: str, - output_dir: str, - **options: Unpack[PackOptions], -) -> str | None: - """Generate a ZIP pack for a platform. - - ``no_game_data`` leaves out the platform's entries categorized as game - data and the cores' ``category: game_data`` files, and names each one. - - ``pack_name`` replaces the derived file name: a split part is named after - its group, and a name built from every system of a hundred-system group - is longer than a file name can be. - - ``record`` builds the pack in memory (PackRecord): no archive is written, - no external file fetched, and the paths are kept on it. - - ``within`` is the full pack's PackRecord.sources, given to a split part: - a declared file or core extra is written only where the full pack writes - the same bytes. A part sees neither the other systems' declarations nor - their extras, so a path the full pack settles (a file/directory conflict, - a case twin, a path another system's file takes) was written again. - - Returns the path to the generated ZIP, or None on failure. - """ - _reject_unknown("generate_pack", options, PackOptions.__optional_keys__) - opts = _PackSettings(**options) - plan = _plan_platform_pack(platform_name, platforms_dir, db, bios_dir, output_dir, opts) - if plan is None: - return None - - def resolve(file_entry: dict, full_dest: str) -> tuple[str | None, str]: - return resolve_declaration( - file_entry, - db, - bios_dir, - plan.zip_contents, - opts.data_registry, - plan.slot_overrides.get(full_dest), - offline=opts.offline, - ) - - def verdict(file_entry: dict, local_path: str | None, status: str) -> tuple[str, str | None]: - return baseline_verdict( - file_entry, local_path, status, plan.verification_mode, - plan.config.get("hash_rule", ""), - ) - - def judge(file_entry: dict, local_path: str | None, dest: str) -> tuple[str | None, str | None]: - return validated_choice( - file_entry, local_path, db, plan.validation_index, bios_dir, - digest_algorithm(plan.verification_mode), dest, plan.validation_owners, - ) - - extra_resolver = ExtraResolver( - db, bios_dir, plan.zip_contents, opts.data_registry, plan.validation_index, - plan.validation_owners, opts.offline, profiles=plan.emu_profiles, - ) - - def resolve_extra(fe: dict, dest: str) -> tuple[str | None, str, str]: - return extra_resolver.resolve(fe, dest) - - with ( - contextlib.nullcontext(opts.record) if opts.record is not None - else _writing_pack(plan.zip_path) - ) as zf: - build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra) - build.run() - build.report() - return plan.zip_path - - -def _extract_zip_to_archive( - source_zip: str, - dest_prefix: str, - target_zf: zipfile.ZipFile | PackRecord, -) -> None: - """Extract contents of a source ZIP into target ZIP under dest_prefix.""" - with zipfile.ZipFile(source_zip, "r") as src: - if isinstance(target_zf, PackRecord): - target_zf.members.extend( - f"{dest_prefix}/{name}" if dest_prefix else name - for name in map(sanitize_pack_path, src.namelist()) - if name and not name.endswith("/") - ) - target_zf.sources[dest_prefix] = source_zip - return - for info in src.infolist(): - if info.is_dir(): - continue - clean_name = sanitize_pack_path(info.filename) - if not clean_name: - continue - data = src.read(info.filename) - target_path = f"{dest_prefix}/{clean_name}" if dest_prefix else clean_name - member = zipfile.ZipInfo( - filename=target_path, date_time=_FIXED_DATE_TIME - ) - member.compress_type = _member_compression(target_path) - member.external_attr = 0o100644 << 16 - target_zf.writestr(member, data) - - -def _add_zip_to_pack( - source_zip: str, - dest_path: str, - target_zf: zipfile.ZipFile | PackRecord, - file_entry: dict | None = None, -) -> None: - """Write a source ZIP into the pack, byte for byte. - - The pack carries the collection's own bytes, so every member hashes to - the sha1 the install list and the site publish. Rebuilt ZIPs gave about - 1,500 archives another hash than the list: an extracted pack then failed - `install.py --check`. The collection's bytes are fixed in git, which keeps - the pack reproducible without a rebuild. - """ - if isinstance(target_zf, PackRecord): - target_zf.members.append(dest_path) - target_zf.sources[dest_path] = source_zip - return - _check_zip_members(source_zip) - _add_pack_member(target_zf, source_zip, dest_path) - - -def _check_zip_members(source_zip: str) -> None: - """Refuse an archive whose members fail their own CRC. - - Copied as-is "for verify to flag", a damaged archive went into the pack - and nothing flagged it. - """ - try: - with zipfile.ZipFile(source_zip) as zf: - bad = zf.testzip() - except zipfile.BadZipFile as exc: - raise DamagedArchiveError( - f"{source_zip}: {exc}; restore it from git or the release before packing" - ) from exc - if bad is not None: - raise DamagedArchiveError( - f"{source_zip}: member {bad} fails its CRC; " - "restore it from git or the release before packing" - ) - - -class DamagedArchiveError(OSError): - """An archive of the collection whose members fail their own CRC.""" - - # Emulator/system mode pack generation - -def _pack_data_tree( - zf: zipfile.ZipFile | PackRecord, - local_cache: str, - dd_dest: str, - seen_destinations: set[str], - seen_parents: set[str], - seen_lower: set[str], - packed_at: dict[str, str] | None = None, -) -> int: - """Write one data directory into an emulator pack, under its shared lock. - - A refresh swaps the tree by rename. Without the lock a walk half done - read the old tree and wrote files of the new one. ``packed_at`` records - each member, so a later profile asking for the same bytes there is - served rather than reported missing. - """ - added = 0 - with cache_lock(local_cache, shared=True): - for root, _dirs, filenames in os.walk(local_cache): - for fname in filenames: - src = os.path.join(root, fname) - rel = os.path.relpath(src, local_cache) - full = f"{dd_dest}/{rel}" if dd_dest else rel - if full.lower() in seen_lower or _has_path_conflict( - full, seen_destinations, seen_parents - ): - continue - seen_destinations.add(full) - _register_path(full, seen_destinations, seen_parents) - seen_lower.add(full.lower()) - _add_pack_member(zf, src, full) - if packed_at is not None: - packed_at[full.lower()] = src - added += 1 - return added - - -def _same_bytes(path: str, other: str | None) -> bool: - if not other: - return False - if os.path.realpath(path) == os.path.realpath(other): - return True - return compute_hashes(path)["sha1"] == compute_hashes(other)["sha1"] - - -# A file name holds 255 bytes on every filesystem a pack is written to, -# and the margin leaves room for the split part suffix and a scratch prefix. -MAX_PACK_NAME_BYTES = 200 - - -def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -> str: - """The emulator pack's file name, its emulators joined while they fit. - - Past the limit the name keeps the first emulator, says how many more the - pack holds, and carries a digest of the selection so two different - selections never share a file. - """ - joined = "_".join(display_names) + suffix - if len(joined.encode("utf-8")) <= MAX_PACK_NAME_BYTES: - return joined - digest = hashlib.sha1("\n".join(sorted(keys)).encode("utf-8")).hexdigest()[:8] - return f"{display_names[0]}_and_{len(display_names) - 1}_more_{digest}{suffix}" - - -class EmulatorPackOptions(TypedDict, total=False): - """The keyword options of generate_emulator_pack.""" - - zip_contents: dict | None - offline: bool | None - platforms_dir: str | None - pack_name: str | None - system_ids: list[str] | None - final_dir: str | None - record: PackRecord | None - - -@dataclass -class _EmulatorPackBuild: - """One emulator pack being written, and what each destination came to.""" - - db: dict - bios_dir: str - standalone: bool - required_only: bool - zip_contents: dict - data_registry: dict - validation_index: dict - region_drops: set[str] - all_profiles: dict - zf: zipfile.ZipFile | PackRecord - offline: bool | None = None - system_ids: list[str] | None = None - record: PackRecord | None = None - total_files: int = 0 - data_files: int = 0 - missing_files: list[str] = field(default_factory=list) - rejected_files: list[str] = field(default_factory=list) - discrepancies: list[str] = field(default_factory=list) - unsourceable_files: list[str] = field(default_factory=list) - instruction_files: list[str] = field(default_factory=list) - placed: _Placed = field(default_factory=lambda: _Placed(True)) - seen_hashes: set[str] = field(default_factory=set) # SHA1 dedup for same file, different path - # Loose file packed at each folded destination, to tell a profile asking - # for the same file there from one asking for other bytes. - packed_at: dict[str, str] = field(default_factory=dict) - # A destination is missing once, however many profiles ask for it: - # verify --emulator counts by destination. - missing_at: set[str] = field(default_factory=set) - data_dir_notices: list[str] = field(default_factory=list) - - def report_missing(self, name: str, destination: str) -> None: - if destination not in self.missing_at: - self.missing_at.add(destination) - self.missing_files.append(name) - - def _add(self, local_path: str, dest: str, fe: dict | None) -> None: - """Write a loose file or an archive at dest and count it.""" - if fe is not None and local_path.endswith(".zip"): - _add_zip_to_pack(local_path, dest, self.zf, fe) - else: - _add_pack_member(self.zf, local_path, dest) - self.placed.take(dest) - self.total_files += 1 - if self.record is not None: - self.record.files.append(dest) - - def pack_profile(self, emu_name: str, profile: dict) -> None: - pack_structure = profile.get("pack_structure") - files = expand_agnostic_entries( - expand_directory_entries( - deliverable(profile.get("files", []), self.standalone), - self.db, - self.standalone, - ), - emu_name, profile, self.db, self.standalone, self.all_profiles, - ) - if self.system_ids: - files = [ - fe for fe in files if entry_serves_systems(fe, profile, self.system_ids) - ] - if not files and not profile.get("data_directories"): - print(f" No files needed for {profile.get('emulator', emu_name)}") - - # What each destination came to, settled by set once the - # profile is read: a member another member fills is not missing, - # and a set nobody holds is reported once (alternatives.py). An - # archive unit is a member like a loose file. - outcomes: list[_Outcome] = [] - spares = emulator_required_spares( - emu_name, profile, files, self.standalone, self.region_drops, self.db, - self.validation_index, self.zip_contents, data_registry=self.data_registry, - ) if self.required_only else set() - - # Pack archives as units - archive_prefix = profile.get("archive_prefix", "") - for archive_name in sorted({fe["archive"] for fe in files if fe.get("archive")}): - archive_dest = _archive_destination( - archive_name, archive_prefix, pack_structure, self.standalone - ) - own_entry = archive_entry(archive_name, files) - if self.required_only and archive_is_optional(own_entry, archive_name, files): - continue - if archive_dest in spares: - continue - outcomes.append(self._pack_archive(own_entry, archive_name, archive_dest)) - - for dest, alternatives in self._slots(files, spares).items(): - outcome = self._pack_slot(emu_name, files, dest, alternatives) - if outcome is not None: - outcomes.append(outcome) - - excused, _standing = settle_sets([ - (slot_set_keys(emu_name, entries), entries[0], fills) - for entries, fills, _report in outcomes - ]) - for position, (_entries, _fills, report) in enumerate(outcomes): - if report is not None and position not in excused: - report() - self._pack_trees(profile, pack_structure) - - def _pack_archive(self, own_entry: dict, archive_name: str, archive_dest: str) -> _Outcome: - local_path, status = resolve_file( - own_entry, - self.db, - self.bios_dir, - self.zip_contents, - data_dir_registry=self.data_registry, - offline=self.offline, - ) - taken = archive_dest.lower() in self.placed.lower - if taken or self.placed.conflicts(archive_dest): - # Another profile's file holds this path. The same archive - # asked for twice is served. Anything else leaves this - # profile without its archive, which used to pass in - # silence: a neocdz.zip lacking 000-lo.lo shipped as the - # one the second core needs. - if not (taken and local_path and _same_bytes( - local_path, self.packed_at.get(archive_dest.lower()) - )): - return ([own_entry], False, functools.partial( - self.report_missing, archive_name, archive_dest - )) - return ([own_entry], True, None) - if local_path and status not in ("not_found",): - self._add(local_path, archive_dest, own_entry) - self.packed_at[archive_dest.lower()] = local_path - return ([own_entry], True, None) - return ([own_entry], False, functools.partial( - self.report_missing, archive_name, archive_dest - )) - - def _slots(self, files: list[dict], spares: set) -> dict[str, list[dict]]: - # Pack individual files (skip archive members). The entries of one - # profile on one destination are the releases the code accepts - # there (raze's seven SW.GRP): the first one the core accepts - # fills the slot, as verify --emulator credits it, and the slot - # has one outcome however many alternatives it lists. - slots: dict[str, list[dict]] = {} - for fe in files: - if self.required_only and fe.get("required") is False: - continue - if fe.get("archive"): - continue - dest = _resolve_destination(fe, self.standalone) - if not dest or dest in spares: - continue - if self.region_drops and dest in self.region_drops: - continue - slots.setdefault(dest, []).append(fe) - return slots - - def _write_instructions(self, provided: dict, dest: str) -> None: - # Instructions, not a file: written beside the slot the - # user fills, and counted apart from what the pack holds. - self.placed.take(dest) - instr = provided.get("instructions", "Please provide this file manually.") - folder = dest.rsplit("/", 1)[0] + "/" if "/" in dest else "" - _write_generated_member( - self.zf, - f"{folder}INSTRUCTIONS_{provided['name']}.txt", - f"File needed: {provided['name']}\n\n{instr}\n", - ) - # verify --emulator counts an unsourceable one as such. - (self.unsourceable_files if provided.get("unsourceable") else self.instruction_files).append( - provided["name"] - ) - - def _choose( - self, emu_name: str, files: list[dict], alternatives: list[dict], - ) -> tuple[tuple[dict, str, str | None] | None, str | None, str | None]: - """The alternative the core accepts, with the refusal of the first - one it turned away and that copy.""" - fallback: tuple[dict, str, str | None] | None = None - refusal: str | None = None - refused_path: str | None = None - for fe in alternatives: - local_path, status = resolve_file( - {**with_archive_members(fe, files), "source_profile": emu_name}, - self.db, - self.bios_dir, - self.zip_contents, - dest_hint=fe.get("path", ""), - data_dir_registry=self.data_registry, - offline=self.offline, - ) - if status == "external": - return (fe, "", "external"), refusal, refused_path - if status in ("not_found", "user_provided") or not local_path: - continue - # The file verify --emulator credits is the one shipped: - # a dump the core's own check rejects gives way to a held - # one it accepts (azahar's otp.bin, dolphin's dsp_rom.bin). - better, disagreement = validated_choice( - fe, local_path, self.db, self.validation_index, self.bios_dir, None, - emulators={emu_name}, - ) - if disagreement: - reason = disagreement.split(" says ", 1)[-1] - refusal = refusal or f"{fe['name']}: {reason}" - refused_path = refused_path or local_path - continue - if better != local_path: - return (fe, better, None), refusal, refused_path - if status == "hash_mismatch": - # Not a check the core runs, so the file still serves, - # but it is not the dump the profile documents. - fallback = fallback or (fe, local_path, "mismatch") - continue - return (fe, local_path, None), refusal, refused_path - return fallback, refusal, refused_path - - def _pack_slot( - self, emu_name: str, files: list[dict], dest: str, alternatives: list[dict], - ) -> _Outcome | None: - # Name order, first file wins, case folded: verify replays - # the rule and reports a later profile's file as missing. - block = self.placed.block(dest) - - provided = next( - (fe for fe in alternatives if fe.get("storage") == "user_provided"), - None, - ) - if provided is not None: - if not block: - self._write_instructions(provided, dest) - return None - - chosen, refusal, refused_path = self._choose(emu_name, files, alternatives) - if block: - held = ( - chosen[1] if chosen is not None and chosen[2] != "external" - else None if chosen is not None else refused_path - ) - if chosen is not None or held is not None: - if block == "taken" and held and _same_bytes( - held, self.packed_at.get(dest.lower()) - ): - # The file already at this path, asked for twice. - return (alternatives, True, None) - return (alternatives, False, functools.partial( - self.report_missing, alternatives[0]["name"], dest - )) - - if chosen is None: - return self._unfilled(alternatives, dest, refusal) - fe, local_path, how = chosen - if how == "external": - return self._pack_external(fe, dest, alternatives) - if how == "mismatch": - self.discrepancies.append( - f"{fe['name']}: not the dump the {emu_name} profile declares" - ) - - # SHA1 dedup: skip if same physical file AND same destination - # (but allow same file to be packed under different destinations, - # e.g., IPL.bin in GC/USA/ and GC/EUR/ from same source) - dedup_key_hash = f"{os.path.realpath(local_path)}:{dest}" - if dedup_key_hash not in self.seen_hashes: - self.seen_hashes.add(dedup_key_hash) - self._add(local_path, dest, fe) - self.packed_at[dest.lower()] = local_path - return (alternatives, True, None) - - def _unfilled(self, alternatives: list[dict], dest: str, refusal: str | None) -> _Outcome: - if refusal: - self.rejected_files.append(refusal) - return (alternatives, False, None) - if all(fe.get("unsourceable") for fe in alternatives): - return (alternatives, False, functools.partial( - self.unsourceable_files.append, alternatives[0]["name"] - )) - return (alternatives, False, functools.partial( - self.report_missing, alternatives[0]["name"], dest - )) - - def _pack_external(self, fe: dict, dest: str, alternatives: list[dict]) -> _Outcome: - file_ext = os.path.splitext(fe["name"])[1] or "" - with tempfile.NamedTemporaryFile( - delete=False, suffix=file_ext, dir=packresolve.scratch_dir() - ) as tmp: - tmp_path = tmp.name - try: - # Built in memory, nothing is fetched: verify --emulator - # cannot fetch either and reports the file missing. - if self.record is None and download_external(fe, tmp_path): - self._add(tmp_path, dest, None) - return (alternatives, True, None) - return (alternatives, False, functools.partial( - self.missing_files.append, fe["name"] - )) - finally: - if os.path.exists(tmp_path): - os.unlink(tmp_path) - - def _pack_trees(self, profile: dict, pack_structure: dict | None) -> None: - # The trees after the files, as in a platform pack: a dump the - # profile declares wins over the copy a tree bundles at the same - # path (Dolphin's real dsp_rom.bin over Sys/GC's free one). - # A tree only one build reads follows that build, like a file. - required_only = self.required_only - for dd in deliverable( - profile.get("data_directories", []), self.standalone - ): - if required_only and dd.get("required") is False: - continue - ref_key = dd.get("ref", "") - if not ref_key or not self.data_registry or ref_key not in self.data_registry: - if ref_key: - self.data_dir_notices.append(ref_key) - continue - local_cache = self.data_registry[ref_key].get("local_cache", "") - if not local_cache or not os.path.isdir(local_cache): - self.data_dir_notices.append(ref_key) - continue - dd_dest = dd.get("destination", "") - if pack_structure: - mode_key = "standalone" if self.standalone else "libretro" - prefix = pack_structure.get(mode_key, "") - if prefix: - dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix - self.data_files += _pack_data_tree( - self.zf, local_cache, dd_dest, self.placed.destinations, - self.placed.parents, self.placed.lower, self.packed_at, - ) - - def nothing_needed(self) -> bool: - return self.total_files + self.data_files == 0 and not ( - self.missing_files or self.rejected_files or self.instruction_files - or self.unsourceable_files - ) - - def report(self, shown: str) -> None: - # Report. The members of data trees are counted apart: verify --emulator - # counts the profile's files, and folding 3500 tree members into the - # same number made the two impossible to compare. - parts = [f"{self.total_files} files packed"] - if self.data_files: - parts.append(f"{self.data_files} from data directories") - if self.missing_files: - parts.append(f"{len(self.missing_files)} missing") - if self.rejected_files: - parts.append(f"{len(self.rejected_files)} refused by the core") - if self.unsourceable_files: - parts.append(f"{len(self.unsourceable_files)} unsourceable") - if self.instruction_files: - parts.append(f"{len(self.instruction_files)} to provide") - print(f" {shown}: {', '.join(parts)}") - for name in self.missing_files: - print(f" MISSING: {name}") - for name in self.unsourceable_files: - print(f" UNSOURCEABLE: {name}") - for name in self.instruction_files: - print(f" TO PROVIDE: {name} (instructions in the pack)") - for line in self.rejected_files: - print(f" REFUSED: {line}") - for line in self.discrepancies: - print(f" DISCREPANCY: {line}") - for ref in sorted(set(self.data_dir_notices)): - print( - f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)" - ) - _MISSING_DATA_DIRS.update(self.data_dir_notices) - - -def generate_emulator_pack( - profile_names: list[str], - emulators_dir: str, - db: dict, - bios_dir: str, - output_dir: str, - standalone: bool = False, - *, - required_only: bool = False, - regions: list[str] | None = None, - **options: Unpack[EmulatorPackOptions], -) -> str | None: - """Generate a ZIP pack for specific emulator profiles. - - Returns the path, "" when no file is needed (verify --emulator reports - 0/0 OK), None on failure. - - `pack_name` is the caller's own file name: the system pack names its - archive after the system, and joining 23 SNES emulator names went past - the 255 bytes a file name may hold. `system_ids` keeps only the entries - of those systems, as a platform pack narrows core extras. `final_dir` - is where the caller moves the archive, the path the report names. - `record` builds the pack in memory instead (PackRecord): nothing is - written or read, and the paths are kept on it. - """ - _reject_unknown("generate_emulator_pack", options, EmulatorPackOptions.__optional_keys__) - all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) - zip_contents = options.get("zip_contents") - if zip_contents is None: - zip_contents = build_zip_contents_index(db) - - try: - selected = select_emulator_profiles(profile_names, all_profiles, standalone) - except ProfileSelectionError as exc: - print(f"Error: {exc}", file=sys.stderr) - return None - - record = options.get("record") - # ZIP naming - display_names = [_name_part(p.get("emulator", n)) for n, p in selected] - validation_index = _build_validation_index(dict(selected)) - narrow_tags = "".join( - tag - for tag, _label in _narrowings( - "full", regions, None, False, required_only, standalone - ) - ) - zip_name = options.get("pack_name") or _bounded_pack_name( - display_names, [n for n, _p in selected], f"{narrow_tags}_BIOS_Pack.zip" - ) - zip_path = os.path.join(output_dir, zip_name) - if record is None: - os.makedirs(output_dir, exist_ok=True) - - data_registry = load_data_dir_registry( - options.get("platforms_dir") or str(REPO_ROOT / "platforms") - ) - region_drops: set[str] = ( - emulator_region_drops( - selected, standalone, regions, required_only, db, - zip_contents=zip_contents, data_registry=data_registry, - ) - if regions - else set() - ) - with ( - contextlib.nullcontext(record) if record is not None - else _writing_pack(zip_path) - ) as zf: - build = _EmulatorPackBuild( - db, bios_dir, standalone, required_only, zip_contents, data_registry, - validation_index, region_drops, all_profiles, zf, - offline=options.get("offline"), system_ids=options.get("system_ids"), record=record, - ) - for emu_name, profile in sorted(selected): - build.pack_profile(emu_name, profile) - - # Remove empty ZIP (no files packed and no missing = nothing to ship) - if record is None and build.nothing_needed(): - os.unlink(zip_path) - # What verify --emulator reports as 0/0 OK: no file is needed, so - # no pack is written and the run succeeds. Printed with the path, - # the run named a file it had just removed and exited 1. - print(f" {', '.join(display_names)}: no file needed, no pack written") - return "" - - final_dir = options.get("final_dir") - build.report(os.path.join(final_dir, zip_name) if final_dir else zip_path) - return None if build.nothing_needed() else zip_path - - -class SystemPackOptions(TypedDict, total=False): - """The keyword options of generate_system_pack.""" - - required_only: bool - regions: list[str] | None - offline: bool | None - platforms_dir: str | None - - -def generate_system_pack( - system_ids: list[str], - emulators_dir: str, - db: dict, - bios_dir: str, - output_dir: str, - standalone: bool = False, - zip_contents: dict | None = None, - **options: Unpack[SystemPackOptions], -) -> str | None: - """Generate a ZIP pack for all emulators supporting given system IDs. - - Returns the path, "" when no file is needed, None on failure. - """ - _reject_unknown("generate_system_pack", options, SystemPackOptions.__optional_keys__) - required_only = options.get("required_only", False) - regions = options.get("regions") - offline = options.get("offline") - platforms_dir = options.get("platforms_dir") - profiles = load_emulator_profiles(emulators_dir) - matching = profiles_for_systems(profiles, system_ids, standalone) - - if not matching: - all_systems: set[str] = set() - for p in profiles.values(): - all_systems.update(p.get("systems", [])) - if standalone: - print( - f"No standalone emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - else: - print( - f"No emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - # --list-systems merges spellings that differ in case or separator: - # the hint counted 579 spellings for the 532 lines it prints. - print(suggest_names(system_ids, sorted(all_systems), "--list-systems", - listed=len(system_index(profiles))), - file=sys.stderr) - return None - - # Named like the platform's --system tag: one spelling of a system is - # one file name, and one selection. - sys_display = _bounded_join( - [_system_display_name(sid) for sid in system_ids], list(system_ids) - ) - # Built in a scratch directory: under its emulator name in output_dir it - # overwrote, then carried away, an --emulator pack already there. - os.makedirs(output_dir, exist_ok=True) - # Every dimension goes through the one list: keeping only the region - # tag made --system X --required-only overwrite the pack built without it. - tags = "".join( - tag - for tag, _label in _narrowings( - "full", regions, None, False, required_only, standalone=standalone - ) - ) - # The selection mode is part of the name: `--system sega-triforce` - # and `--emulator triforce` both wrote Triforce_BIOS_Pack.zip, and - # the second run replaced the first without a word. - final_name = f"{sys_display}_System{tags}_BIOS_Pack.zip" - scratch = tempfile.mkdtemp(prefix=".system-", dir=output_dir) - try: - result = generate_emulator_pack( - matching, - emulators_dir, - db, - bios_dir, - scratch, - standalone, - zip_contents=zip_contents, - required_only=required_only, - regions=regions, - offline=offline, - platforms_dir=platforms_dir, - pack_name=final_name, - system_ids=system_ids, - final_dir=output_dir, - ) - if not result: - return result - new_path = os.path.join(output_dir, final_name) - os.replace(result, new_path) - return new_path - finally: - shutil.rmtree(scratch, ignore_errors=True) - - -def _system_display_name(system_id: str) -> str: - """Convert system ID to display name for ZIP naming.""" - s = system_id.lower().replace("_", "-") - for prefix in MANUFACTURER_PREFIXES: - if s.startswith(prefix): - s = s[len(prefix) :] - break - parts = s.split("-") - return "_".join(p.title() for p in parts if p) - - -def _group_systems_by_manufacturer( - systems: dict[str, dict], - db: dict, - bios_dir: str, -) -> dict[str, list[str]]: - """Group system IDs by manufacturer for --split --group-by manufacturer.""" - from model.systems import derive_manufacturer - - groups: dict[str, list[str]] = {} - for sid, sys_data in systems.items(): - mfr = derive_manufacturer(sid, sys_data) - groups.setdefault(mfr, []).append(sid) - return groups - - -class SplitOptions(PackNarrowing, total=False): - """The keyword options of generate_split_packs.""" - - records: dict[str, PackRecord] | None - - -def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict]: - """The core extras of every part, collected once (expensive: scans 260+ - emulator profiles), then distributed per group by system overlap.""" - emu_profiles = narrowing["emu_profiles"] or {} - source = narrowing["source"] - target_cores = narrowing["target_cores"] - base_dest = config.get("base_destination", "") - # Each part cuts the platform's own entries from the full profiles. The - # extras are collected once here, already without the cores' game data. - cut = ( - without_game_data(config, emu_profiles, narrowing["data_registry"], target_cores) - if narrowing["no_game_data"] else None - ) - if source == "platform": - all_extras = [] - elif emu_profiles: - all_extras = _collect_emulator_extras( - cut.config if cut else config, narrowing["emulators_dir"], db, - set(), base_dest, cut.profiles if cut else emu_profiles, - target_cores=target_cores, include_all=(source == "truth"), - ) - else: - all_extras = [] - if cut is not None and source != "platform": - _report_left_out(cut, systems=set(), cores=True) - return all_extras - - -def generate_split_packs( - platform_name: str, - platforms_dir: str, - db: dict, - bios_dir: str, - output_dir: str, - group_by: str = "system", - **options: Unpack[SplitOptions], -) -> list[str]: - """Generate split packs (one ZIP per system or manufacturer). - - The parts add up to the full pack: each is built against the full pack's - own placement (``within``). ``records`` builds the parts in memory, keyed - by part name, with no archive written. - """ - _reject_unknown("generate_split_packs", options, SplitOptions.__optional_keys__) - config = load_platform_config(platform_name, platforms_dir) - records = options.get("records") - narrowing: PackNarrowing = { - "emulators_dir": options.get("emulators_dir", "emulators"), - "zip_contents": options.get("zip_contents"), - "data_registry": options.get("data_registry"), - "emu_profiles": options.get("emu_profiles"), - "target_cores": options.get("target_cores"), - "required_only": options.get("required_only", False), - "source": options.get("source", "full"), - "regions": options.get("regions"), - "target_name": options.get("target_name"), - "one_per_slot": options.get("one_per_slot", False), - "offline": options.get("offline"), - "no_game_data": options.get("no_game_data", False), - } - # The split directory carries the same tags as the packs inside it, or two - # differently narrowed runs write into one another. - split_tags = "".join( - tag - for tag, _label in _narrowings( - narrowing["source"], narrowing["regions"], narrowing["target_name"], - narrowing["one_per_slot"], narrowing["required_only"], - no_game_data=narrowing["no_game_data"], - ) - ) - # Two groupings write different files. Without the tag they accumulate in - # one directory under one SHA256SUMS.txt. - group_tag = "" if group_by == "system" else f"_By{group_by.title()}" - # The parts carry the version, so the directory does too: a rescrape that - # moves the version would otherwise leave the old parts beside the new - # under one SHA256SUMS.txt. - # Named by the stem the full pack reads: assembled here by hand, a '/' in - # a version nested the directory where the check never looked for it. - part_prefix = ( - f"{_platform_pack_stem([platform_name], platform_name, platforms_dir)}{split_tags}" - ) - split_dir = os.path.join(output_dir, f"{part_prefix}{group_tag}_Split") - if records is None: - os.makedirs(split_dir, exist_ok=True) - - emu_profiles = narrowing["emu_profiles"] - if emu_profiles is None: - emu_profiles = load_emulator_profiles(narrowing["emulators_dir"]) - narrowing["emu_profiles"] = emu_profiles - full = PackRecord() - with contextlib.redirect_stdout(io.StringIO()): - generate_pack( - platform_name, platforms_dir, db, bios_dir, split_dir, - record=full, **narrowing, - ) - - def part(pack_name: str, scope: _PartScope) -> str | None: - record = PackRecord() if records is not None else None - zip_path = generate_pack( - platform_name, platforms_dir, db, bios_dir, split_dir, - pack_name=pack_name, record=record, within=full.sources, - **scope, **narrowing, - ) - if records is not None and record is not None and zip_path: - records[pack_name] = record - return zip_path - # The systems a core of the target runs: a part per declared system sent - # each one the target drops to a refusal naming it as unknown. - systems = platform_scope_systems(config, emu_profiles, narrowing["target_cores"]) - - if group_by == "manufacturer": - groups = _group_systems_by_manufacturer(systems, db, bios_dir) - else: - groups = {_system_display_name(sid): [sid] for sid in systems} - - all_extras = _split_extras(config, db, narrowing) - results = [] - for group_name, group_system_ids in sorted(groups.items()): - group_extras = _extras_for_systems(all_extras, group_system_ids) - zip_path = part( - f"{part_prefix}_{_name_part(group_name, '_')}_BIOS_Pack.zip", - {"system_filter": group_system_ids, "precomputed_extras": group_extras}, - ) - if zip_path: - results.append(zip_path) - - # Extras whose system the platform does not declare, or that name none, - # belong to no group: they go in a part of their own, or the parts would - # not add up to the full pack (4507 of RetroArch's 5430 were left out). - distributed = { - id(fe) - for fe in _extras_for_systems( - all_extras, [s for ids in groups.values() for s in ids] - ) - } - undistributed = [fe for fe in all_extras if id(fe) not in distributed] - if undistributed: - zip_path = part( - f"{part_prefix}_Other_Cores_BIOS_Pack.zip", - {"precomputed_extras": undistributed, "extras_only": True}, - ) - if zip_path: - results.append(zip_path) - - return results - - -def _entry_for_file(candidates: list[dict], held: dict) -> dict: - """The declaration a held file answers when several share its name. - - BBKEmu declares 8.BIN once per model. The last one won, and the A4980 - dump went to the A4988 folder. The declared hash decides, then the - destination the collection's own path ends with, then the last one. - """ - def declared(fe: dict, key: str) -> set[str]: - value = fe.get(key) - values = value if isinstance(value, list) else str(value or "").split(",") - return {str(v).strip().lower() for v in values if str(v).strip()} - - for fe in candidates: - if any( - str(held.get(key, "")).lower() in declared(fe, key) - for key in ("sha1", "md5", "sha256", "crc32") - if held.get(key) - ): - return fe - held_paths = [str(held.get("path", ""))] + [str(p) for p in held.get("paths") or []] - for fe in candidates: - tail = str(fe.get("path") or fe.get("destination") or "").lower() - if tail and any(path.lower().endswith("/" + tail) for path in held_paths): - return fe - return candidates[-1] - - -class Md5PackOptions(TypedDict, total=False): - """The keyword options of generate_md5_pack: the layout to follow.""" - - platform_name: str | None - platforms_dir: str | None - emulator_name: str | None - emulators_dir: str | None - standalone: bool - - -@dataclass(frozen=True) -class _Md5Settings: - """Md5PackOptions with their defaults.""" - - platform_name: str | None = None - platforms_dir: str | None = None - emulator_name: str | None = None - emulators_dir: str | None = None - standalone: bool = False - - -@dataclass(frozen=True) -class _Md5Layout: - """Where a hash-selected pack puts each file: the declarations by - lowercased name, the platform's base destination, and the pack's name.""" - - index: dict[str, list[dict]] - base_dest: str - context_name: str - - -def _md5_layout(opts: _Md5Settings) -> _Md5Layout | None: - """The platform or emulator layout a hash list is packed in, or None - when the emulator named is refused.""" - platform_name = opts.platform_name - platforms_dir = opts.platforms_dir - emulator_name = opts.emulator_name - emulators_dir = opts.emulators_dir - plat_file_index: dict[str, list[dict]] = {} - base_dest = "" - plat_display = "Custom" - if platform_name and platforms_dir: - config = load_platform_config(platform_name, platforms_dir) - base_dest = config.get("base_destination", "") - plat_display = config.get("platform", platform_name) - for system in config.get("systems", {}).values(): - for fe in system.get("files", []): - plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe) - - emu_display = "" - if emulator_name and emulators_dir: - profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) - # The same gate as --emulator, unknown names included: a typo or a - # buildbot name gave a generic pack in the layout of no emulator. A - # core with no standalone build has no standalone layout either. - try: - (_name, profile), = select_emulator_profiles( - [emulator_name], profiles, opts.standalone - ) - except ProfileSelectionError as exc: - print(f"Error: {exc}", file=sys.stderr) - return None - emu_display = profile.get("emulator", emulator_name) - for fe in profile.get("files", []): - plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe) - for alias in fe.get("aliases", []): - plat_file_index.setdefault(alias.lower(), []).append(fe) - - context_name = plat_display if platform_name else (emu_display or "Custom") - return _Md5Layout(plat_file_index, base_dest, context_name) - - -def _md5_pack_name( - context_name: str, hashes: list[tuple[str, str]], opts: _Md5Settings, -) -> str: - """The file name of a hash-selected pack.""" - # The selection mode is part of the name, as for --system: BizHawk is - # both a platform and a profile display name, and the two layouts - # (Firmware/ under the platform, the profile's paths under the core) - # wrote one file, the second run replacing the first without a word. - mode_part = ( - "_Emulator" if opts.emulator_name and not opts.platform_name else "" - ) - # --standalone changes the destination layout, so a run with it must not - # take the name of a run without it. - custom_tags = "".join( - tag - for tag, _label in _narrowings( - "full", None, None, False, False, standalone=opts.standalone - ) - ) - # The hash list is what chooses the content: two lists under one name - # overwrote each other in the same output directory. - selection = hashlib.sha1( - "\n".join(sorted(f"{kind}:{value.lower()}" for kind, value in hashes)).encode() - ).hexdigest()[:8] - return ( - f"{_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}" - "_BIOS_Pack.zip" - ) - - -def _md5_destination(entry: dict, layout: _Md5Layout, opts: _Md5Settings) -> str: - """Where a held file goes in a hash-selected pack.""" - name = entry.get("name", "") - aliases = entry.get("aliases") or [] - paths = entry.get("paths") or [] - - dest = name - matched_fe = None - for lookup_name in [name] + aliases: - if lookup_name.lower() in layout.index: - matched_fe = _entry_for_file(layout.index[lookup_name.lower()], entry) - break - - if matched_fe: - if opts.emulator_name: - # Laid out as the emulator pack lays it out: its path and - # its standalone_path, which --standalone has to reach. - dest = _resolve_destination(matched_fe, opts.standalone) - else: - dest = matched_fe.get("destination", matched_fe.get("name", name)) - elif paths: - dest = paths[0] - - if layout.base_dest and not dest.startswith(layout.base_dest): - return f"{layout.base_dest}/{dest}" - return dest - - -def generate_md5_pack( - hashes: list[tuple[str, str]], - db: dict, - bios_dir: str, - output_dir: str, - zip_contents: dict | None = None, - **options: Unpack[Md5PackOptions], -) -> str | None: - """Build a pack from an explicit list of hashes with layout context.""" - files_db = db.get("files", {}) - if zip_contents is None: - zip_contents = {} - _reject_unknown("generate_md5_pack", options, Md5PackOptions.__optional_keys__) - opts = _Md5Settings(**options) - layout = _md5_layout(opts) - if layout is None: - return None - zip_path = os.path.join(output_dir, _md5_pack_name(layout.context_name, hashes, opts)) - os.makedirs(output_dir, exist_ok=True) - - packed: list[tuple[str, str]] = [] - not_in_repo: list[tuple[str, str]] = [] - not_in_db: list[str] = [] - seen: set[str] = set() - - with _writing_pack(zip_path) as zf: - for hash_type, hash_val in hashes: - sha1 = sha1_for_hash(hash_type, hash_val, db) - if not sha1: - not_in_db.append(hash_val) - continue - - entry = files_db[sha1] - name = entry.get("name", "") - full_dest = _md5_destination(entry, layout, opts) - if full_dest in seen: - continue - seen.add(full_dest) - - fe_for_resolve = {"name": name, "sha1": sha1, "md5": entry.get("md5", "")} - local_path, status = resolve_file( - fe_for_resolve, db, bios_dir, zip_contents - ) - - if status == "not_found" or not local_path: - not_in_repo.append((name, hash_val)) - continue - - _add_pack_member(zf, local_path, full_dest) - packed.append((name, hash_val)) - - total = len(hashes) - print(f"\nPacked {len(packed)}/{total} requested files") - for name, h in packed: - print(f" PACKED: {name} ({h[:16]}...)") - for name, h in not_in_repo: - print(f" NOT IN REPO: {name} ({h[:16]}...)") - for h in not_in_db: - print(f" NOT IN DB: {h}") - - if not packed: - if os.path.exists(zip_path): - os.unlink(zip_path) - return None - return zip_path - - def _json_artifact_kind(path: Path) -> str | None: """"manifest" for an install manifest, "targets" for a per-target core list, None for anything else. The two share their file names: install.py @@ -3012,102 +177,6 @@ def _refuse_mixed_output(output_dir: str, writing: str) -> None: sys.exit(1) -def generate_target_manifests(targets_dir: str, output_dir: str) -> None: - """Convert target YAMLs to installer JSON manifests.""" - os.makedirs(output_dir, exist_ok=True) - targets_path = Path(targets_dir) - if not targets_path.is_dir(): - print(f"No targets directory at {targets_dir}", file=sys.stderr) - return - count = 0 - for yml_file in sorted(targets_path.glob("*.yml")): - if yml_file.name.startswith("_"): - continue - result = target_list(yml_file) - out_path = Path(output_dir) / f"{yml_file.stem}.json" - write_text_atomic(out_path, json.dumps(result, indent=2, sort_keys=True) + "\n") - count += 1 - print(f" {yml_file.stem}: {len(result)} targets") - print(f"Generated {count} target manifest(s) in {output_dir}") - - -def target_list(yml_file: Path) -> dict[str, list[str] | dict | None]: - """A platform's cores per hardware target, as install/targets/ publishes - them and a pack carries them: aliases included, overrides applied.""" - targets_path = yml_file.parent - with open(yml_file) as f: - data = yaml_load(f) or {} - targets = data.get("targets", {}) - if not isinstance(targets, dict): - raise ValueError(f"{yml_file}: targets must be a mapping") - - # The pack builder accepts the aliases declared in _overrides.yml, so - # --target switch works there. Emitting only canonical names left the - # installer rejecting the same word and, worse, carrying on with every - # file instead: the user asked for a filter and got the full pack. - overrides_path = targets_path / "_overrides.yml" - alias_map: dict[str, list[str]] = {} - platform_overrides: dict = {} - if overrides_path.is_file(): - with open(overrides_path) as f: - all_overrides = yaml_load(f) or {} - platform_overrides = ( - all_overrides.get(yml_file.stem, {}).get("targets", {}) or {} - ) - for tname, ovr in platform_overrides.items(): - names = [a for a in (ovr or {}).get("aliases", []) if isinstance(a, str)] - if names: - alias_map[tname] = names - - result: dict[str, list[str] | dict | None] = {} - for target_name, target_info in targets.items(): - if not isinstance(target_name, str) or not target_name: - raise ValueError(f"{yml_file}: target names must be non-empty strings") - if not isinstance(target_info, dict): - raise ValueError(f"{yml_file}: target {target_name!r} must be a mapping") - cores = target_info.get("cores") - if cores is None: - result[target_name] = None - continue - if ( - not isinstance(cores, list) - or any(not isinstance(core, str) or not core for core in cores) - or len(cores) != len(set(cores)) - ): - raise ValueError( - f"{yml_file}: target {target_name!r} cores must be unique " - "non-empty strings" - ) - # The builder's own reading, overrides included: a list published - # another way makes the installer serve what the pack does not. - # An empty list is a board with no core, not one with every core. - resolved = load_target_config( - yml_file.stem, target_name, str(targets_path.parent) - ) - listed = None if resolved is None else sorted(resolved) - images = target_info.get("images") - # The image names a card's board file holds (Batocera writes - # anbernic-rg35xx-plus for the h700 target): the installer reads - # the board of a card prepared on a computer through them. - result[target_name] = ( - {"cores": listed, "images": images} - if images and listed is not None else listed - ) - - for target_name, names in alias_map.items(): - if target_name not in result: - continue - for alias in names: - if alias in result: - raise ValueError( - f"{yml_file}: alias {alias!r} collides with a target name" - ) - # An alias names the board, not its images. - held = result[target_name] - result[alias] = held["cores"] if isinstance(held, dict) else held - return result - - def _resolve_systems(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: """Turn --system into the platform's system ids, before any work. @@ -3417,16 +486,6 @@ def _pack_output_lock(output_dir: str, exclusive: bool = True) -> Iterator[None] sys.exit(1) -def _baseline_shortfall(excluded: int, absent: int) -> list[str]: - """Why a verified pack holds fewer baseline files than the platform declares.""" - parts = [] - if excluded: - parts.append(f"{excluded} unsafe excluded") - if absent: - parts.append(f"{absent} not in the collection") - return parts - - @dataclass(frozen=True) class _PackCheck: """What --verify-packs checks every pack against.""" @@ -3987,12 +1046,6 @@ def _given_flags(args: argparse.Namespace) -> set[str]: return {flag for flag, on in flags.items() if on} -# Data directories a pack needed and the cache did not hold. The pack is -# written without them, so the run cannot exit as if it were complete: a -# refresh refused by a quota left the PPSSPP pack with 2 files, exit 0. -_MISSING_DATA_DIRS: set[str] = set() - - def main() -> None: # One run's account: tests call main() repeatedly in one process, and a # notice left by an earlier run failed a later one that missed nothing. @@ -4306,7 +1359,7 @@ def _requested_platforms(args: argparse.Namespace, parser: argparse.ArgumentPars def _refresh_data_directories(args: argparse.Namespace, data_registry: dict) -> None: """Bring the data directory caches up to date before a build reads them.""" - from refresh_data_dirs import load_registry, refresh_all + from packs.datadirs import load_registry, refresh_all registry = load_registry(os.path.join(args.platforms_dir, "_data_dirs.yml")) results = refresh_all(registry, force=args.refresh_data) @@ -4446,1710 +1499,6 @@ def _main(held: contextlib.ExitStack) -> None: # Manifest generation (JSON inventory for install.py) -@functools.cache -def _registered(repo_root: str) -> frozenset[str]: - """The paths a repository's .gitignore registers as release assets, read - by the parser the fetcher and the release check use, once per root.""" - return frozenset(load_registered_paths(os.path.join(repo_root, ".gitignore"))) - - -def _is_release_asset(local_path: str, repo_root: str) -> bool: - """Whether the installer fetches this file from the large-files release. - - The repository serves every committed file from its raw URL. Only the - files kept out of git live as release assets, and .gitignore is the - ledger of those. Size is not the criterion: a committed file over 50 MB - is still served by the repository, and announcing it as a release asset - sends the installer to an asset nobody uploaded. - """ - return _repo_relative(local_path, repo_root) in _registered(repo_root) - - -def _repo_relative(local_path: str, repo_root: str) -> str: - try: - return os.path.relpath(local_path, repo_root) - except ValueError: - return "" - - -def _release_asset_name(local_path: str, repo_root: str) -> str: - """The large-files asset install.py downloads for a gitignored file. - - The name GitHub serves, not the one uploaded: a space in the path came - back as a 404 for an installer asking for it verbatim. - """ - return published_asset_name( - asset_name(_repo_relative(local_path, repo_root), sorted(_registered(repo_root))) - ) - - -def _get_repo_path(sha1: str, db: dict) -> str: - """Get the repo path for a file by SHA1 lookup.""" - entry = db.get("files", {}).get(sha1, {}) - return entry.get("path", "") - - -# The database the index was built from, held so its identity stays its own. -_DB_SHA1_BY_PATH: list[tuple[dict, dict[str, str]]] = [] - - -def _db_sha1_by_path(db: dict) -> dict[str, str]: - """Path -> sha1 of the database, built once per database.""" - if _DB_SHA1_BY_PATH and _DB_SHA1_BY_PATH[0][0] is db: - return _DB_SHA1_BY_PATH[0][1] - index = { - os.path.normpath(entry["path"]): sha1 - for sha1, entry in db.get("files", {}).items() - if entry.get("path") - } - _DB_SHA1_BY_PATH[:] = [(db, index)] - return index - - -# The hashes a manifest entry records, and each file's once verified. -_MANIFEST_HASHES = frozenset({"sha1", "sha256"}) -_STABLE_HASHES: dict[tuple, dict] = {} - - -def _placed_copies(copies: list[dict], dests: list[str]) -> list[dict]: - """Each standalone copy with the path this manifest gives its file. - - The registry names one path per file for every platform (one anchor), - while each manifest places the file its own way: EmuDeck installs - aes_keys.txt at the root and Batocera prod.keys under switch/, so the - installer looked for Citra/sysdata/aes_keys.txt, found nothing and - copied nothing. `file` stays as written, since it also lays out a custom - emulator root. `source` says where the installed file is. - """ - by_name: dict[str, list[str]] = {} - for dest in dests: - by_name.setdefault(dest.rsplit("/", 1)[-1].casefold(), []).append(dest) - placed: list[dict] = [] - for copy in copies: - wanted = copy.get("file") - if not wanted or wanted in dests: - placed.append(copy) - continue - tail = [d for d in dests if d.endswith("/" + wanted)] - if tail: - # The file whose path carries the least on top of the tail. - shortest = min(len(d) for d in tail) - tail = [d for d in tail if len(d) == shortest] - else: - tail = by_name.get(wanted.rsplit("/", 1)[-1].casefold(), []) - placed.append({**copy, "source": tail[0]} if len(tail) == 1 else copy) - return placed - - -# data_root keys of the profiles, as the copy targets name each system. -_DATA_ROOT_SYSTEMS = {"linux": "linux", "macos": "darwin", "windows": "windows", - "android": "android"} - - -def _data_root_target(system: str, text: str) -> str | None: - """A profile's data_root on one system as a copy target, or None when it - names no place a run can find: a folder beside an executable, a working - directory, a folder picked in the app. Of `A, else B` the alternative - under the home is kept, the default the registry's targets write. - """ - for choice in (part.strip() for part in text.split(", else ")): - if "<" in choice: - continue - if system == "windows" and re.match(r"^%[A-Za-z0-9_()]+%/", choice): - return choice.replace("/", "\\") - if system == "android" and choice.startswith("Android/data/"): - return "$EXTERNAL_STORAGE/" + choice - if system in ("linux", "darwin"): - if choice.startswith("~/"): - return "$HOME/" + choice[2:] - if choice.startswith("$HOME/"): - return choice - return None - - -def _one_content(held: list[str], entries: dict[str, dict], emulator: str) -> list[str]: - """The one dest a copy reads when every held dest carries the same bytes. - - Unchanged when the contents differ: the name then designates nothing. - """ - if len({entries[dest].get("sha1") for dest in held}) != 1: - return held - own = [dest for dest in held if emulator in (entries[dest].get("cores") or ())] - return [min(own or held, key=lambda dest: (dest.count("/"), len(dest), dest))] - - -def _profile_roots(profile: dict) -> dict[str, str]: - """The data_root of each system the profile names a findable place for.""" - return { - _DATA_ROOT_SYSTEMS[key]: target - for key, value in (profile.get("data_root") or {}).items() - if key in _DATA_ROOT_SYSTEMS and isinstance(value, dict) - and (target := _data_root_target(_DATA_ROOT_SYSTEMS[key], value.get("path", ""))) - } - - -def _copy_source( - entry: dict, - by_tail: dict[str, list[str]], - entries: dict[str, dict] | None, - profile_name: str, -) -> str | None: - """The manifest dest a profile entry's standalone copy is taken from.""" - standalone = entry.get("standalone_path") - if (not standalone or standalone.endswith("/") or entry.get("mode") == "libretro" - or entry.get("type") == "directory" or entry.get("found_by") == "content"): - return None - held = by_tail.get(entry.get("path") or entry["name"], []) - if len(held) > 1 and entries is not None: - held = _one_content(held, entries, profile_name) - if len(held) != 1: - return None - return held[0] - - -def _profile_copies( - profiles: dict[str, dict], dests: list[str], declared: list[dict], - entries: dict[str, dict] | None = None, -) -> list[dict]: - """The standalone copies the emulator profiles document: each file with - a standalone_path, into the data_root of each system that names a place. - - The registry's list was kept by hand for eight emulators, while the - profiles give the folder of 61 with the code that builds it: a machine - with standalone Cemu only got none of its keys. A target the registry - already gives for the same name is left to it, and a file the manifest - does not carry, or carries under the save directory, has no source. A - file found by content (found_by) sits wherever the folder the user set - for the scan points: Amiberry reads its ROMs from rom_path, which - amiberry.conf moves, so its name under data_root proves nothing. - ``entries`` maps each dest to its manifest entry: one file carried at - two paths with the same bytes is one source, the copy whose cores name - the emulator, else the shortest path. DuckStation's ps2_scph50006.bin - sits at the BIOS root and under pcsx2/bios/ for the libretro PS2 cores. - """ - from fnmatch import fnmatch - - taken: list[tuple[str, str, str, bool]] = [] - for copy in declared: - name = copy.get("pattern") or PurePosixPath(copy.get("file", "")).name - for system, targets in (copy.get("targets") or {}).items(): - taken += [(system, target, name, "pattern" in copy) for target in targets] - - def covered(system: str, target: str, name: str) -> bool: - return any( - system == t_system and target == t_target - and (fnmatch(name, t_name) if is_pattern else name == t_name) - for t_system, t_target, t_name, is_pattern in taken - ) - - by_tail: dict[str, list[str]] = {} - for dest in dests: - parts = dest.split("/") - for start in range(len(parts)): - by_tail.setdefault("/".join(parts[start:]), []).append(dest) - copies: list[dict] = [] - for profile_name in sorted(profiles): - profile = profiles[profile_name] - roots = _profile_roots(profile) - if not roots: - continue - for entry in profile.get("files", []): - source = _copy_source(entry, by_tail, entries, profile_name) - if source is None: - continue - where = PurePosixPath(entry["standalone_path"]) - placed: dict[str, list[str]] = {} - for system, root in roots.items(): - sep = "\\" if system == "windows" else "/" - target = root if str(where.parent) == "." else ( - root + sep + str(where.parent).replace("/", sep)) - if not covered(system, target, where.name): - placed[system] = [target] - if not placed: - continue - copy = {"file": source, "targets": placed} - if where.name != PurePosixPath(source).name: - copy["as"] = where.name - copies.append(copy) - return copies - - -def _standalone_copies( - declared: list[dict], profiles: dict[str, dict], manifest_files: list[dict], -) -> list[dict]: - """A manifest's standalone copies: the registry's, placed where this - manifest puts each file, then the ones the profiles document. A platform - whose registry entry declares none gets none.""" - if not declared: - return [] - kept = [entry for entry in manifest_files if entry.get("root") != "save"] - dests = [entry["dest"] for entry in kept] - entries = {entry["dest"]: entry for entry in kept} - return _placed_copies(declared, dests) + _profile_copies(profiles, dests, declared, entries) - - -def _stable_hashes(local_path: str, db: dict) -> dict: - """The file's hashes, held against the scan that built the database. - - A manifest entry is what every installer downloads and checks against. - Under load this host has hashed a 252 MB DSi NAND to a sha1 no file - holds, twice and the same way, so recomputing alone proves nothing: the - database scanned the same path, and a manifest that disagrees with it is - refused rather than published. - """ - stat = os.stat(local_path) - expected = _db_sha1_by_path(db).get(os.path.normpath(local_path)) - # Keyed by what was checked, the sha1 this database expects there, never - # by id(db): a database freed and replaced at the same address answered - # with hashes verified against the first one. - key = (os.path.normpath(local_path), stat.st_size, stat.st_mtime_ns, expected) - known = _STABLE_HASHES.get(key) - if known is not None: - # Verified against the scan once: twelve manifests name a file up - # to a dozen times, and rehashing it each time spent 163 s of 218. - return known - hashes = compute_hashes(local_path, _MANIFEST_HASHES) - for _attempt in range(2): - if expected is None or hashes["sha1"] == expected: - _STABLE_HASHES[key] = hashes - return hashes - # Read from disk again: the cached digest is the one in doubt, and a - # retry through the cache answered with it without a second read. - hashes = compute_hashes(local_path, _MANIFEST_HASHES, cache=False) - raise RuntimeError( - f"{local_path}: sha1 {hashes['sha1']} contradicts the database scan " - f"({expected}). Rehash the file or regenerate database.json" - ) - - -def _manifest_entry( - local_path: str | None, - dest: str, - cores: list[str] | None, - db: dict, - repo_root: str, - selection_fields: dict, -) -> tuple[dict | None, int]: - """The download record of a resolved file, and the size it occupies. - - The installer fetches by hash, so the entry records the copy this - repository holds: an upstream hash carried by no local file resolves to - no URL. An entry needs somewhere to be fetched from, and a file the - database does not index (a data directory, a copy added since the last - scan, a hash computed wrong) has neither a repo path nor a release - asset. None then, so the caller records an omission instead of a dead - entry that makes the installer refuse the whole manifest. - `selection_fields` carries what the installer narrows on. - """ - sha1 = "" - sha256 = "" - file_size = 0 - if local_path and os.path.exists(local_path): - file_size = os.path.getsize(local_path) - hashes = _stable_hashes(local_path, db) - sha1 = hashes["sha1"] - sha256 = hashes["sha256"] - repo_path = _get_repo_path(sha1, db) if sha1 else "" - is_release_asset = _is_release_asset(local_path or "", repo_root) - if not repo_path and not is_release_asset: - return None, file_size - entry: dict = { - "dest": dest, - "sha1": sha1, - "sha256": sha256, - "size": file_size, - "repo_path": repo_path, - "cores": cores, - **selection_fields, - } - if local_path and is_release_asset: - entry["storage"] = "release" - entry["release_asset"] = _release_asset_name(local_path, repo_root) - # The installer writes what it downloads with the umask's mode, but a program - # (RetroDECK's pico8, vox) has to stay runnable. The git mode cannot say: - # hundreds of MAME archives carry an execute bit nothing reads. - if local_path and _is_program(local_path): - entry["executable"] = True - return entry, file_size - - -_PROGRAM_MAGIC = ( - b"\x7fELF", - b"#!", - b"\xcf\xfa\xed\xfe", - b"\xce\xfa\xed\xfe", - b"\xca\xfe\xba\xbe", -) - - -def _is_program(path: str) -> bool: - """An ELF or Mach-O binary, or a script with an interpreter line.""" - with open(path, "rb") as handle: - head = handle.read(4) - return any(head.startswith(magic) for magic in _PROGRAM_MAGIC) - - -@dataclass(frozen=True) -class _ClaimContext: - """How a manifest resolves and judges the copy a core claim names.""" - - db: dict - bios_dir: str - zip_contents: dict | None - offline: bool | None - required_only: bool - validation_index: dict | None - owners: dict | None - repo_root: str - data_registry: dict | None = None - - -def _attach_claims( - entry: dict, - claims: list[dict], - ctx: _ClaimContext, - dest: str, - manifest_dest: str, -) -> None: - """Every other core that reads this destination, in the order the builder - meets them: a pack built without the earlier cores, or without the - platform system that declares the file, carries the first remaining - one's copy. - - A claim joins the copy just before it when the bytes agree and starts an - alternative otherwise. It never joins an earlier copy, which would let it - win over a core the builder tries first. Only a core's first claim can - win: its later ones are reached only when that one is. A platform entry - names no core, so its first claim always starts an alternative. - """ - claimed = set(entry["cores"] or []) - for claim in claims: - claim_emu = claim.get("source_profile") or claim.get("source_emulator", "") - if not claim_emu or claim_emu in claimed: - continue - claimed.add(claim_emu) - if ctx.required_only and claim.get("required") is False: - continue - claim_path, claim_status = resolve_file( - claim, ctx.db, ctx.bios_dir, ctx.zip_contents, - dest_hint=claim.get("destination", ""), - data_dir_registry=ctx.data_registry, offline=ctx.offline, - ) - if claim_status in ("not_found", "external", "user_provided") or not claim_path: - # Nothing held for this core: narrowed to it without the cores - # served above, the slot is a file left out (installer replays it). - entry.setdefault("absent_claims", []).append( - _absent_claim(claim, claim_emu, claim_status) - ) - continue - claim_path, _ = validated_choice( - claim, claim_path, ctx.db, ctx.validation_index or {}, ctx.bios_dir, None, - claim.get("layout_path") or dest, ctx.owners, - ) - copy, _size = _manifest_entry( - claim_path, manifest_dest, [claim_emu], ctx.db, ctx.repo_root, {} - ) - if copy is None: - continue - alternatives = entry.setdefault("alternatives", []) - last = alternatives[-1] if alternatives else entry - if last["cores"] is not None and copy["sha1"] == last["sha1"]: - if claim_emu not in last["cores"]: - last["cores"].append(claim_emu) - continue - del copy["dest"] - alternatives.append(copy) - if not entry.get("alternatives"): - entry.pop("alternatives", None) - - -def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict: - """The omission a claim with nothing held stands for.""" - systems = _extra_system_ids(claim) - return { - "name": str(claim.get("name") or ""), - "system": systems[0] if systems else "", - "required": bool(claim.get("required", True)), - "reason": ( - claim_status - if claim_status in ("not_found", "external", "user_provided") - else "not_found" - ), - "cores": [claim_emu], - } - - -def _record_slot_choices( - entry: dict, - choices: list[tuple[str, str | None]], - declarations: list[tuple[list[str], dict, str]], - settle: Callable[[dict, str, str, str | None], tuple[str | None, str]], - dest: str, - db: dict, - repo_root: str, -) -> None: - """Record what a pack built for fewer cores serves at a platform destination. - - `slot_choices` lists, in the order slots decides, the cores whose claim - settles the slot and the copy it serves, a choice without a copy leaving - the platform's answer. `declared_choices` is the platform's answer by the - declaring systems that remain, in the order the builder takes them. - Nothing is recorded where every narrowing gets the entry's own copy. - """ - - def download(file_entry: dict, sys_id: str, override: str | None) -> dict | None: - local_path, _status = settle(file_entry, sys_id, dest, override) - if local_path is None: - return None - copy, _size = _manifest_entry(local_path, dest, None, db, repo_root, {}) - if copy is None: - return None - return {k: v for k, v in copy.items() if k not in ("dest", "cores")} - - declared: list[dict] = [] - for systems, file_entry, sys_id in declarations: - copy = download(file_entry, sys_id, None) - if copy is None: - # An omission is not a copy the installer can switch to. - return - if declared and declared[-1]["sha1"] == copy["sha1"]: - declared[-1]["systems"].extend(systems) - else: - declared.append({**copy, "systems": list(systems)}) - _systems, first, first_sys = declarations[0] - recorded: list[dict] = [] - seen: set[str] = set() - for emulator, path in choices: - if emulator in seen: - continue - seen.add(emulator) - copy = {} if path is None else download(first, first_sys, path) - if copy is None: - return - if recorded and recorded[-1].get("sha1") == copy.get("sha1"): - recorded[-1]["cores"].append(emulator) - else: - recorded.append({**copy, "cores": [emulator]}) - while recorded and "sha1" not in recorded[-1]: - recorded.pop() - if not recorded and len(declared) == 1: - return - if recorded: - entry["slot_choices"] = recorded - entry["declared_choices"] = declared - - -class _CoreEntryState(TypedDict): - """What _manifest_core_entries reads and fills of the manifest being listed.""" - - region_drops: set - case_insensitive: bool - seen_destinations: set - seen_lower: set - seen_parents: set - manifest_files: list - omitted_by_destination: dict - record_omission: Callable[..., None] - pack_only_sizes: list[int] - selection: SelectionIndex - - -class _CoreEntryParts(_CoreEntryState, total=False): - """_CoreEntryState and the optional keywords of _manifest_core_entries.""" - - required_only: bool - validation_index: dict | None - owners: dict | None - data_registry: dict | None - profiles: dict | None - - -@dataclass -class _CoreEntryLister: - """Lists a platform's core extras into the manifest, one at a time.""" - - config: dict - base_dest: str - ctx: _ClaimContext - state: _CoreEntryParts - resolver: ExtraResolver - total_size: int = 0 - extras_pfx: str = field(init=False) - - def __post_init__(self) -> None: - self.extras_pfx = _detect_extras_prefix(self.config, self.base_dest) - - def region_key(self, fe: dict) -> str: - return extra_region_key(fe, declared_root(self.config)) - - def region_dropped(self, fe: dict) -> bool: - drops = self.state["region_drops"] - return bool(drops) and self.region_key(fe) in drops - - def list_extra(self, fe: dict) -> None: - state = self.state - dest = sanitize_pack_path(fe.get("destination", fe["name"])) - if not dest: - return - region_key = self.region_key(fe) - if state["region_drops"] and region_key in state["region_drops"]: - return - full_dest = extra_full_destination(fe, self.extras_pfx) - if not full_dest: - return - - if ( - state["case_insensitive"] - and full_dest not in state["seen_destinations"] - and full_dest.lower() in state["seen_lower"] - ): - self._join_spelling(fe, full_dest, dest) - return - - if placement_block( - full_dest, state["seen_destinations"], state["seen_lower"], state["seen_parents"], - state["case_insensitive"], - ): - return - - # The builder's own lookup (ExtraResolver): the data directories, the - # copy the emulator accepts, and the size its code checks. Without - # the data directories blueMSX's MSX2P.rom named a different dump - # than the one its pack carried. - local_path, status, _disagreement = self.resolver.resolve(fe, dest) - if not local_path: - self._omit(fe, full_dest, status) - return - self._list_held(fe, dest, full_dest, region_key, local_path) - - def _join_spelling(self, fe: dict, full_dest: str, dest: str) -> None: - # One file under two spellings: BlastEm opens 32X_M_BIOS.bin and - # PicoDrive 32X_M_BIOS.BIN. The second core's claim joins the - # entry kept, or a pack built without the first core loses the - # file the installer would still have to place. Collisions are - # rare, so the entry is looked up only when one happens. - save_root = fe.get("root") == "save" - folded = ( - save_manifest_dest(fe) if save_root - else _manifest_dest_of(full_dest, self.base_dest) - ).lower() - held = next( - (e for e in self.state["manifest_files"] - if e["dest"].lower() == folded - and (e.get("root") == "save") == save_root), - None, - ) - if held is not None and held.get("cores") is not None: - _attach_claims(held, [fe], self.ctx, dest, held["dest"]) - - def _omit(self, fe: dict, full_dest: str, reason: str) -> None: - source_emu = fe.get("source_profile") or fe.get("source_emulator", "") - if not _claim_platform_omission( - self.state["omitted_by_destination"].get(full_dest), source_emu - ): - systems = _extra_system_ids(fe) - self.state["record_omission"]( - full_dest, fe, systems[0] if systems else "", reason, _claim_cores(fe), - ) - - def _list_held( - self, fe: dict, dest: str, full_dest: str, region_key: str, local_path: str, - ) -> None: - state = self.state - source_emu = fe.get("source_profile") or fe.get("source_emulator", "") - save_root = fe.get("root") == "save" - - # Manifest dests are relative to base_destination. Keep the inferred - # extras prefix when it is an internal layout dir (RetroDECK bios/). - # A file read below the save directory is written relative to the - # directory the core is handed, and says so (save_entry_fields). - outer_root = fe.get("root") if fe.get("root") in OUTER_ROOTS else None - if save_root: - manifest_dest = save_manifest_dest(fe) - elif outer_root: - # Relative to the roms or emulators folder the entry names. - manifest_dest = dest - else: - manifest_dest = _manifest_dest_of(full_dest, self.base_dest) - - entry, file_size = _manifest_entry( - local_path, manifest_dest, [source_emu] if source_emu else [], - self.ctx.db, self.ctx.repo_root, - state["selection"].fields(region_key, fe.get("name", "")), - ) - if entry is not None and save_root: - entry.update(save_entry_fields(fe)) - elif entry is not None and outer_root: - entry["root"] = outer_root - if entry is None: - self._omit(fe, full_dest, "not_found") - if file_size: - state["pack_only_sizes"].append(file_size) - return - - if is_game_data(fe) and all( - is_game_data(claim) for claim in fe.get("other_claims", []) - ): - entry["category"] = GAME_DATA - _attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest) - - state["manifest_files"].append(entry) - displaced = state["omitted_by_destination"].pop(full_dest, None) - if displaced and displaced.get("cores"): - # A core that wants this slot and has nothing held: a pack built - # without the cores served here leaves the slot to it, missing, - # and the installer narrowing to those cores has to say so too. - entry.setdefault("absent_claims", []).append( - {k: v for k, v in displaced.items() if k not in ("dest", "held")} - ) - self.total_size += file_size - state["seen_destinations"].add(full_dest) - _register_path(full_dest, state["seen_destinations"], state["seen_parents"]) - if state["case_insensitive"]: - state["seen_lower"].add(full_dest.lower()) - - -def _manifest_core_entries( - core_files: list, - config: dict, - db: dict, - bios_dir: str, - base_dest: str, - repo_root: str, - zip_contents: dict | None, - offline: bool | None, - **state: Unpack[_CoreEntryParts], -) -> int: - """Add the files a platform's cores need but its list does not name. - - The installer fetches by hash, so an entry records the copy this - repository holds rather than the value the profile declares: an - upstream hash carried by no local file leaves the entry with no URL. - Returns the bytes added. - """ - _reject_unknown( - "_manifest_core_entries", state, - _CoreEntryParts.__required_keys__ | _CoreEntryParts.__optional_keys__, - ) - required_only = state.get("required_only", False) - ctx = _ClaimContext( - db, bios_dir, zip_contents, offline, required_only, - state.get("validation_index"), state.get("owners"), repo_root, - state.get("data_registry"), - ) - lister = _CoreEntryLister( - config, base_dest, ctx, state, - ExtraResolver( - db, bios_dir, zip_contents, ctx.data_registry, ctx.validation_index or {}, - ctx.owners, offline, profiles=state.get("profiles"), - ), - ) - spares = core_file_spares(core_files, lister.region_dropped) if required_only else set() - for fe in core_files: - if required_only and (fe.get("required") is False or id(fe) in spares): - continue - lister.list_extra(fe) - return lister.total_size - - -def _manifest_dest_of(full_dest: str, base_dest: str) -> str: - """A pack destination as the manifest writes it, below base_destination.""" - if base_dest and full_dest.startswith(f"{base_dest}/"): - return full_dest[len(base_dest) + 1:] - return full_dest - - -def _claim_platform_omission(held: dict | None, emulator: str) -> bool: - """Record a core's claim on a destination the platform already omits. - - The platform's own omission stands while one of its declaring systems - does. A pack built without them falls to the first core claiming the - path, as for a file present. Overwriting the record lost the platform's - claim: a target without that core dropped an omission its pack reports. - """ - if held is None or held.get("cores") is not None: - return False - if emulator: - claims = held.setdefault("alternatives", []) - if {"cores": [emulator]} not in claims: - claims.append({"cores": [emulator]}) - return True - - -class _SelectionOptions(TypedDict, total=False): - """The keyword options of _manifest_selection.""" - - required_only: bool - regions: list[str] | None - undeclared: list[dict] | None - zip_contents: dict | None - data_registry: dict | None - slot_overrides: dict[str, str] | None - one_per_slot: bool - - -def _manifest_selection( - config: dict, - pack_systems: dict, - emulators_dir: str, - db: dict, - base_dest: str, - emu_profiles: dict, - target_cores: set[str] | None, - source: str, - **options: Unpack[_SelectionOptions], -) -> tuple[set[str], SelectionIndex, set[str]]: - """Destinations a region list and --one-per-slot remove, the groups the - installer replays, and the destinations the builder holds. - - Grouped as the pack groups them, so a region or a slot the installer - decides on the full manifest withdraws what `--region` and - `--one-per-slot` withdraw from the pack. - """ - _reject_unknown("_manifest_selection", options, _SelectionOptions.__optional_keys__) - required_only = options.get("required_only", False) - regions = options.get("regions") - one_per_slot = options.get("one_per_slot", False) - extras: list[dict] = [] - held: set[str] = set() - region_groups, _extra_dests = platform_region_groups( - config, - pack_systems, - emulators_dir, - db, - base_dest, - emu_profiles, - target_cores=target_cores, - include_extras=(source != "platform"), - include_all=(source == "truth"), - required_only=required_only, - extras_out=extras, - held_out=held, - undeclared=options.get("undeclared"), - zip_contents=options.get("zip_contents"), - data_registry=options.get("data_registry"), - slot_overrides=options.get("slot_overrides"), - ) - region_index = resolve_regions.platform_region_index( - config, emu_profiles, target_cores - ) - drops = ( - resolve_regions.resolve_region_drops(region_groups, region_index, regions, held) - if regions - else set() - ) - if one_per_slot: - drops = drops | _slot_drops( - config, emu_profiles, target_cores, region_groups, drops, held - )[0] - return drops, SelectionIndex.build( - region_groups, region_index, pack_systems, extras, required_only, - extras_prefix=declared_root(config), - slot_claims=slot_mod.platform_slot_claims(config, emu_profiles, target_cores), - ), held - - -def _claim_cores(fe: dict) -> list[str]: - """The cores an extra and the claims folded onto it name: an omission - names every core reading the file, as a list built for one of them - would.""" - names = { - claim.get("source_profile") or claim.get("source_emulator", "") - for claim in (fe, *fe.get("other_claims", [])) - } - return sorted(name for name in names if name) - - -def _record_absent( - absent: list[dict], - config: dict, - base_dest: str, - region_drops: set, - required_only: bool, - seen_destinations: set, - omitted_by_destination: dict, - record_omission: Callable[..., None], -) -> None: - """A file a core needs that the collection does not hold is an omission. - - Left out of both lists, DevilutionX's diabdat.mpq and dhewm3's - pak000-004 reached no safety notice: the installer said everything - was verified and the game refused to start. - """ - extras_pfx = _detect_extras_prefix(config, base_dest) - for fe in absent: - if required_only and fe.get("required") is False: - continue - dest = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) - if not dest or ( - region_drops and extra_region_key(fe, declared_root(config)) in region_drops - ): - continue - full_dest = extra_full_destination(fe, extras_pfx) - if not full_dest or full_dest in seen_destinations: - continue - source_emu = fe.get("source_profile") or fe.get("source_emulator", "") - held = omitted_by_destination.get(full_dest) - if held is not None: - # Another core reads the same missing file there (Raze and - # EDuke32 both open NAPALM.GRP): one omission names them all. - claimed = held.get("cores") - if (held.get("reason") == "not_found" and claimed and source_emu - and source_emu not in claimed): - held["cores"] = sorted([*claimed, source_emu]) - continue - systems = _extra_system_ids(fe) - record_omission( - full_dest, fe, systems[0] if systems else "", "not_found", - [source_emu] if source_emu else [], - ) - - -# What a manifest's roms_directory and emulators_directory carry: the BIOS -# folder's name, for the roms root its place relative to the BIOS folder -# (romfolders roms_root.from_bios), and for emulator folders the places the -# launcher searches, the one a missing folder is created at, and the config -# file whose key moves a folder. -MANIFEST_OUTER_FIELDS = ("bios_folder", "from_bios", "searched", "default", "config") - - -def _record_unplaceable( - unplaceable: list[dict], - record_omission: Callable[..., None], - config: dict, - profiles: dict[str, dict], -) -> None: - """Held by the collection, nowhere to put it on this platform. - - Said in the manifest, where RomM's DOSBox Pure ROMs were simply absent. - One place read by several cores is one omission naming them all. - """ - # The emulator's own folder is the one the platform installs the name - # it lists into: RetroPie puts amiberry 5.7.2 and 6.3.3, one per board, - # both in $md_inst of its amiberry package. - platform_names = { - str(c) for key in ("cores", "standalone_cores") - if isinstance(config.get(key), list) for c in config[key] - } - - def folder(profile: str) -> str: - names = {profile, *map(str, (profiles.get(profile) or {}).get("cores") or [])} - return min(names & platform_names, default=profile) - - grouped: dict[str, tuple[dict, list[str]]] = {} - for u in unplaceable: - where = u.get("path") or u.get("name", "") - # The profile key, the name a target's core list and the - # installer's narrowing match: the display name matched none. - core = u.get("profile") or u.get("emulator", "") - if u.get("unplaced"): - key = f"emulator:{folder(core)}:{where}" - elif u.get("root") in OUTER_ROOTS: - key = f"{u['root']}:{where}" - elif u.get("root") == "save": - key = f"save:{save_manifest_dest(u)}" - else: - key = where - held, cores = grouped.setdefault(key, (u, [])) - if core and core not in cores: - cores.append(core) - if u.get("required", True) and not held.get("required", True): - grouped[key] = ({**held, "required": True}, cores) - for key, (u, cores) in grouped.items(): - record_omission( - # Keyed apart from the BIOS tree's paths, which a file read below - # the save directory or in the emulator's folder can repeat. - key, u, u.get("system") or "", - u.get("unplaceable", "no_platform_slug"), sorted(cores), - ) - - -# Systems whose default filesystems fold case (NTFS, APFS, HFS+). -CASE_FOLDING_OS = frozenset({"windows", "darwin"}) - - -def system_titles(*entry_lists: Iterable[dict]) -> dict[str, str]: - """The name a person reads for each system the entries carry. - - Batocera names PlayStation `psx` and the installer showed - `sony-playstation (psx)`: neither is what a beginner looks for. The - title is the one the site prints, so a system reads the same on its - page and in the installer. A system the site cannot name is left out, - and the installer shows its id: the site build refuses such a system, - so only a test fixture reaches here with one. - """ - from siterender import system_name - - ids = { - sys_id - for entries in entry_lists for entry in entries - for sys_id in entry.get("systems") or [] - } - titles: dict[str, str] = {} - for sys_id in sorted(ids): - try: - titles[sys_id] = system_name(sys_id) - except KeyError: - continue - return titles - - -class InstallListOptions(TypedDict, total=False): - """The keyword options of generate_install_list, which it hands to - generate_manifest.""" - - emulators_dir: str - zip_contents: dict | None - emu_profiles: dict | None - target_cores: set[str] | None - source: str - regions: list[str] | None - target_name: str | None - offline: bool | None - required_only: bool - data_registry: dict | None - fold_case: bool | None - no_game_data: bool - one_per_slot: bool - - -class ManifestOptions(InstallListOptions, total=False): - """The keyword options of generate_manifest.""" - - known_slot_choices: dict | None - build_out: dict | None - - -@dataclass(frozen=True) -class _ManifestSettings: - """ManifestOptions with their defaults.""" - - emulators_dir: str = "emulators" - zip_contents: dict | None = None - emu_profiles: dict | None = None - target_cores: set[str] | None = None - source: str = "full" - regions: list[str] | None = None - target_name: str | None = None - offline: bool | None = None - required_only: bool = False - data_registry: dict | None = None - fold_case: bool | None = None - no_game_data: bool = False - one_per_slot: bool = False - known_slot_choices: dict | None = None - build_out: dict | None = None - - -@dataclass -class _ManifestBuild: - """One install manifest being listed: its files, omissions and the slots - they take, settled by the rules the pack builder follows.""" - - platform_name: str - platforms_dir: str - db: dict - bios_dir: str - opts: _ManifestSettings - config: dict - emu_profiles: dict - zip_contents: dict - data_registry: dict - game_entries: set[int] - install_section: dict - repo_root: str - pack_systems: dict - manifest_profiles: dict = field(default_factory=dict) - manifest_validation: dict = field(default_factory=dict) - manifest_owners: dict = field(default_factory=dict) - game_destinations: set[str] = field(default_factory=set) - placed: _Placed = field(init=False) - # Destination -> (entry, full destination, manifest destination) of each - # platform file, for the core claims a target build would fall back on. - platform_entries: dict[str, tuple[dict, str, str]] = field(default_factory=dict) - # Full destination -> the platform systems declaring it. A file's - # `systems` also names the systems whose cores read it there. A pack built - # for a target keeps the file only while a declaring system stays. - declared_by: dict[str, set[str]] = field(default_factory=dict) - manifest_files: list[dict] = field(default_factory=list) - omitted_by_destination: dict[str, dict] = field(default_factory=dict) - total_size: int = 0 - # Sizes of the files the pack carries and the installer cannot fetch: the - # collection does not index them, a data directory cache answered. - pack_only_sizes: list[int] = field(default_factory=list) - # Platform entries resolved into a data directory cache: destination -> - # (cache file, size). Settled once the trees are walked. - cache_held: dict[str, tuple[str, int]] = field(default_factory=dict) - rename_notes: set[str] = field(default_factory=set) - slot_choices: dict = field(default_factory=dict) - slot_overrides: dict[str, str] = field(default_factory=dict) - undeclared: list[dict] | None = None - region_drops: set[str] = field(default_factory=set) - selection: SelectionIndex | None = None - builder_held: set[str] = field(default_factory=set) - declarations: dict[str, dict[str, list[dict]]] = field(default_factory=dict) - data_members: list[tuple[str, str]] = field(default_factory=list) - data_directories: list[dict] = field(default_factory=list) - - def __post_init__(self) -> None: - self.placed = _Placed(self.case_insensitive) - - @property - def base_dest(self) -> str: - return self.config.get("base_destination", "") - - @property - def case_insensitive(self) -> bool: - return self.config.get("case_insensitive_fs", False) - - @property - def verification_mode(self) -> str: - return self.config.get("verification_mode", "existence") - - @property - def fields(self) -> SelectionIndex: - assert self.selection is not None - return self.selection - - def manifest_destination(self, full_destination: str) -> str: - return _manifest_dest_of(full_destination, self.base_dest) - - def record_omission( - self, - full_destination: str, - file_entry: dict, - system_id: str, - reason: str, - cores: list[str] | None, - ) -> None: - # A core extra (cores given) is keyed as the region pass keys it. - bare = ( - sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) - if cores is None else extra_region_key(file_entry, declared_root(self.config)) - ) - self.omitted_by_destination[full_destination] = { - **self._omission_dest(full_destination, file_entry), - "name": str(file_entry.get("name") or ""), - "system": system_id, - "required": bool(file_entry.get("required", True)), - "reason": reason, - "cores": cores, - # An omission keeps its region groups, as the builder groups it: - # a requested file the collection lacks answers the request - # without displacing a held fallback (resolve_region_drops, - # held). One the builder holds and the installer cannot fetch - # does displace it in the pack, so it says so, and the installer - # drops the same fallback. - **self.fields.fields(bare, str(file_entry.get("name") or "")), - **({"held": True} if bare in self.builder_held else {}), - **( - {"category": GAME_DATA} - if (bare in self.game_destinations if cores is None else is_game_data(file_entry)) - else {} - ), - } - - def _omission_dest(self, full_destination: str, file_entry: dict) -> dict: - # Read in the emulator's own folder, outside the BIOS tree: dest is - # the path the emulator reads, relative to that folder. - if file_entry.get("unplaced"): - return {"dest": sanitize_pack_path(file_entry.get("path") or ""), - "root": "emulator"} - if file_entry.get("root") in OUTER_ROOTS: - return {"dest": sanitize_pack_path( - file_entry.get("destination") or file_entry.get("path") or "" - ), "root": file_entry["root"]} - if file_entry.get("root") == "save": - return {"dest": save_manifest_dest(file_entry), **save_entry_fields(file_entry)} - return {"dest": self.manifest_destination(full_destination)} - - def kept_declarations(self) -> Iterator[tuple[str, dict, str, str]]: - """(system, entry, destination, full destination) of each platform - declaration this manifest keeps, in the builder's order.""" - opts = self.opts - for sys_id, system in sorted(self.pack_systems.items()): - for file_entry in system.get("files", []): - if opts.required_only and file_entry.get("required") is False: - continue - dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) - if not dest: - continue - if self.region_drops and dest in self.region_drops: - continue - full_dest = f"{self.base_dest}/{dest}" if self.base_dest else dest - yield sys_id, file_entry, dest, full_dest - - def declaration_order(self, full_dest: str) -> list[tuple[list[str], dict, str]]: - """The declarations answering a destination as its systems drop. - - A pack built for a target loses the systems no available core - reads, and the next declaration takes the destination by the - same rule: RetroArch's bare nintendo-ds dsi_bios9.bin once the - pinned nintendo-dsi one is gone. - """ - remaining = dict(self.declarations.get(full_dest, {})) - order: list[tuple[list[str], dict, str]] = [] - while remaining: - winner = _preferred_entries( - {sid: {"files": fes} for sid, fes in remaining.items()}, - self.db, self.bios_dir, self.base_dest, self.opts.required_only, - self.zip_contents, self.opts.offline, - ).get(full_dest) - first_sys, first = next( - (sid, fe) for sid, fes in sorted(remaining.items()) for fe in fes - if winner is None or id(fe) == winner - ) - systems = sorted( - sid for sid, fes in remaining.items() - if any(fe is first for fe in fes) - ) - order.append((systems, first, first_sys)) - for sid in systems: - del remaining[sid] - return order - - def list_baseline(self, settle: _Settle) -> None: - """Phase 1: the platform's own files.""" - # The same destination can be declared by more than one system, bare - # in one and hash-constrained in another. The builder lets the - # constrained sibling claim it. Without the same rule here the - # manifest named whatever answered to the name, so the pack and the - # installer disagreed about which file a destination means. - # Decided among the declarations this manifest keeps, as the pack - # does. A manifest carries no data directories. - preferred_entries = _preferred_entries( - self.pack_systems, self.db, self.bios_dir, self.base_dest, - self.opts.required_only, self.zip_contents, self.opts.offline, - ) - for sys_id, file_entry, _dest, full_dest in self.kept_declarations(): - self.declarations.setdefault(full_dest, {}).setdefault(sys_id, []).append( - file_entry - ) - for sys_id, file_entry, dest, full_dest in self.kept_declarations(): - self.declared_by.setdefault(full_dest, set()).add(sys_id) - preferred = preferred_entries.get(full_dest) - if preferred is not None and id(file_entry) != preferred: - continue - if self.placed.holds(full_dest) or self.placed.conflicts(full_dest): - continue - if file_entry.get("storage", "embedded") == "user_provided": - self._list_instructions(file_entry, sys_id, full_dest) - continue - local_path, status = settle( - file_entry, sys_id, dest, self.slot_overrides.get(full_dest) - ) - if local_path is None: - self.record_omission(full_dest, file_entry, sys_id, status, None) - continue - self._list_declared(file_entry, sys_id, dest, full_dest, local_path, settle) - - def _list_instructions(self, file_entry: dict, sys_id: str, full_dest: str) -> None: - self.record_omission( - full_dest, - file_entry, - sys_id, - "user_provided", - None, - ) - # The pack writes the instructions in the slot's place - # and holds it: one more member than the files listed. - instructions = file_entry.get( - "instructions", "Please provide this file manually." - ) - self.pack_only_sizes.append(len( - f"File needed: {file_entry['name']}\n\n{instructions}\n".encode() - )) - self.placed.take(full_dest) - - def _list_declared( - self, - file_entry: dict, - sys_id: str, - dest: str, - full_dest: str, - local_path: str, - settle: _Settle, - ) -> None: - entry, file_size = _manifest_entry( - local_path, dest, None, self.db, self.repo_root, - self.fields.fields(dest, file_entry["name"]), - ) - if entry is not None and dest in self.game_destinations: - entry["category"] = GAME_DATA - if entry is not None and self.opts.target_cores is None: - order = self.declaration_order(full_dest) - if full_dest in self.slot_choices or len(order) > 1: - _record_slot_choices( - entry, self.slot_choices.get(full_dest, []), order, - settle, dest, self.db, self.repo_root, - ) - if entry is None: - self.record_omission(full_dest, file_entry, sys_id, "not_found", None) - if file_size and full_dest not in self.placed.destinations: - if _in_data_cache(local_path, self.data_registry): - self.cache_held[full_dest] = (local_path, file_size) - else: - self.pack_only_sizes.append(file_size) - self.placed.take(full_dest) - return - - self.manifest_files.append(entry) - self.platform_entries[full_dest] = (entry, full_dest, dest) - self.omitted_by_destination.pop(full_dest, None) - self.total_size += file_size - self.placed.take(full_dest) - - def claim_context(self) -> _ClaimContext: - return _ClaimContext( - self.db, self.bios_dir, self.zip_contents, self.opts.offline, - self.opts.required_only, self.manifest_validation, self.manifest_owners, - self.repo_root, self.data_registry, - ) - - def list_core_files(self) -> None: - """Phase 2: core complement (emulator extras).""" - opts = self.opts - unplaceable: list[dict] = [] - baseline_claims: dict[str, dict] = {} - absent: list[dict] = [] - if opts.source != "platform": - core_files = _collect_emulator_extras( - self.config, - opts.emulators_dir, - self.db, - self.placed.destinations, - self.base_dest, - self.emu_profiles, - target_cores=opts.target_cores, - include_all=(opts.source == "truth"), - unplaceable=unplaceable, - baseline_claims=baseline_claims, - absent=absent, - undeclared=self.undeclared, - ) - else: - core_files = [] - _record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles) - _record_absent( - absent, self.config, self.base_dest, self.region_drops, opts.required_only, - self.placed.destinations, self.omitted_by_destination, self.record_omission, - ) - self.total_size += _manifest_core_entries( - core_files, self.config, self.db, self.bios_dir, self.base_dest, self.repo_root, - self.zip_contents, opts.offline, - region_drops=self.region_drops, case_insensitive=self.case_insensitive, - seen_destinations=self.placed.destinations, seen_lower=self.placed.lower, - seen_parents=self.placed.parents, manifest_files=self.manifest_files, - omitted_by_destination=self.omitted_by_destination, - record_omission=self.record_omission, pack_only_sizes=self.pack_only_sizes, - selection=self.fields, required_only=opts.required_only, - validation_index=self.manifest_validation, owners=self.manifest_owners, - data_registry=self.data_registry, profiles=self.emu_profiles, - ) - self._settle_claims(baseline_claims) - - def _settle_claims(self, baseline_claims: dict[str, dict]) -> None: - ctx = self.claim_context() - for key, (entry, full_dest, dest) in self.platform_entries.items(): - declared = self.declared_by.get(full_dest, set()) - if declared and declared != set(entry.get("systems") or []): - entry["declared_in"] = sorted(declared) - claims = baseline_claims.get(key, {}).get("other_claims") - if claims and any(not is_game_data(claim) for claim in claims): - # A core reads this path as firmware: a pack without game data - # still fills it. - entry.pop("category", None) - if claims: - _attach_claims(entry, claims, ctx, dest, dest) - # A platform omission narrows like a platform file: by the systems - # declaring it, which can be fewer than the ones whose cores read it. - for full_dest, omission in self.omitted_by_destination.items(): - declared = self.declared_by.get(full_dest, set()) - if ( - omission.get("cores") is None - and declared - and declared != set(omission.get("systems") or []) - ): - omission["declared_in"] = sorted(declared) - - def list_data_directories(self) -> list[int]: - """Phase 3: data directories, and the sizes the pack alone holds. - - They are not files of the collection: the installer fetches each - from its source archive and keeps the members whose hash the list - below records, the same tree the pack carries. - """ - opts = self.opts - required_only = opts.required_only - data_refs: dict[str, tuple[str, tuple[str, ...], str, bool]] = {} - reclaim = {full: path for full, (path, _size) in self.cache_held.items()} - core_trees = ([] if opts.source == "platform" - else core_data_trees(self.config, self.emu_profiles, self.platform_name, - self.data_registry, opts.target_cores)) - self.data_members = list(_data_directory_members( - self.pack_systems, self.data_registry, self.platform_name, self.base_dest, - self.case_insensitive, self.placed.destinations, self.placed.lower, - self.placed.parents, refs_out=data_refs, required_only=required_only, - core_trees=core_trees, - reclaim=reclaim, - )) - # A platform entry found in a tree the pack carries is that tree's member: - # the installer rebuilds it from the tree's archive. One found in a tree - # the pack does not carry stays omitted, held by the pack alone. - for full_dest, (_path, size) in self.cache_held.items(): - if full_dest in reclaim: - self.pack_only_sizes.append(size) - else: - self.omitted_by_destination.pop(full_dest, None) - self.data_directories = _manifest_data_directories( - self.data_members, data_refs, self.data_registry or {}, self.base_dest, - tree_readers(self.pack_systems, core_trees), self.pack_systems, - ) - return self.pack_only_sizes + [os.path.getsize(src) for src, _dest in self.data_members] - - def result(self, data_sizes: list[int]) -> dict: - opts, config, pack_systems = self.opts, self.config, self.pack_systems - manifest_files, platform_name = self.manifest_files, self.platform_name - omitted = self.omitted_by_destination - # The pack is unzipped into the BIOS folder: an entry the installer puts - # in the roms, emulators or configs folder is in its list, not in the ZIP. - outer = [e for e in manifest_files if e.get("root") in OUTER_ROOTS] - core_names, system_cores = _manifest_core_index( - config, self.emu_profiles, manifest_files, list(omitted.values()) - ) - result: dict = { - "manifest_version": 2, - "source": opts.source, - "regions": list(opts.regions or []), - # A target-filtered manifest is only distinguishable from the full one - # by its filename, so it records the filter the way regions does. - # Absent on an unfiltered manifest rather than empty, to leave the - # twelve default files byte-identical. - **({"target": opts.target_name} if opts.target_name else {}), - # Every game data file below says so: the installer's --no-game-data - # relies on it, and refuses a list that does not record categories. - "categorized": True, - # The entries a slot decides carry `slot`, which --one-per-slot - # reads: without this mark the installer refuses it. - "slot_fields": True, - **({"no_game_data": True} if opts.no_game_data else {}), - "platform": platform_name, - "display_name": config.get("platform", platform_name), - "version": platform_list_version(config, platform_name), - "generated": _build_timestamp(self.db), - "base_destination": self.base_dest, - "detect": self.install_section.get("detect", []), - "standalone_copies": _standalone_copies( - self.install_section.get("standalone_copies", []), self.manifest_profiles, - manifest_files, - ), - "total_files": len(manifest_files), - "total_size": self.total_size, - "pack_files": ( - len(manifest_files) - len(outer) + len(data_sizes) + len(PACK_DOCUMENTS) - + len(self.rename_notes) - + len(pack_markers(platform_name, opts.target_name, self.platforms_dir)) - ), - "pack_size": self.total_size - sum(int(e.get("size") or 0) for e in outer) - + sum(data_sizes), - "total_omitted": len(omitted), - "omitted_files": sorted( - omitted.values(), key=lambda entry: entry["dest"] - ), - "core_names": core_names, - **({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores( - config, self.emu_profiles, core_names, self.platforms_dir, - )) else {}), - **({"offered_boards": offered} if (offered := _offered_boards( - config, self.emu_profiles, core_names, - [*manifest_files, *omitted.values()], - )) else {}), - "system_cores": system_cores, - # The names the platform itself gives its systems (Batocera's psx), - # which --system accepts beside the ids. - "system_names": platform_system_names(config, list(pack_systems)), - "system_titles": system_titles(manifest_files, omitted.values()), - "files": manifest_files, - } - if self.data_directories: - result["data_directories"] = self.data_directories - self._outer_directories(result) - return result - - def _outer_directories(self, result: dict) -> None: - for root in OUTER_ROOTS: - layout = outer_layout(self.config, root) or {} - if layout and any(entry.get("root") == root - for entry in [*self.manifest_files, *result["omitted_files"]]): - # Where the installer finds the folder: relative to the folder - # holding the BIOS folder, which the platform names bios_folder. - result[f"{root}_directory"] = { - key: layout[key] for key in MANIFEST_OUTER_FIELDS if key in layout - } - saved = [entry for entry in self.manifest_files if entry.get("root") == "save"] - if saved: - save = save_layout(self.config) - result["save_directory"] = {"folder": save.folder, "by_core": save.by_core} - if save.by_system: - # The launcher writes the directory at each launch, one folder - # per system: each dest starts with that folder. - result["save_directory"]["by_system"] = True - - -def _start_manifest( - platform_name: str, - platforms_dir: str, - db: dict, - bios_dir: str, - registry_path: str, - opts: _ManifestSettings, -) -> tuple[_ManifestBuild, dict]: - """The manifest's configuration and scope, and the profiles before the - game data cut.""" - config = load_platform_config(platform_name, platforms_dir) - if opts.fold_case is not None: - config = {**config, "case_insensitive_fs": opts.fold_case} - if opts.target_name: - config = {**config, TARGET_KEY: opts.target_name} - zip_contents = {} if opts.zip_contents is None else opts.zip_contents - emu_profiles = opts.emu_profiles - if emu_profiles is None: - emu_profiles = load_emulator_profiles(opts.emulators_dir) - data_registry = opts.data_registry - if data_registry is None: - data_registry = load_data_dir_registry(platforms_dir) - full_profiles = emu_profiles - game_entries: set[int] = set() - if opts.no_game_data: - cut = without_game_data(config, emu_profiles, data_registry, opts.target_cores) - config, emu_profiles = cut.config, cut.profiles - else: - game_entries = platform_game_data(config, emu_profiles, data_registry) - - # Load registry for install metadata - registry: dict = {} - if os.path.exists(registry_path): - with open(registry_path) as f: - registry = yaml_load(f) or {} - plat_registry = registry.get("platforms", {}).get(platform_name, {}) - - plat_cores = _platform_cores(config, emu_profiles) if opts.target_cores else None - pack_systems = filter_systems_by_target( - config.get("systems", {}), - emu_profiles, - opts.target_cores, - platform_cores=plat_cores, - ) - build = _ManifestBuild( - platform_name, platforms_dir, db, bios_dir, opts, config, emu_profiles, - zip_contents, data_registry, game_entries, plat_registry.get("install", {}), - str(REPO_ROOT), pack_systems, - ) - build.manifest_profiles = { - name: emu_profiles[name] - for name in _platform_cores(config, emu_profiles) - } - build.manifest_validation = _build_validation_index(build.manifest_profiles) - build.manifest_owners = destination_owners(build.manifest_profiles) - _settle_manifest_scope(build) - return build, full_profiles - - -def _settle_manifest_scope(build: _ManifestBuild) -> None: - """Game data destinations, slot choices and the region selection.""" - opts, config, emu_profiles = build.opts, build.config, build.emu_profiles - # A destination is game data when every declaration of it is: a firmware - # declaration of the same path keeps it in a pack built without game data. - declared_kinds: dict[str, set[bool]] = {} - for system in build.pack_systems.values(): - for fe in system.get("files", []): - bare = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) - if bare: - declared_kinds.setdefault(bare, set()).add(id(fe) in build.game_entries) - build.game_destinations = {d for d, kinds in declared_kinds.items() if kinds == {True}} - - # The full manifest records every core's answer at a contested slot, so a - # target narrowed from it gets what that target's own pack serves. - whole = opts.target_cores is None and opts.source != "platform" and bool(emu_profiles) - # The truth list read inside this run takes the choices already made. - build.slot_choices = ( - opts.known_slot_choices if opts.known_slot_choices is not None and whole - else slots.slot_choices(config, emu_profiles, build.db, build.zip_contents, - build.data_registry) - if whole else {} - ) - # Derived from the same choices: computed twice, it was 8% of a run. - build.slot_overrides = slots.pack_overrides( - config, emu_profiles, build.db, build.zip_contents, build.data_registry, - target_cores=opts.target_cores, source=opts.source, - choices=build.slot_choices if whole else None, - ) - - # Read by the region grouping and by phase 2 with the same arguments. - build.undeclared = ( - undeclared_report( - config, opts.emulators_dir, build.db, emu_profiles, opts.target_cores, - include_all=(opts.source == "truth"), - ) - if opts.source != "platform" - else None - ) - build.region_drops, build.selection, build.builder_held = _manifest_selection( - config, build.pack_systems, opts.emulators_dir, build.db, build.base_dest, - emu_profiles, opts.target_cores, opts.source, - required_only=opts.required_only, regions=opts.regions, - undeclared=build.undeclared, zip_contents=build.zip_contents, - data_registry=build.data_registry, slot_overrides=build.slot_overrides, - one_per_slot=opts.one_per_slot, - ) - - -def generate_manifest( - platform_name: str, - platforms_dir: str, - db: dict, - bios_dir: str, - registry_path: str, - **options: Unpack[ManifestOptions], -) -> dict: - """Generate a JSON manifest for a platform (same resolution as generate_pack). - - Returns a dict ready for JSON serialization with file inventory, - install hints, and download metadata. ``fold_case`` overrides the - platform's ``case_insensitive_fs``, for the case variants below. - - A file that is a game's data, not firmware, carries ``"category": - "game_data"``, so the installer can leave it out as the builder does - under ``no_game_data``. Firmware carries no category. - One build: generate_install_list adds what --source truth and - --standalone read. `build_out` receives the slot choices and the - profiles this build read, which that second build takes over. - """ - _reject_unknown("generate_manifest", options, ManifestOptions.__optional_keys__) - opts = _ManifestSettings(**options) - build, full_profiles = _start_manifest( - platform_name, platforms_dir, db, bios_dir, registry_path, opts - ) - config, verification_mode = build.config, build.verification_mode - - def settle( - file_entry: dict, sys_id: str, dest: str, override: str | None - ) -> tuple[str | None, str]: - """The file served once the slot is settled, or None and why not.""" - local_path, status = resolve_declaration( - file_entry, - db, - bios_dir, - build.zip_contents, - build.data_registry, - override, - offline=opts.offline, - ) - if status == "not_found" and not reads_file_contents(verification_mode): - found = agnostic_substitute(file_entry, sys_id, db, build.manifest_profiles) - if found: - local_path, status = found[0], "agnostic_fallback" - if os.path.basename(local_path) != file_entry.get("name", ""): - # The pack explains the rename in a note of its own. - build.rename_notes.add(file_entry.get("name", "")) - # The builder's verdict: a hash platform omits what its frontend - # would reject, a zipped_file archive included when the member is - # missing whatever the outer resolution said. An existence - # platform never reads the bytes. - status, refusal = baseline_verdict( - file_entry, local_path, status, verification_mode, - config.get("hash_rule", ""), - ) - if refusal or status in ("not_found", "external"): - return None, "hash_mismatch" if refusal else status - # The variant the pack ships when an emulator rejects the - # resolved file: the installer must place the same bytes. - local_path, _disagreement = validated_choice( - file_entry, local_path, db, build.manifest_validation, bios_dir, - digest_algorithm(verification_mode), dest, build.manifest_owners, - ) - return local_path, status - - if opts.source != "truth": - build.list_baseline(settle) - build.list_core_files() - result = build.result(build.list_data_directories()) - detect = build.install_section.get("detect", []) - if build.case_insensitive and opts.fold_case is None and any( - d.get("os") not in CASE_FOLDING_OS for d in detect - ): - # RetroArch also runs where case is kept: there Mesen-CE opens - # bios.col and np2kai np2kai/2608_bd.wav, which the folded list - # serves only as BIOS.col and 2608_BD.WAV. The installer adds these - # where the directory keeps case, while the pack, extracted on Windows - # or macOS too, stays folded. - kept = generate_manifest( - platform_name, platforms_dir, db, bios_dir, registry_path, - emulators_dir=opts.emulators_dir, zip_contents=build.zip_contents, - emu_profiles=full_profiles, target_cores=opts.target_cores, source=opts.source, - regions=opts.regions, target_name=opts.target_name, offline=opts.offline, - required_only=opts.required_only, data_registry=build.data_registry, - fold_case=False, no_game_data=opts.no_game_data, - ) - folded = {entry["dest"] for entry in build.manifest_files} - folded_lower = {dest.lower() for dest in folded} - variants = [ - entry for entry in kept["files"] - if entry["dest"] not in folded and entry["dest"].lower() in folded_lower - ] - if variants: - result["case_variants"] = variants - if opts.build_out is not None: - opts.build_out.update(slot_choices=build.slot_choices, profiles=build.manifest_profiles) - return result - - -def generate_install_list( - platform_name: str, - platforms_dir: str, - db: dict, - bios_dir: str, - registry_path: str, - standalone_out: dict | None = None, - **options: Unpack[InstallListOptions], -) -> dict: - """The list install.py reads: the full manifest, the files and omissions - the --source truth build holds apart from it, and the emulators with a - standalone build. `standalone_out` receives, per such emulator, what - `--emulator X --standalone` packs, written apart from the list - (install/standalone/.json) and fetched only by a run given - --standalone. - - A manifest narrowed by a target, a case fold or --one-per-slot is no - list install.py reads by default and gets neither. - """ - settings = _ManifestSettings(**options) - built: dict = {} - result = generate_manifest(platform_name, platforms_dir, db, bios_dir, registry_path, - build_out=built, **options) - if (settings.source != "full" or settings.target_cores is not None - or settings.fold_case is not None or settings.one_per_slot): - return result - truth_options: InstallListOptions = {**options, "source": "truth"} - with contextlib.redirect_stdout(io.StringIO()): - truth = generate_manifest( - platform_name, platforms_dir, db, bios_dir, registry_path, - **truth_options, known_slot_choices=built["slot_choices"], - ) - _mark_truth(result, truth) - layouts = _standalone_layouts( - built["profiles"], settings.emulators_dir, db, bios_dir, - settings.zip_contents or {}, settings.offline, platforms_dir, result, - ) - if layouts: - result["standalone_builds"] = sorted(layouts) - if standalone_out is not None: - standalone_out.update(layouts) - return result - - -STANDALONE_DIR = "standalone" - def _write_standalone_layouts(output_dir: str, platform: str, layouts: dict) -> str: """install/standalone/.json, what --standalone reads beside the @@ -6162,754 +1511,9 @@ def _write_standalone_layouts(output_dir: str, platform: str, layouts: dict) -> return path -def _truth_key(entry: dict) -> tuple: - """What tells one entry from another, as the installer's _entry_key.""" - root = entry.get("root") - cores = tuple(entry.get("cores") or []) if root == "emulator" else () - return (str(entry.get("dest")), root, cores) - - -def _mark_truth(result: dict, truth: dict) -> None: - """What `--source truth` installs, carried in the full list. - - The truth list holds what the emulator profiles prove is read. A file of - the full list it does not hold, by destination and content, is marked - `"truth": false`, and what only the truth list holds is `truth_files`. - Omissions compare by destination. The installer then rebuilds the - truth list from the full one, and a list without `truth_files` is one - published before, on which `--source truth` is refused. - """ - held = {(_truth_key(entry), entry.get("sha1")) for entry in truth["files"]} - full = {(_truth_key(entry), entry.get("sha1")) for entry in result["files"]} - for entry in result["files"]: - if (_truth_key(entry), entry.get("sha1")) not in held: - entry["truth"] = False - result["truth_files"] = [ - entry for entry in truth["files"] - if (_truth_key(entry), entry.get("sha1")) not in full - ] - absent = {_truth_key(entry) for entry in truth["omitted_files"]} - listed = {_truth_key(entry) for entry in result["omitted_files"]} - for entry in result["omitted_files"]: - if _truth_key(entry) not in absent: - entry["truth"] = False - result["truth_omitted"] = [ - entry for entry in truth["omitted_files"] if _truth_key(entry) not in listed - ] - - -def _standalone_layouts( - profiles: dict[str, dict], - emulators_dir: str, - db: dict, - bios_dir: str, - zip_contents: dict, - offline: bool | None, - platforms_dir: str, - result: dict, -) -> dict[str, list]: - """Per emulator with a standalone build, the files `--emulator X - --standalone` packs, at the destinations that build reads. - - Built by the emulator pack itself, in memory. A file whose content the - list already carries is written as [dest, sha1], its download read from - that entry. Another is written whole. A data tree member is left to the - list's data directories. - """ - repo_root = str(REPO_ROOT) - known = { - copy["sha1"] - for entry in [*result["files"], *result.get("truth_files", [])] - for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])] - if copy.get("sha1") and (copy.get("repo_path") or copy.get("release_asset")) - } - layouts: dict[str, list] = {} - for name, profile in sorted(profiles.items()): - if "standalone" not in str(profile.get("type", "")): - continue - record = PackRecord() - with contextlib.redirect_stdout(io.StringIO()), \ - contextlib.redirect_stderr(io.StringIO()): - generate_emulator_pack( - [name], emulators_dir, db, bios_dir, "", standalone=True, - zip_contents=zip_contents, offline=offline, - platforms_dir=platforms_dir, record=record, - ) - items: list = [] - for member in record.files: - entry, _size = _manifest_entry( - record.sources.get(member), member, [name], db, repo_root, {} - ) - if entry is None: - continue - items.append([member, entry["sha1"]] if entry["sha1"] in known else entry) - layouts[name] = items - return layouts - - -def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, list[str]]: - """The cores that read each tree, for a tree only cores read. A tree a - platform system declares is the system's, whatever core runs it, and - gets no entry. Every reference counts: two cores reading one tree yield - its files once.""" - cores: dict[str, set[str]] = {} - declared: set[str] = set() - for _systems, dd in _tree_references(pack_systems, core_trees): - ref = str(dd.get("ref") or "") - if dd.get("core"): - cores.setdefault(ref, set()).update(str(core) for core in dd.get("readers") or [dd["core"]]) - else: - declared.add(ref) - return {ref: sorted(names) for ref, names in cores.items() if ref not in declared} - - -def _tree_group( - ref: str, prefix: str, entry: dict, base_dest: str, versions: dict[str, dict[str, dict]], -) -> dict: - """The manifest record of one data directory, before its files. - - ``versions`` caches each .versions.json read, by path. - """ - version = str(entry.get("version", "master")) - dest = prefix - if base_dest and (dest == base_dest or dest.startswith(base_dest + "/")): - dest = dest[len(base_dest):].lstrip("/") - group: dict = { - "ref": ref, - "dest": dest, - "url": str(entry.get("source_url", "")).format(version=version), - "type": "zip" if entry.get("source_type") == "zip" else "tarball", - "systems": [], - "files": {}, - } - if group["type"] == "zip": - group["strip_components"] = int(entry.get("strip_components", 0)) - else: - group["source_path"] = str(entry.get("source_path", "")).format(version=version) - if entry.get("exclude"): - group["exclude"] = [str(e) for e in entry["exclude"]] - cache = entry.get("local_cache") - if cache: - recorded = Path(cache).parent / ".versions.json" - if str(recorded) not in versions: - try: - versions[str(recorded)] = json.loads(recorded.read_text()) - except FileNotFoundError: - versions[str(recorded)] = {} - size = versions[str(recorded)].get(ref, {}).get("archive_size") - if isinstance(size, int) and size > 0: - group["archive_size"] = size - return group - - -def _manifest_data_directories( - members: list[tuple[str, str]], - refs: dict[str, tuple[str, tuple[str, ...], str, bool]], - registry: dict, - base_dest: str, - readers: dict[str, list[str]] | None = None, - platform_systems: Iterable[str] | None = None, -) -> list[dict]: - """Each data directory the pack carries, as the installer rebuilds it. - - The source archive and the rule that maps its members onto the tree - (strip_components for a ZIP, source_path for a tarball, exclude) come - from _data_dirs.yml, the same refresh_data_dirs applies. Every file - carries the sha1 and size the cache holds, so a member the source - changed since is refused rather than installed. archive_size is the - size of the archive refresh_data_dirs last downloaded, what fetching - the tree costs: a tarball whose tree is 10 KB is a download of 21 MB. - ``systems`` are the platform's ids (``platform_systems``) the tree's - systems normalize to, as a core extra's are: a tree no platform system - serves has none, and goes with the files of no system, as the pack - built with --system puts it in the part of its own. FBNeo's cheats - carried sega-megadrive where RetroArch's list says sega-mega-drive. - ``optional`` marks a tree every core reading it runs without - (``required: false``): install.py --required-only leaves it out, as the - pack built with --required-only does. ``cores`` names the cores that - read a tree no platform system declares (``readers``): an install for - the games of a card keeps it only when its plan runs one of them. - """ - grouped: dict[tuple[str, str], dict] = {} - versions: dict[str, dict[str, dict]] = {} - by_norm: dict[str, list[str]] = {} - for sys_id in sorted(platform_systems or ()): - by_norm.setdefault(_norm_system_id(sys_id), []).append(sys_id) - for src, full in members: - ref, systems, prefix, needed = refs[full] - if platform_systems is not None: - systems = tuple(own for sid in systems for own in by_norm.get(_norm_system_id(sid), ())) - key = (ref, prefix) - group = grouped.get(key) - if group is None: - group = grouped[key] = _tree_group( - ref, prefix, registry.get(ref, {}), base_dest, versions - ) - if needed: - group["needed"] = True - group["systems"].extend(s for s in systems if s not in group["systems"]) - rel = full[len(prefix):].lstrip("/") if prefix else full - hashes = compute_hashes(src, frozenset({"sha1"})) - group["files"][rel] = {"sha1": hashes["sha1"], "size": os.path.getsize(src)} - trees = [] - for key in sorted(grouped): - group = grouped[key] - if not group.pop("needed", False): - group["optional"] = True - if readers and group["ref"] in readers: - group["cores"] = readers[group["ref"]] - trees.append(group) - return trees - - -def _offered_boards( - config: dict, - profiles: dict[str, dict], - core_names: dict[str, list[str]], - entries: list[dict], -) -> dict[str, list[dict]]: - """The roms folders each profile is offered for on some boards only, - each with those boards, aliases included, where the manifest places a - file of that profile. - - ROCKNIX writes uae4arm for roms/amiga under the devices it builds it for - (emulators/package.mk:188), and a board's core list names uae4arm when - another folder offers it there. The pack builder reads the board from - the config (TARGET_KEY) and `install.py --target` reads its answer here. - A manifest built for one board needs none. - """ - if config.get(TARGET_KEY): - return {} - pairs = content_folder_boards(config) - if all(on is None for on in pairs.values()): - return {} - from resolve.launchers import _roms_place - - by_key: dict[str, set[str]] = {} - for name, claimants in upstream_profile_index(profiles).items(): - by_key.setdefault(_core_key(name), set()).update(claimants) - free = { - (profile, folder) for (core, folder), on in pairs.items() if on is None - for profile in by_key.get(core, ()) - } - found: dict[tuple[str, str, str], set[str]] = {} - for (core, folder), on in pairs.items(): - where = _roms_place(config, folder) if on is not None else None - if where is None: - continue - for profile in by_key.get(core, ()): - if profile in core_names and (profile, folder) not in free: - found.setdefault((profile, where[0], where[1]), set()).update(on) - # An entry below the roms root names it, one in the install tree none. - trees = {ROMS_ROOT: ROMS_ROOT, None: "install"} - placed = { - (profile, trees[entry.get("root")], str(entry.get("dest", "")).rpartition("/")[0]) - for entry in entries if entry.get("root") in trees - for copy in [entry, *entry.get("alternatives", [])] - for profile in copy.get("cores") or [] - } - result: dict[str, list[dict]] = {} - for (profile, tree, folder), boards in sorted(found.items()): - if not any( - p == profile and t == tree and (d == folder or d.startswith(f"{folder}/")) - for p, t, d in placed - ): - continue - result.setdefault(profile, []).append( - {"root": tree, "folder": folder, "boards": sorted(boards)} - ) - return result - - -def _downloaded_cores( - config: dict, - profiles: dict[str, dict], - core_names: dict[str, list[str]], - platforms_dir: str, -) -> dict[str, list[str]]: - """The cores only the platform's RetroArch downloader brings, each with - the boards, aliases included, whose downloader offers it. - - A target list names the board's standalone amiberry and the buildbot's - amiberry core alike, so the installer cannot tell from the name whether - the board reaches the core. `resolve_platform_cores` decides it, and - `install.py --target` reads its answer here. - """ - reached = { - profile: names - for profile, names in downloaded_only_profiles(config, profiles).items() - if profile in core_names - } - if not reached: - return {} - platform = str(config.get("_key") or "") - boards: dict[str, list[str]] = {profile: [] for profile in reached} - for target in list_available_targets(platform, platforms_dir): - cores = load_target_config(platform, target["name"], platforms_dir) - if cores is None: - continue - for profile, names in reached.items(): - if downloadable_on(cores, names): - boards[profile] += [target["name"], *target.get("aliases", [])] - return {profile: sorted(names) for profile, names in sorted(boards.items())} - - -def _manifest_core_index( - config: dict, - profiles: dict[str, dict], - files: list[dict], - omitted: list[dict], -) -> tuple[dict[str, list[str]], dict[str, list[str]]]: - """What the installer needs to narrow by a list of core names. - - A target list, or the cores found installed, names cores the way the - buildbot does, and a file names the profile that reads it: `core_names` - gives each profile the other names it goes by, and names every core the - platform runs, one that reads no file included: a core found installed - that the list does not name is one it has no profile for. `system_cores` - gives each platform system the cores whose presence keeps it, as - `filter_systems_by_target` decides. A system absent from it is kept - whatever is available. - """ - runs = _platform_cores(config, profiles) - reach = system_core_reach(config.get("systems", {}), profiles, runs) - system_cores = { - sys_id: sorted(cores) for sys_id, cores in sorted(reach.items()) - if cores is not None - } - named = { - c for entry in [*files, *omitted] - for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])] - for c in copy.get("cores") or [] - } - named |= {c for cores in system_cores.values() for c in cores} - named |= set(runs) - aliases: dict[str, set[str]] = {profile: set() for profile in named & set(runs)} - for name, claimants in upstream_profile_index(profiles, include_aliases=True).items(): - for profile in claimants & named: - if name != profile: - aliases.setdefault(profile, set()).add(name) - core_names = {profile: sorted(names) for profile, names in sorted(aliases.items())} - return core_names, system_cores - - # Post-generation pack verification + manifest + SHA256SUMS - -def pack_systems(install_manifest: dict, targets: dict | None = None) -> dict: - """What a pack's manifest.json records of its systems, from the install - list built with the same choices: each file's systems, by its path in - the pack, and the names a person reads for them. - - A pack recorded none: the installer refused --system with a pack alone - ("the file list comes from an older release") and offered no Choose - systems, the route of a handheld without Wi-Fi. - - The install list itself and the platform's cores per board (targets, as - install/targets/ publishes them) ride along: with the pack alone, a - board was never applied and --target was refused, and a Batocera RPi4 - card took 8.9 GB where its board reads 5.8. - """ - files = install_manifest.get("files", []) - entries = [*files, *install_manifest.get("omitted_files", [])] - # What the install list narrows by, the installer's recorded_axes: with - # the pack alone it names that list as the way to --core and --region - # only when the list records them. It named install/misterfpga.json for - # --core, a list that records no core. - records = {"systems"} if any("systems" in entry for entry in entries) else set() - if any(copy.get("cores") for entry in files - for copy in [entry, *entry.get("alternatives", []), - *entry.get("slot_choices", [])]): - records.add("cores") - if records or any("regions" in entry for entry in entries): - records.add("regions") - systems = { - "files": {entry["dest"]: list(entry.get("systems") or []) - for entry in files if "systems" in entry}, - "system_titles": dict(install_manifest.get("system_titles") or {}), - "system_names": dict(install_manifest.get("system_names") or {}), - "list_records": sorted(records), - } - # The version of the platform's list, which the installer compares with - # the one the machine runs when it has the pack alone. - if install_manifest.get("version"): - systems["list_version"] = install_manifest["version"] - systems["install_list"] = install_manifest - if targets is not None: - systems["targets"] = targets - return systems - - -def annotate_pack_systems(manifest: dict, systems: dict | None) -> None: - """Write pack_systems into a pack's manifest: a systems list on each - file the install list names, the titles and names beside.""" - if not systems: - return - for entry in manifest.get("files", []): - held = systems["files"].get(entry["path"]) - if held is not None: - entry["systems"] = held - for key in ("system_titles", "system_names"): - if systems.get(key): - manifest[key] = systems[key] - for key in ("list_records", "list_version", "install_list", "targets"): - if key in systems: - manifest[key] = systems[key] - - -def inject_manifest(zip_path: str, manifest: dict) -> None: - """Inject manifest.json into an existing ZIP pack. - - The pack is rewritten beside its final name and swapped in, as - _writing_pack builds it: appending in place rewrites the central - directory last, so a process killed in between left an unreadable ZIP - where a valid pack had been. - """ - manifest_json = json.dumps(manifest, indent=2, ensure_ascii=False) - - with zipfile.ZipFile(zip_path, "r") as zf: - has_manifest = "manifest.json" in zf.namelist() - - directory = os.path.dirname(zip_path) or "." - fd, scratch = tempfile.mkstemp( - prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory - ) - os.close(fd) - try: - if not has_manifest: - # Append to a copy. Append mode defaults to ZIP_STORED, which - # would leave the manifest uncompressed and give the same pack - # two different byte layouts depending on the path taken here. - shutil.copyfile(zip_path, scratch) - with zipfile.ZipFile(scratch, "a", zipfile.ZIP_DEFLATED) as zf: - _write_generated_member(zf, "manifest.json", manifest_json) - else: - with zipfile.ZipFile(zip_path, "r") as src, \ - zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as dst: - for item in src.infolist(): - if item.filename == "manifest.json": - continue - dst.writestr(item, src.read(item.filename)) - _write_generated_member(dst, "manifest.json", manifest_json) - set_plain_mode(scratch) - os.replace(scratch, zip_path) - except BaseException: - Path(scratch).unlink(missing_ok=True) - raise - - - - - - - - -def _target_cores_for( - platform_name: str, target_name: str | None, platforms_dir: str -) -> set[str] | None: - """Cores a target leaves available, or None when no target was asked for. - - Called on a platform the build already packed under the target, so the - target is known to it: a platform without one is left out of the run. - """ - if not target_name: - return None - return load_target_config(platform_name, target_name, platforms_dir) - - -def _expected_pack_names( - platforms: list[str], - platforms_dir: str, - regions: list[str] | None, - target_name: str | None, - variants: tuple[tuple[str, bool], ...] = (("full", False),), - no_game_data: bool = False, -) -> dict[str, set[str]]: - """Exact pack file names --verify-packs may check, per platform. - - Rebuilt from the name builder, never matched by substring: a substring - picks the full pack when a regional or targeted one was asked for, or a - narrowed pack when the full one was. A platform answers to its own name - and to the name of the group it shares a pack with. ``variants`` lists - the (source, required_only) combinations the run built. - """ - def narrow_tags(platform_name: str) -> list[str]: - named = _platform_target(platform_name, target_name, platforms_dir) - return [ - "".join( - tag - for tag, _label in _narrowings( - source, regions, named, False, required, no_game_data=no_game_data - ) - ) - for source, required in variants - ] - - names: dict[str, set[str]] = { - p: { - f"{_platform_pack_stem([p], p, platforms_dir)}{tags}_BIOS_Pack.zip" - for tags in narrow_tags(p) - } - for p in platforms - } - # Groups depend on which platforms a run built: the release packs of - # --all. - pool = list_release_pack_platforms(platforms_dir) - cache = None - if target_name: - try: - cache, pool = build_target_cores_cache( - pool, target_name, platforms_dir, is_all=True - ) - except ValueError: - # No platform has the target: no pack was built under it. - return names - for group, representative in group_identical_platforms( - pool, platforms_dir, cache - ): - if len(group) < 2: - continue - stem = _platform_pack_stem(group, representative, platforms_dir) - for tags in narrow_tags(representative): - for p in group: - if p in names: - names[p].add(f"{stem}{tags}_BIOS_Pack.zip") - return names - - -def _content_narrowing_tags() -> tuple[str, ...]: - """Tags naming a pack that holds fewer files than the platform declares. - - Read from the name builder rather than retyped, so the two cannot drift. - Region and target are absent on purpose: both are handed to the check - itself, which narrows its expectation instead of skipping it. - """ - # (source, one_per_slot, required_only), one dimension at a time. - dimensions = ( - ("platform", False, False), - ("truth", False, False), - ("full", True, False), - ("full", False, True), - ) - tags: list[str] = [] - for source, one_per_slot, required_only in dimensions: - tags.extend( - tag - for tag, _label in _narrowings(source, None, None, one_per_slot, required_only) - ) - return tuple(tags) - - -_CONTENT_NARROWING_TAGS = _content_narrowing_tags() - - -def _narrows_contents(pack_name: str) -> bool: - """True when a pack holds fewer files than the platform declares. - - A source-restricted or required-only build is narrower by design, so the - full platform expectation does not apply to it and conformance is skipped. - Region is not listed: the region filter is passed to the check itself, and - a hardware target is passed the same way. - """ - return any(f"{tag}_" in pack_name for tag in _CONTENT_NARROWING_TAGS) - - -def _pack_variant(pack_name: str) -> tuple[str, bool] | None: - """The (source, required_only) a pack was built as, read from its name. - - None for a one-per-slot pack, whose slot choice the check does not - replay. The tags come from the name builder, as for _narrows_contents. - """ - def tagged(**dimension: object) -> bool: - tags = [ - tag for tag, _label in _narrowings( - str(dimension.get("source", "full")), None, None, - bool(dimension.get("one_per_slot", False)), - bool(dimension.get("required_only", False)), - ) - ] - return all(f"{tag}_" in pack_name for tag in tags) - - if tagged(one_per_slot=True): - return None - source = next( - (s for s in ("platform", "truth") if tagged(source=s)), "full" - ) - return source, tagged(required_only=True) - - -def _pack_archives(output_dir: str) -> list[str]: - """The ZIPs of a directory that are packs. - - A part of a split pack holds a share of a platform by design and was - checked against the whole when it was cut: judged as a pack it would - fail conformance, and injecting a manifest would change published bytes. - Every name the builder gives holds `_BIOS_Pack`, then the system tag of - a --system platform pack (`_BIOS_Pack_Playstation.zip`): build_port.py - wrote its launcher archives (RetroBIOS.zip) to the same dist/, and - taking every ZIP rewrote them with a manifest after build_port had - printed their hashes. - """ - return sorted( - name - for name in os.listdir(output_dir) - if _PACK_NAME.search(name) and not split_pack.is_part(name) - ) - - -_PACK_NAME = re.compile(r"_BIOS_Pack(?:_[^/]+)?\.zip$") - - -class FinalizeOptions(TypedDict, total=False): - """The keyword options of verify_and_finalize_packs.""" - - platforms_dir: str - skip_conformance: bool - data_registry: dict | None - regions: list[str] | None - target_name: str | None - emulators_dir: str - no_game_data: bool - pack_systems_by_name: dict[str, dict] | None - built: Iterable[str] | None - - -@dataclass(frozen=True) -class _FinalizeSettings: - """FinalizeOptions with their defaults.""" - - platforms_dir: str = "platforms" - skip_conformance: bool = False - data_registry: dict | None = None - regions: list[str] | None = None - target_name: str | None = None - emulators_dir: str = "emulators" - no_game_data: bool = False - pack_systems_by_name: dict[str, dict] | None = None - built: Iterable[str] | None = None - - -def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> bool: - """Stage 2 for one platform of a pack: extract and verify against its - config. Prints the platform's line and its errors.""" - ( - p_ok, - _total, - _matched, - p_errors, - bl_checked, - bl_present, - core_checked, - core_present, - bl_excluded, - bl_absent, - ) = verify_pack_against_platform( - zip_path, - pname, - opts.platforms_dir, - db=db, - emulators_dir=opts.emulators_dir, - regions=opts.regions, - data_registry=opts.data_registry, - target_cores=_target_cores_for(pname, opts.target_name, opts.platforms_dir), - no_game_data=opts.no_game_data, - ) - status = "OK" if p_ok else "FAILED" - exclusion_note = "".join( - f", {part}" for part in _baseline_shortfall(bl_excluded, bl_absent) - ) - print( - f" platform {pname}: {bl_present}/{bl_checked} baseline present" - f"{exclusion_note}, " - f"{core_present}/{core_checked} cores present, {status}" - ) - if not p_ok: - for err in p_errors: - print(f" {err}") - return p_ok - - -def verify_and_finalize_packs( - output_dir: str, - db: dict, - **options: Unpack[FinalizeOptions], -) -> bool: - """Verify all packs, inject manifests, generate SHA256SUMS. - - pack_systems_by_name gives, per pack file name, the systems its - manifest.json records (pack_systems). - - ``built`` names the packs this run wrote, and only those are verified - and get a manifest. A pack another run left in the directory was - reopened, recompressed and given a manifest without its pack_systems, - which made the installer refuse to narrow it. None takes every pack. - - Two-stage verification: - 1. Hash check against database.json (integrity) - 2. Extract + verify against platform config (conformance) - - Returns True if all packs pass verification. - """ - _reject_unknown("verify_and_finalize_packs", options, FinalizeOptions.__optional_keys__) - opts = _FinalizeSettings(**options) - all_ok = True - - # Map ZIP names to platform names - # By the exact name this run's reduction gives a platform's pack, never by - # substring: a _Custom or regional pack left by another run was judged - # against this run's expectation and failed it. - registered = list_registered_platforms(opts.platforms_dir) - expected = _expected_pack_names( - registered, opts.platforms_dir, opts.regions, opts.target_name, - no_game_data=opts.no_game_data, - ) - packs = _pack_archives(output_dir) - if opts.built is not None: - packs = [name for name in packs if name in set(opts.built)] - pack_to_platform: dict[str, list[str]] = {} - for name in packs: - for pname in registered: - if name in expected[pname]: - pack_to_platform.setdefault(name, []).append(pname) - - failing: list[str] = [] - for name in packs: - zip_path = os.path.join(output_dir, name) - - # Stage 1: database integrity - ok, manifest = verify_pack(zip_path, db, data_registry=opts.data_registry) - summary = manifest["summary"] - status = "OK" if ok else "ERRORS" - print( - f" verify {name}: {summary['verified']}/{summary['total_files']} verified, " - f"{summary['untracked']} untracked, {summary['errors']} errors [{status}]" - ) - if not ok: - for err in manifest["errors"]: - print(f" ERROR: {err}") - all_ok = False - failing.append(name) - annotate_pack_systems(manifest, (opts.pack_systems_by_name or {}).get(name)) - inject_manifest(zip_path, manifest) - - # Stage 2: platform conformance (extract + verify) - # Skipped for filtered/split/custom packs (intentionally partial) - if opts.skip_conformance: - continue - if _narrows_contents(name): - continue - for pname in pack_to_platform.get(name, []): - if not _conforms(zip_path, pname, db, opts): - all_ok = False - failing.append(f"{name} ({pname})") - - generate_sha256sums(output_dir) - if failing: - # Named at the end, where a 4,000-line log is read, and on stderr. - print(f"ERROR: packs failed verification: {', '.join(failing)}", file=sys.stderr) - return all_ok - if __name__ == "__main__": from core.cli import run_cli diff --git a/scripts/generate_readme.py b/scripts/generate_readme.py index 23f107e75..bd313926d 100644 --- a/scripts/generate_readme.py +++ b/scripts/generate_readme.py @@ -35,10 +35,10 @@ from model.systems import system_index import archive_build import release_record from siteguides import PACKAGE_COMMAND, install_command -from validate_pr import LARGE_FILE_ISSUE_URL +from resolve.review import LARGE_FILE_ISSUE_URL from model.largefiles import LARGE_FILES_CACHE, load_registered_paths import pr_checks -from verify import verify_platform +from packs.coverage import verify_platform def _installer_words() -> ModuleType: @@ -989,7 +989,7 @@ def main() -> None: import contextlib from model.registry import load_data_dir_registry - from refresh_data_dirs import hold_data_dirs + from packs.datadirs import hold_data_dirs db = load_database(args.db) diff --git a/scripts/generate_site.py b/scripts/generate_site.py index 07dcd6ac3..1c3628f63 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -70,7 +70,7 @@ 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 -from cross_reference import FileConsumers, entry_target, held_copy +from packs.crossref import FileConsumers, entry_target, held_copy from resolve.nativemode import check_label, digest_algorithm, reads_file_contents from generate_readme import ( @@ -123,7 +123,7 @@ import sitebootstrap import sitehandheld import sitemeasurements import sitewanted -from validate_pr import load_platform_hashes, load_profile_hashes +from resolve.review import load_platform_hashes, load_profile_hashes from sitediagrams import local_images, prepare_page, unresolved_images from sitewrite import ( _record, @@ -688,7 +688,7 @@ def _pack_version(pack_name: str, platforms: list[str]) -> str: Read past the platform part the builder writes, not at the last underscore: AmberELEC_prerelease-20261019_1835 read as 1835. """ - from generate_pack import platform_pack_prefix + from packs.naming import platform_pack_prefix stem = pack_name.removesuffix("_BIOS_Pack.zip") prefix = platform_pack_prefix( @@ -1231,7 +1231,7 @@ def build_emulator_gap_report( """ from model.systems import _norm_system_id from model.declarations import merged_platform_declarations - from cross_reference import cross_reference as run_cross_reference + from packs.crossref import cross_reference as run_cross_reference # Enriched with alias resolution, with each declaration's size and slot: # a name alone settled DOSBox's 32 KiB SC-55 ROM1.BIN on Galaksija's. @@ -9975,7 +9975,7 @@ def _availability_check( missing while the gap report called it held would describe a different collection on two pages of the same site. """ - from cross_reference import entry_source + from packs.crossref import entry_source by_name = db.get("indexes", {}).get("by_name", {}) by_name_lower = {k.lower(): k for k in by_name} @@ -10006,7 +10006,7 @@ def _availability_check( def _emulator_slots(files: list[dict]) -> list[list[dict]]: """The entries of each slot, as verify --emulator and the gaps page count them, leaving out the slots the app ships.""" - from cross_reference import slot_key + from packs.crossref import slot_key slots: dict[tuple, list[dict]] = {} for f in files: @@ -13044,7 +13044,7 @@ def main() -> None: from model.registry import load_data_dir_registry from core.artifacts import repository_output_lock - from refresh_data_dirs import hold_data_dirs + from packs.datadirs import hold_data_dirs # The coverage pages resolve against data/, held while they are read. # Whatever --docs-dir says, website/src/data and wiki/ are written. @@ -13131,7 +13131,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 model.registry import load_data_dir_registry - from cross_reference import _build_supplemental_index + from packs.crossref import _build_supplemental_index registry = _load_registry(args.platforms_dir) diff --git a/scripts/model/nodedup.py b/scripts/model/nodedup.py new file mode 100644 index 000000000..a2555dce7 --- /dev/null +++ b/scripts/model/nodedup.py @@ -0,0 +1,54 @@ +"""Trees of bios/ addressed by path, which deduplication leaves alone.""" + +from __future__ import annotations + +from pathlib import Path + + +# Directories where deduplication must NOT be applied. +NODEDUP_DIRS = { + "RPG Maker", + "ScummVM", + # A zoneinfo tree is addressed by zone name and its aliases are equal + # files by design: US/Samoa is Pacific/Midway. + "tzdata", + # VICE data is addressed by machine directory: C64, C64DTV and SCPU64 + # share one keymap, C64 and CBM-II one palette. With the copies removed + # the name step served the C128 keymap to all of them. + "c64-emu", + # PinMAME reads a sound-only parent (gts80s) as its own archive, equal + # byte for byte to the base set. Folding them into the clone map would + # key gts1.zip twice, once for MAME's set and once for PinMAME's. + "PinMAME", + # BBK dictionary ROMs are addressed by model directory, and the OS ROM + # the A4988 folder needs is the one the gam4980 core is given. + "BBK", + # Engine data trees read by path: one sound or one sprite sits under + # several characters, campaigns or episodes, and each copy is opened + # where it lies. + "C-Dogs SDL", + "Ikemen GO", + "Theme Hospital", + "TheXTech", + # Aleph One opens each scenario's Physics Models and the Splitwolf mod + # tree its sounds and maps by path: Marathon 2 and Infinity share one + # Standard.phyA, lwmp/ repeats 182 files across its levels. + "Bungie", + "splitwolf", + # CatacombGL reads each game's folder by name and compares sizes only: + # the Armageddon and Apocalypse intro shapes SHP1, SHP9 to SHP13 are the + # Abyss shareware bytes under the retail names, and each game opens + # its own copy. + "Softdisk", + # MAME's support trees (hash, plugins) are read by path as a whole, and + # two MAME versions share most of their software lists byte for byte. + "mame", + # The Tyrian 2.1 distribution ships netset.pcx and tyrset.pcx with the + # same bytes, and EmuELEC places both names under ports/opentyrian/. + "opentyrian", +} + + +def _in_nodedup_dir(path: str) -> bool: + parts = Path(path).parts + return any(nodedup in parts for nodedup in NODEDUP_DIRS) diff --git a/scripts/packs/__init__.py b/scripts/packs/__init__.py new file mode 100644 index 000000000..e2a1a1a63 --- /dev/null +++ b/scripts/packs/__init__.py @@ -0,0 +1 @@ +"""Pack building and verification: selection, archives, manifests, coverage, cross-reference.""" diff --git a/scripts/packs/archive.py b/scripts/packs/archive.py new file mode 100644 index 000000000..1a66f063e --- /dev/null +++ b/scripts/packs/archive.py @@ -0,0 +1,260 @@ +"""Writing pack archives: members, generated files, copied archives, data trees.""" + +from __future__ import annotations + +import contextlib +import os +import shutil +import tempfile +import zipfile +from collections.abc import Iterator, Mapping +from dataclasses import dataclass, field +from pathlib import Path + +from core.artifacts import set_plain_mode +from core.deterministic_zip import _FIXED_DATE_TIME +from core.hashing import compute_hashes +from core.paths import sanitize_pack_path +from packs.paths import _has_path_conflict, _register_path, placement_block + + +def _reject_unknown(function: str, options: Mapping[str, object], known: frozenset[str]) -> None: + """Refuse a keyword the options do not declare, as a named parameter would.""" + for key in options: + if key not in known: + raise TypeError(f"{function}() got an unexpected keyword argument '{key}'") + + +# Formats that are already compressed: deflating them again took 28 s of the +# RetroArch build for 2.1 GB of members and saved 9.6 MB (0.45 %), 16 GB and +# about 72 MB across all packs. Measured per extension on the 2026-10-20 +# packs; .pk3 (3 %), .jpg (6 %), .avi (44 %) and .jar (60 %) still shrink +# and stay deflated. Chosen by name alone, so a pack stays a function of its +# inputs. +_STORED_EXTENSIONS = frozenset({".7z", ".chd", ".ogg", ".pk4", ".png", ".zip"}) + + +def _member_compression(arcname: str) -> int: + """ZIP_STORED for a member whose format is already compressed.""" + if os.path.splitext(arcname)[1].lower() in _STORED_EXTENSIONS: + return zipfile.ZIP_STORED + return zipfile.ZIP_DEFLATED + + +class PackRecord: + """A pack build kept in memory: the paths it writes, no archive. + + ``members`` is every path written, ``files`` the ones the build counts as + the profile's files (archives and loose files, not trees or notes), and + ``trees`` the members a platform pack takes from its data directories. + The pipeline builds every emulator pack and every narrowed platform pack + this way and compares them with what verify credits, without reading or + compressing a byte. + """ + + def __init__(self) -> None: + self.members: list[str] = [] + self.files: list[str] = [] + self.trees: list[str] = [] + # The collection file each copied member comes from: a split part + # writes a file only where the full pack writes the same bytes. + self.sources: dict[str, str] = {} + + +def _add_pack_member( + zf: zipfile.ZipFile | PackRecord, source_path: str, arcname: str +) -> None: + """Add a file to the pack with metadata that does not depend on the build. + + ZipFile.write copies the source file's mtime into the member. For a file + this build just produced in tmp/ that is the wall clock, and for a file + from the collection it is whenever the clone was checked out, so a pack + rebuilt from identical inputs differed from the last one although every + byte of content matched: 348 members of the Recalbox pack moved between + two consecutive builds. The content is streamed rather than read whole, + because some members are firmware images of several hundred megabytes. + """ + if isinstance(zf, PackRecord): + zf.members.append(arcname) + zf.sources[arcname] = source_path + return + info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME) + info.compress_type = _member_compression(arcname) + # The executable bit is the one permission worth carrying: the RetroDECK + # pack ships the two Voxatron engine binaries, and a user who extracts + # them at 644 cannot run them. Git records the bit, so reading it from + # the source keeps the pack the same from any clone. Nothing else about + # the source's mode reaches the archive. + stat_result = os.stat(source_path) + mode = 0o755 if stat_result.st_mode & 0o111 else 0o644 + info.external_attr = (0o100000 | mode) << 16 + size = stat_result.st_size + info.file_size = size + with open(source_path, "rb") as source, zf.open( + info, "w", force_zip64=size >= 1 << 31 + ) as target: + shutil.copyfileobj(source, target, 1024 * 1024) + + +def _write_generated_member( + zf: zipfile.ZipFile | PackRecord, arcname: str, text: str +) -> None: + """Write a pack member the builder composes rather than copies. + + READMEs, instruction notes and the manifest are produced at build time, + so writestr would stamp them with the wall clock and give the same pack + a different hash on every run. Pinning them to the epoch the archive + rebuilder already uses makes a pack a function of its inputs alone. + """ + if isinstance(zf, PackRecord): + zf.members.append(arcname) + return + info = zipfile.ZipInfo(filename=arcname, date_time=_FIXED_DATE_TIME) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = 0o100644 << 16 + zf.writestr(info, text) + + +@contextlib.contextmanager +def _writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]: + """A pack written beside its final name, swapped in once complete. + + Opened on the final name, a rebuild truncated the previous pack at once, + and a build that raised half way still wrote a central directory: a + readable ZIP holding part of the files, which the run then checked and + summed as the pack. + """ + directory = os.path.dirname(zip_path) or "." + fd, scratch = tempfile.mkstemp( + prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory + ) + os.close(fd) + try: + with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as zf: + yield zf + set_plain_mode(scratch) + os.replace(scratch, zip_path) + except BaseException: + Path(scratch).unlink(missing_ok=True) + raise + + +# What the builder writes into a platform pack beside the files it carries. +PACK_DOCUMENTS = ("README.txt", "manifest.json") + + +@dataclass +class _Placed: + """The destinations a build has taken, and the folders they open. + + ``fold`` is whether a case twin of a taken path counts as taken. + """ + + fold: bool + destinations: set[str] = field(default_factory=set) + lower: set[str] = field(default_factory=set) # only used when fold=True + parents: set[str] = field(default_factory=set) # parent dirs of added files (path conflict detection) + + def take(self, dest: str) -> None: + self.destinations.add(dest) + _register_path(dest, self.destinations, self.parents) + if self.fold: + self.lower.add(dest.lower()) + + def holds(self, dest: str) -> bool: + return dest in self.destinations or (self.fold and dest.lower() in self.lower) + + def conflicts(self, dest: str) -> bool: + return _has_path_conflict(dest, self.destinations, self.parents) + + def block(self, dest: str) -> str | None: + return placement_block(dest, self.destinations, self.lower, self.parents, self.fold) + + +def _extract_zip_to_archive( + source_zip: str, + dest_prefix: str, + target_zf: zipfile.ZipFile | PackRecord, +) -> None: + """Extract contents of a source ZIP into target ZIP under dest_prefix.""" + with zipfile.ZipFile(source_zip, "r") as src: + if isinstance(target_zf, PackRecord): + target_zf.members.extend( + f"{dest_prefix}/{name}" if dest_prefix else name + for name in map(sanitize_pack_path, src.namelist()) + if name and not name.endswith("/") + ) + target_zf.sources[dest_prefix] = source_zip + return + for info in src.infolist(): + if info.is_dir(): + continue + clean_name = sanitize_pack_path(info.filename) + if not clean_name: + continue + data = src.read(info.filename) + target_path = f"{dest_prefix}/{clean_name}" if dest_prefix else clean_name + member = zipfile.ZipInfo( + filename=target_path, date_time=_FIXED_DATE_TIME + ) + member.compress_type = _member_compression(target_path) + member.external_attr = 0o100644 << 16 + target_zf.writestr(member, data) + + +def _add_zip_to_pack( + source_zip: str, + dest_path: str, + target_zf: zipfile.ZipFile | PackRecord, + file_entry: dict | None = None, +) -> None: + """Write a source ZIP into the pack, byte for byte. + + The pack carries the collection's own bytes, so every member hashes to + the sha1 the install list and the site publish. Rebuilt ZIPs gave about + 1,500 archives another hash than the list: an extracted pack then failed + `install.py --check`. The collection's bytes are fixed in git, which keeps + the pack reproducible without a rebuild. + """ + if isinstance(target_zf, PackRecord): + target_zf.members.append(dest_path) + target_zf.sources[dest_path] = source_zip + return + _check_zip_members(source_zip) + _add_pack_member(target_zf, source_zip, dest_path) + + +def _check_zip_members(source_zip: str) -> None: + """Refuse an archive whose members fail their own CRC. + + Copied as-is "for verify to flag", a damaged archive went into the pack + and nothing flagged it. + """ + try: + with zipfile.ZipFile(source_zip) as zf: + bad = zf.testzip() + except zipfile.BadZipFile as exc: + raise DamagedArchiveError( + f"{source_zip}: {exc}; restore it from git or the release before packing" + ) from exc + if bad is not None: + raise DamagedArchiveError( + f"{source_zip}: member {bad} fails its CRC; " + "restore it from git or the release before packing" + ) + + +class DamagedArchiveError(OSError): + """An archive of the collection whose members fail their own CRC.""" + + +def _same_bytes(path: str, other: str | None) -> bool: + if not other: + return False + if os.path.realpath(path) == os.path.realpath(other): + return True + return compute_hashes(path)["sha1"] == compute_hashes(other)["sha1"] + + +# Systems whose default filesystems fold case (NTFS, APFS, HFS+). +CASE_FOLDING_OS = frozenset({"windows", "darwin"}) diff --git a/scripts/packs/bysystem.py b/scripts/packs/bysystem.py new file mode 100644 index 000000000..653bffb66 --- /dev/null +++ b/scripts/packs/bysystem.py @@ -0,0 +1,189 @@ +"""A platform pack cut into one pack per system or per manufacturer.""" + +from __future__ import annotations + +import contextlib +import io +import os +from typing import TYPE_CHECKING + +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from packs.archive import PackRecord, _reject_unknown +from packs.emulatorpack import _system_display_name +from packs.extras import _collect_emulator_extras, extras_for_systems as _extras_for_systems +from packs.naming import _name_part, _narrowings, _platform_pack_stem +from packs.platformpack import PackNarrowing, _PartScope, _report_left_out, generate_pack +from resolve.cores import platform_scope_systems +from resolve.gamedata import without_game_data + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def _group_systems_by_manufacturer( + systems: dict[str, dict], + db: dict, + bios_dir: str, +) -> dict[str, list[str]]: + """Group system IDs by manufacturer for --split --group-by manufacturer.""" + from model.systems import derive_manufacturer + + groups: dict[str, list[str]] = {} + for sid, sys_data in systems.items(): + mfr = derive_manufacturer(sid, sys_data) + groups.setdefault(mfr, []).append(sid) + return groups + + +class SplitOptions(PackNarrowing, total=False): + """The keyword options of generate_split_packs.""" + + records: dict[str, PackRecord] | None + + +def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict]: + """The core extras of every part, collected once (expensive: scans 260+ + emulator profiles), then distributed per group by system overlap.""" + emu_profiles = narrowing["emu_profiles"] or {} + source = narrowing["source"] + target_cores = narrowing["target_cores"] + base_dest = config.get("base_destination", "") + # Each part cuts the platform's own entries from the full profiles. The + # extras are collected once here, already without the cores' game data. + cut = ( + without_game_data(config, emu_profiles, narrowing["data_registry"], target_cores) + if narrowing["no_game_data"] else None + ) + if source == "platform": + all_extras = [] + elif emu_profiles: + all_extras = _collect_emulator_extras( + cut.config if cut else config, narrowing["emulators_dir"], db, + set(), base_dest, cut.profiles if cut else emu_profiles, + target_cores=target_cores, include_all=(source == "truth"), + ) + else: + all_extras = [] + if cut is not None and source != "platform": + _report_left_out(cut, systems=set(), cores=True) + return all_extras + + +def generate_split_packs( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + output_dir: str, + group_by: str = "system", + **options: Unpack[SplitOptions], +) -> list[str]: + """Generate split packs (one ZIP per system or manufacturer). + + The parts add up to the full pack: each is built against the full pack's + own placement (``within``). ``records`` builds the parts in memory, keyed + by part name, with no archive written. + """ + _reject_unknown("generate_split_packs", options, SplitOptions.__optional_keys__) + config = load_platform_config(platform_name, platforms_dir) + records = options.get("records") + narrowing: PackNarrowing = { + "emulators_dir": options.get("emulators_dir", "emulators"), + "zip_contents": options.get("zip_contents"), + "data_registry": options.get("data_registry"), + "emu_profiles": options.get("emu_profiles"), + "target_cores": options.get("target_cores"), + "required_only": options.get("required_only", False), + "source": options.get("source", "full"), + "regions": options.get("regions"), + "target_name": options.get("target_name"), + "one_per_slot": options.get("one_per_slot", False), + "offline": options.get("offline"), + "no_game_data": options.get("no_game_data", False), + } + # The split directory carries the same tags as the packs inside it, or two + # differently narrowed runs write into one another. + split_tags = "".join( + tag + for tag, _label in _narrowings( + narrowing["source"], narrowing["regions"], narrowing["target_name"], + narrowing["one_per_slot"], narrowing["required_only"], + no_game_data=narrowing["no_game_data"], + ) + ) + # Two groupings write different files. Without the tag they accumulate in + # one directory under one SHA256SUMS.txt. + group_tag = "" if group_by == "system" else f"_By{group_by.title()}" + # The parts carry the version, so the directory does too: a rescrape that + # moves the version would otherwise leave the old parts beside the new + # under one SHA256SUMS.txt. + # Named by the stem the full pack reads: assembled here by hand, a '/' in + # a version nested the directory where the check never looked for it. + part_prefix = ( + f"{_platform_pack_stem([platform_name], platform_name, platforms_dir)}{split_tags}" + ) + split_dir = os.path.join(output_dir, f"{part_prefix}{group_tag}_Split") + if records is None: + os.makedirs(split_dir, exist_ok=True) + + emu_profiles = narrowing["emu_profiles"] + if emu_profiles is None: + emu_profiles = load_emulator_profiles(narrowing["emulators_dir"]) + narrowing["emu_profiles"] = emu_profiles + full = PackRecord() + with contextlib.redirect_stdout(io.StringIO()): + generate_pack( + platform_name, platforms_dir, db, bios_dir, split_dir, + record=full, **narrowing, + ) + + def part(pack_name: str, scope: _PartScope) -> str | None: + record = PackRecord() if records is not None else None + zip_path = generate_pack( + platform_name, platforms_dir, db, bios_dir, split_dir, + pack_name=pack_name, record=record, within=full.sources, + **scope, **narrowing, + ) + if records is not None and record is not None and zip_path: + records[pack_name] = record + return zip_path + # The systems a core of the target runs: a part per declared system sent + # each one the target drops to a refusal naming it as unknown. + systems = platform_scope_systems(config, emu_profiles, narrowing["target_cores"]) + + if group_by == "manufacturer": + groups = _group_systems_by_manufacturer(systems, db, bios_dir) + else: + groups = {_system_display_name(sid): [sid] for sid in systems} + + all_extras = _split_extras(config, db, narrowing) + results = [] + for group_name, group_system_ids in sorted(groups.items()): + group_extras = _extras_for_systems(all_extras, group_system_ids) + zip_path = part( + f"{part_prefix}_{_name_part(group_name, '_')}_BIOS_Pack.zip", + {"system_filter": group_system_ids, "precomputed_extras": group_extras}, + ) + if zip_path: + results.append(zip_path) + + # Extras whose system the platform does not declare, or that name none, + # belong to no group: they go in a part of their own, or the parts would + # not add up to the full pack (4507 of RetroArch's 5430 were left out). + distributed = { + id(fe) + for fe in _extras_for_systems( + all_extras, [s for ids in groups.values() for s in ids] + ) + } + undistributed = [fe for fe in all_extras if id(fe) not in distributed] + if undistributed: + zip_path = part( + f"{part_prefix}_Other_Cores_BIOS_Pack.zip", + {"precomputed_extras": undistributed, "extras_only": True}, + ) + if zip_path: + results.append(zip_path) + + return results diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py new file mode 100644 index 000000000..0728a944e --- /dev/null +++ b/scripts/packs/coverage.py @@ -0,0 +1,952 @@ +"""A platform's coverage: each declaration resolved and judged as its frontend would.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict + +from core.paths import sanitize_pack_path +from core.ziptools import build_zip_contents_index +from model.alternatives import core_file_spares +from model.declarations import OUTER_ROOTS, platform_declarations +from model.profiles import load_emulator_profiles +from model.systems import select_systems +from packs import slots +from packs.crossref import launcher_reads_not_held +from packs.gaps import find_exclusion_notes, find_undeclared_files +from packs.verdicts import ( + DEFAULT_BIOS_DIR, + DEFAULT_EMULATORS_DIR, + RELEASE_ASSET_PENDING, + Severity, + Status, + _SEVERITY_ORDER, + _STATUS_ORDER, + _storage_verdict, + compute_severity, + verify_entry_existence, + verify_entry_md5, + verify_entry_sha1, +) +from resolve.categories import BIOS, EntryCategories +from resolve.cores import platform_scope_systems, resolve_platform_cores +from resolve.launchers import launcher_unproven +from resolve.nativemode import digest_algorithm, normalize as normalize_mode, reads_file_contents +from resolve.validation import ( + _build_validation_index, + agnostic_substitute, + baseline_verdict, + build_ground_truth, + destination_owners, + validated_choice, +) + +if TYPE_CHECKING: + from packs.extras import ExtraResolver + from typing_extensions import Unpack + + +_UNPLACED_REASONS = { + "outside_bios_folder": "read in a folder the platform keeps outside the BIOS tree", + "no_roms_directory": "read below a roms folder the platform's registry does not name", + "no_emulators_directory": "read in an emulator folder the platform's registry does not describe", + "no_configs_directory": "read below a configs folder the platform's file does not record", + "no_platform_slug": "no platform slug for its system", + "below_platform_folder": "below the folder the platform lists", + "no_save_directory": "read below a save directory the platform keeps in no fixed place", + "no_core_folder": "read below the save directory and the profile names no library_name", + "no_save_system": "read below a save folder per system and no system runs the core there", +} + + +def _mark_unplaced(config: dict, undeclared: list[dict], profiles: dict) -> None: + """What the builder cannot place is not in the pack, held or not.""" + from packs.extras import unplaceable_extras + + unplaced = unplaceable_extras(config, undeclared, profiles) + for u in undeclared: + if u.get("bundled"): + # Installed with the emulator, so already on the user's machine: + # the pack leaves it out, held or not. + u["in_pack"] = False + u["omitted"] = "installed with its emulator" + continue + reason = unplaced.get( + (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") + ) + if not reason and u.get("root") in OUTER_ROOTS: + # The pack is extracted into the BIOS folder: the installer + # writes this file into the roms or emulator folder, the pack + # cannot. + u["in_pack"] = False + u["omitted"] = f"read below the {u['root']} folder, which only the installer reaches" + continue + if reason: + u["in_pack"] = False + u["omitted"] = _UNPLACED_REASONS[reason] + + +_HIDDEN_REASONS = { + "case_twin": "a packed file of the same name in another case takes its place", + "path_conflict": "a packed file occupies its directory", +} + + +@dataclass(frozen=True) +class _BuilderPass: + """The arguments the builder's own pass over the core files is run with.""" + + emulators_dir: str + db: dict + emu_profiles: dict | None + target_cores: set[str] | None + region_drops: set[str] | None + report: list[dict] | None + resolver: ExtraResolver | None + placed_kind: dict[str, str] | None + system_ids: list[str] | None + required_only: bool + + +def _mark_hidden( + config: dict, + undeclared: list[dict], + shipped: dict[str, str | None], + builder: _BuilderPass, +) -> set[str]: + """What the builder holds but cannot place beside the files it packed. + + Returns the full destinations the builder fills with a core's file. + ``builder.report`` is the gap report the caller already computed with the + builder's arguments. Without it the builder's pass computes its own. + """ + from packs.extras import hidden_extras + + placed: set[str] = set() + hidden = hidden_extras( + config, builder.emulators_dir, builder.db, + builder.emu_profiles if builder.emu_profiles is not None + else load_emulator_profiles(builder.emulators_dir), + shipped, builder.target_cores, builder.region_drops, placed, + report=builder.report, resolver=builder.resolver, placed_kind=builder.placed_kind, + system_ids=builder.system_ids, required_only=builder.required_only, + ) + for u in undeclared: + reason = hidden.get( + (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") + ) + if reason and u.get("in_repo") and u.get("in_pack", True): + u["in_pack"] = False + u["omitted"] = _HIDDEN_REASONS[reason] + return placed + + +def _builder_placement( + packed_order: list[tuple[str, str, str | None]], case_insensitive: bool, +) -> tuple[dict[str, str], dict[str, str | None]]: + """The platform files the builder writes, and every path it keeps. + + The builder walks the systems in name order and skips a path that a + written file blocks as a directory, or the reverse: RetroArch declares + SGB1.sfc and SGB1.sfc/program.rom, and only the first is in the pack. + An entry without a destination (EmuDeck's system:md5 whitelist) is + judged but takes no path. Returns (path -> local copy written there, + path -> copy or None for each slot kept, a user_provided or external one + included). + """ + from packs.paths import _has_path_conflict, _register_path + + shipped: dict[str, str] = {} + occupied: dict[str, str | None] = {} + seen: set[str] = set() + folded: set[str] = set() + parents: set[str] = set() + for _sys_id, full, local in sorted(packed_order, key=lambda item: item[0]): + # EmuDeck's system:md5 entries name no file: the builder writes none. + if not full or full.endswith("/"): + continue + if ( + full in occupied + or (case_insensitive and full.lower() in folded) + or _has_path_conflict(full, seen, parents) + ): + continue + _register_path(full, seen, parents) + folded.add(full.lower()) + occupied[full] = local + if local is not None: + shipped[full] = local + return shipped, occupied + + +def _dest_key(file_entry: dict, sys_id: str) -> str: + """The path a declaration occupies, as the builder keys its pack.""" + dest = sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) + return dest or f"{sys_id}/{file_entry.get('name', '')}" + + +def _twin_index( + verify_systems: dict, db: dict, base_dest: str, zip_contents: dict, +) -> tuple[dict[str, int], dict[int, tuple[str, dict]]]: + """Which declaration the pack ships at each destination, and every declaration by id.""" + # From the module that defines the rule, not the builder's CLI: importing + # generate_pack made every verify depend on its argparse and manifest code. + from resolve.packfiles import preferred_entries as _preferred_entries + + preferred_entries = _preferred_entries( + verify_systems, db, DEFAULT_BIOS_DIR, base_dest, False, + zip_contents, True, + ) + winners = { + id(fe): (sid, fe) + for sid, system in verify_systems.items() + for fe in system.get("files", []) + } + return preferred_entries, winners + + +@dataclass(frozen=True) +class _DeclarationResolver: + """How a platform run resolves its declarations, as the builder does.""" + + db: dict + zip_contents: dict + data_dir_registry: dict | None + slot_overrides: dict[str, str] + mode: str + platform_profiles: dict + # Which declaration the pack ships at each destination, and every + # declaration by id (_twin_index). + preferred_entries: dict[str, int] + winners: dict[int, tuple[str, dict]] + base_dest: str + + +def _resolve_declaration( + file_entry: dict, sys_id: str, resolver: _DeclarationResolver, +) -> tuple[str | None, str, str | None]: + """Resolve a declaration to the file the pack ships at its destination. + + When another declaration holds the destination, that one's file is + returned and the evidence reset: the winner's hash match is not this + declaration's, which is hashed against the shipped file. + """ + base_dest = resolver.base_dest + bare = sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) + preferred = resolver.preferred_entries.get(f"{base_dest}/{bare}" if base_dest else bare) + held_by, winner = (None, file_entry) + if preferred is not None and preferred != id(file_entry): + held_by, winner = resolver.winners[preferred] + local_path, resolve_status = _resolve_for_platform( + winner, held_by or sys_id, resolver.db, resolver.zip_contents, + resolver.data_dir_registry, resolver.slot_overrides, resolver.mode, + resolver.platform_profiles, + ) + return local_path, "" if held_by else resolve_status, held_by + + +def _twin_unmet( + result: dict, + held_by: str | None, + file_entry: dict | None = None, + sys_id: str = "", + destination: str = "", +) -> bool: + """Mark a declaration unmet at a path another declaration holds. + + The path is answered by the winner's file, which the pack counts once. + This declaration's failure is reported, never folded into the + destination's status. The message names the path, both systems and + what this declaration expects: "is not met at the path coco holds" + named neither the path nor the file wanted there. + """ + if held_by is None or result["status"] == Status.OK: + return False + entry = file_entry or {} + expects = next( + (f" ({h} {str(entry[h]).split(',')[0]})" + for h in ("sha1", "md5", "crc32") if entry.get(h)), + "", + ) + owner = sys_id or "this" + result["discrepancy"] = ( + f"{destination or result.get('name', '')} is declared for {owner}" + f" and for {held_by}. The {owner} declaration{expects} is not met at" + f" the path, which holds the {held_by} file" + ) + # Read by reports that list entries: the destination itself is held, and + # a count by destination does not include this one. + result["settled_by"] = held_by + return True + + +def _resolve_for_platform( + file_entry: dict, + sys_id: str, + db: dict, + zip_contents: dict, + data_dir_registry: dict | None, + slot_overrides: dict[str, str], + mode: str, + platform_profiles: dict, +) -> tuple[str | None, str]: + """Resolve one platform entry the way the pack builder does. + + The builder's own resolution (packresolve.resolve_declaration), read from + disk and the large-file cache: verify never downloads. A frontend that + never reads the bytes takes the filename-free core's own image. + """ + from resolve.packfiles import pending_release_asset, resolve_declaration, run_is_offline + + override = slot_overrides.get( + sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) + ) + local_path, status = resolve_declaration( + file_entry, db, DEFAULT_BIOS_DIR, zip_contents, data_dir_registry, + override, offline=True, + ) + if status in ("not_found", "hash_mismatch") and not run_is_offline(): + # Not in the cache, and the release holds a copy that answers the + # declaration: an online build fetches and packs it (resolve_file). + asset = pending_release_asset(file_entry, db) + if asset: + return asset, RELEASE_ASSET_PENDING + if status == "not_found" and not reads_file_contents(mode): + found = agnostic_substitute(file_entry, sys_id, db, platform_profiles) + if found: + return found[0], "agnostic_fallback" + return local_path, status + + +@dataclass(frozen=True) +class _PlatformRun: + """The inputs of one verify_platform run, read by each of its stages.""" + + config: dict + db: dict + emulators_dir: str + emu_profiles: dict | None + profiles: dict + target_cores: set[str] | None + data_dir_registry: dict | None + zip_contents: dict + system_filter: list[str] | None + required_only: bool + mode: str + base_dest: str + + def full(self, destination: str) -> str: + return f"{self.base_dest}/{destination}" if self.base_dest else destination + + +@dataclass +class _PlatformTally: + """Each declaration's verdict, and the verdicts aggregated by destination.""" + + run: _PlatformRun + platform: str + resolver: _DeclarationResolver + region_drops: set[str] + validation_index: dict + validation_owners: dict[str, list[tuple[str, str]]] + hle_index: dict[str, bool] + categories: EntryCategories + details: list[dict] = field(default_factory=list) + file_status: dict[str, str] = field(default_factory=dict) + file_required: dict[str, bool] = field(default_factory=dict) + file_severity: dict[str, str] = field(default_factory=dict) + # What each entry is: firmware, a game's data, or a name no core the + # platform runs opens. Only firmware gaps carry a severity. + file_category: dict[str, str] = field(default_factory=dict) + # (system, full destination, local copy) of each declaration the builder + # writes, and None for one whose slot it keeps without a file from the + # collection (user_provided, external). Placed below in the builder's order. + packed_order: list[tuple[str, str, str | None]] = field(default_factory=list) + shipped_keys: set[str] = field(default_factory=set) + results_at: dict[str, list[dict]] = field(default_factory=dict) + + def judge(self, sys_id: str, file_entry: dict) -> None: + """Verify one declaration and add it to its destination's tally.""" + destination = sanitize_pack_path( + file_entry.get("destination", file_entry.get("name", "")) + ) + if self.region_drops and destination in self.region_drops: + return + local_path, resolve_status, held_by = _resolve_declaration( + file_entry, sys_id, self.resolver, + ) + result, local_path = self._verdict( + file_entry, sys_id, local_path, resolve_status, destination, + ) + result["system"] = sys_id + result["hle_fallback"] = self.hle_index.get(file_entry.get("name", ""), False) + result["ground_truth"] = build_ground_truth( + file_entry.get("name", ""), + self.validation_index, + ) + self.details.append(result) + config = self.run.config + mode = self.run.mode + # Occupied only where the builder ships the declaration: a hash + # the frontend refuses is left out, and the destination stays free + # for a core's file the pack does carry. + if ( + local_path + and result["status"] != Status.MISSING + and baseline_verdict( + file_entry, local_path, resolve_status, mode, config.get("hash_rule", "") + )[1] is None + ): + self.packed_order.append((sys_id, self.run.full(destination), local_path)) + self.shipped_keys.add(_dest_key(file_entry, sys_id)) + if _twin_unmet( + result, held_by, file_entry, sys_id, self.run.full(destination), + ): + return + self._aggregate(sys_id, file_entry, destination, result) + + def _verdict( + self, file_entry: dict, sys_id: str, local_path: str | None, + resolve_status: str, destination: str, + ) -> tuple[dict, str | None]: + """The declaration's result, and the local copy the pack writes for it.""" + config = self.run.config + mode = self.run.mode + stored = _storage_verdict(file_entry, emulator_pack=False) + if resolve_status == RELEASE_ASSET_PENDING: + # Counted as an online build counts it, which fetches the + # asset. Under --offline the builder cannot, and neither + # does this report (_resolve_for_platform). + result = { + "name": file_entry.get("name", ""), + "required": file_entry.get("required", True), + "status": Status.OK, + "release_asset": local_path, + "reason": "release asset, fetched when the pack is built", + } + # Written at its path like any held file: keyed to None, it + # stayed out of pack_destinations and step 5 read the pack's + # copy as a file only the pack holds. + self.packed_order.append((sys_id, self.run.full(destination), local_path)) + self.shipped_keys.add(_dest_key(file_entry, sys_id)) + return result, None + if stored is not None: + # The builder keeps the slot: instructions for a user_provided + # file, the download for an external one, whether it arrives + # or not. No core file goes there. + self.packed_order.append((sys_id, self.run.full(destination), None)) + return stored, None + if not reads_file_contents(mode): + return verify_entry_existence( + file_entry, + local_path, + self.validation_index, + self.run.db, + destination, + self.validation_owners, + resolve_status, + config.get("platform", ""), + ), local_path + if digest_algorithm(mode) == "sha1": + return verify_entry_sha1(file_entry, local_path), local_path + result = verify_entry_md5( + file_entry, local_path, resolve_status, config.get("hash_rule", "") + ) + # Emulator-level validation: informational for platform packs. + # Platform verification (MD5) is the authority. Emulator + # mismatches are reported as discrepancies, not failures. + if result["status"] == Status.OK: + _chosen, disagreement = validated_choice( + file_entry, local_path, self.run.db, self.validation_index, "bios", + digest_algorithm(mode), destination, self.validation_owners, + ) + if disagreement: + result["discrepancy"] = f"{self.platform} says OK but {disagreement}" + return result, local_path + + def _aggregate( + self, sys_id: str, file_entry: dict, destination: str, result: dict, + ) -> None: + # Aggregate by destination, keyed as the builder keys its pack. + # A declaration that finds nothing leaves the path to one that + # holds a file: the builder packs that file there, whatever the + # order the two are read in. + dest = _dest_key(file_entry, sys_id) + self.results_at.setdefault(dest, []).append(result) + required = file_entry.get("required", True) + cur = result["status"] + prev = self.file_status.get(dest) + hle = self.hle_index.get(file_entry.get("name", ""), False) + sev = compute_severity(cur, required, self.run.mode, hle) + explained = self.categories.explain(file_entry, destination, sys_id) + category = explained.pop("category") + result["category"] = category + result["category_evidence"] = explained + if cur != Status.MISSING: + # A held entry is firmware for the counts: its category only + # documents it. + category = BIOS + if self.file_category.get(dest, category) == BIOS: + category = BIOS + self.file_category[dest] = category + if prev is not None and (cur == Status.MISSING) != (prev == Status.MISSING): + if cur == Status.MISSING: + return + del self.file_status[dest], self.file_severity[dest] + prev = None + if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(prev, 0): + self.file_status[dest] = cur + self.file_required[dest] = required + prev_sev = self.file_severity.get(dest) + if prev_sev is None or _SEVERITY_ORDER.get(sev, 0) > _SEVERITY_ORDER.get( + prev_sev, 0 + ): + self.file_severity[dest] = sev + + def settle_groups(self) -> None: + """RetroBat's group: one file of it held is enough, and the others are + reported OPTIONAL (batocera-systems/Program.cs). None held, each stays + required.""" + members: dict[tuple[str, str], list[str]] = {} + for sys_id, system in self.run.config.get("systems", {}).items(): + for file_entry in system.get("files", []): + if file_entry.get("group"): + dest = _dest_key(file_entry, sys_id) + if dest in self.file_status: + members.setdefault((sys_id, file_entry["group"]), []).append(dest) + for dests in members.values(): + if not any(self.file_status[d] == Status.OK for d in dests): + continue + for dest in dests: + if self.file_status[dest] == Status.MISSING: + self.file_required[dest] = False + self.file_severity[dest] = compute_severity( + Status.MISSING, False, self.run.mode + ) + for result in self.results_at.get(dest, []): + result["required"] = False + + def credit_placed(self, placed: set[str]) -> None: + """An existence frontend is satisfied by any file at the path, and the + builder fills a free platform destination with a core's file.""" + for dest, status in self.file_status.items(): + if status == Status.MISSING and self.run.full(dest) in placed: + self.file_status[dest] = Status.OK + self.file_severity[dest] = Severity.OK + for result in self.results_at.get(dest, []): + result["status"] = Status.OK + + def severity_counts(self) -> tuple[dict[str, int], dict[str, list[str]]]: + """Destinations by severity, and the missing ones that are not firmware.""" + counts = { + Severity.OK: 0, + Severity.INFO: 0, + Severity.WARNING: 0, + Severity.CRITICAL: 0, + } + not_firmware: dict[str, list[str]] = {} + for dest, s in self.file_severity.items(): + category = self.file_category.get(dest, BIOS) + if category != BIOS and self.file_status.get(dest) == Status.MISSING: + not_firmware.setdefault(category, []).append(dest) + continue + counts[s] = counts.get(s, 0) + 1 + return counts, not_firmware + + +def _cut_game_data( + config: dict, + emu_profiles: dict | None, + emulators_dir: str, + data_dir_registry: dict | None, + target_cores: set[str] | None, + system_filter: list[str] | None, +) -> tuple[dict, dict, list[str]]: + """The config and profiles of a --no-game-data pack, and what it leaves out.""" + from resolve.gamedata import without_game_data + + if emu_profiles is None: + emu_profiles = load_emulator_profiles(emulators_dir) + cut = without_game_data(config, emu_profiles, data_dir_registry, target_cores) + config, emu_profiles = cut.config, cut.profiles + systems = config.get("systems", {}) + in_scope = set(select_systems(systems, system_filter) if system_filter else systems) + cut.left_out = [ + item for item in cut.left_out + if item.layer == "core" or item.system in in_scope + ] + return config, emu_profiles, cut.report_lines() + + +def _required_declarations(verify_systems: dict) -> dict: + return { + sys_id: { + **system, + "files": [ + fe for fe in system.get("files", []) if fe.get("required") is not False + ], + } + for sys_id, system in verify_systems.items() + } + + +def _region_pass( + run: _PlatformRun, verify_systems: dict, pack_overrides: dict, regions: list[str], +) -> tuple[set[str], list[str], dict[tuple[str, str, str], str]]: + """The destinations a region run withdraws, the groups no file answers, + and the destination of each core extra.""" + from resolve import regions as resolve_regions + + # The builder owns pack composition, so it owns the grouping the region + # pass reads. Grouping the platform files here and the core extras + # there let the two answer differently on one request: the report kept + # every core extra a region run withdraws from the pack. + from packs.extras import platform_region_groups + + config = run.config + held: set[str] = set() + region_groups, region_extra_dests = platform_region_groups( + config, + verify_systems, + run.emulators_dir, + run.db, + config.get("base_destination", ""), + run.profiles, + target_cores=run.target_cores, + required_only=run.required_only, + held_out=held, + zip_contents=run.zip_contents, + data_registry=run.data_dir_registry, + slot_overrides=pack_overrides, + ) + region_index = resolve_regions.platform_region_index(config, run.profiles, run.target_cores) + region_drops = resolve_regions.resolve_region_drops( + region_groups, region_index, regions, held, + ) + # The pack README names these: no file answers the request, so every + # candidate stays. Reported here too, or verify reads all OK for a + # system that has no BIOS for the region asked. + region_fallbacks = resolve_regions.fallback_groups( + region_groups, region_index, regions + ) + return region_drops, region_fallbacks, region_extra_dests + + +def _platform_gaps( + run: _PlatformRun, + occupied: dict[str, str | None], + region_drops: set[str], + region_extra_dests: dict[tuple[str, str, str], str], + validation_index: dict, + validation_owners: dict[str, list[tuple[str, str]]], +) -> tuple[list[dict], set[str], dict[str, str]]: + """The core files of the pack: the gap report as the builder narrows it, + the destinations it fills, and the category of each.""" + config = run.config + # Cross-reference undeclared files, called exactly as the builder calls + # it: its declarations, not the enriched ones (a core file the platform + # also declares under another name is packed at the core's own path, 21 + # such files in the RetroArch pack), and no names from inside archives + # or data trees (a loose file whose name exists only as a member of + # naomi2.zip was counted "in pack" while the builder shipped nothing). + undeclared = find_undeclared_files( + config, + run.emulators_dir, + run.db, + run.emu_profiles, + target_cores=run.target_cores, + declared_names=platform_declarations(config, run.db, enrich=False), + ) + # The builder's own pass reads the same report: computed once here and + # handed over as it stands now, before the markings below. + report_for_builder = [dict(u) for u in undeclared] + if run.system_filter: + # A system pack carries the extras its systems own. + from packs.extras import report_owned_by_systems + + undeclared = report_owned_by_systems(undeclared, run.system_filter) + if run.required_only: + undeclared = [u for u in undeclared if u.get("required") is not False] + if region_drops: + undeclared = [ + u + for u in undeclared + if region_extra_dests.get( + (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") + ) + not in region_drops + ] + if run.required_only: + # One member of a required set, as the builder keeps it. + spares = core_file_spares(undeclared) + undeclared = [u for u in undeclared if id(u) not in spares] + _mark_unplaced(config, undeclared, run.profiles) + from packs.extras import ExtraResolver + + placed_kind: dict[str, str] = {} + placed = _mark_hidden(config, undeclared, occupied, _BuilderPass( + run.emulators_dir, run.db, run.emu_profiles, run.target_cores, region_drops, + report_for_builder, + ExtraResolver( + run.db, DEFAULT_BIOS_DIR, run.zip_contents, run.data_dir_registry, + validation_index, validation_owners, profiles=run.profiles, + pending_assets=True, + ), + placed_kind, + run.system_filter, + run.required_only, + )) + return undeclared, placed, placed_kind + + +def _profile_coverage( + profiles: dict, verify_systems: dict, file_status: dict[str, str], + validation_index: dict, +) -> tuple[int, int]: + """Destinations whose file a core validates, and those a profile names.""" + gt_filenames = set(validation_index) + profiled_names: set[str] = set() + for profile in profiles.values(): + if profile.get("type") in ("launcher", "alias"): + continue + for f in profile.get("files", []): + name = f.get("name", "") + if name: + profiled_names.add(name) + profiled_names.update(f.get("aliases") or []) + dest_to_name: dict[str, str] = {} + for sys_id, system in verify_systems.items(): + for fe in system.get("files", []): + dest_to_name.setdefault(_dest_key(fe, sys_id), fe.get("name", "")) + with_validation = sum( + 1 for dest in file_status if dest_to_name.get(dest, "") in gt_filenames + ) + with_profile = sum( + 1 for dest in file_status if dest_to_name.get(dest, "") in profiled_names + ) + return with_validation, with_profile + + +class PlatformNarrowing(TypedDict, total=False): + """The narrowings of a platform pack verify_platform reports on.""" + + regions: list[str] | None + system_filter: list[str] | None + no_game_data: bool + required_only: bool + + +def verify_platform( + config: dict, + db: dict, + emulators_dir: str = DEFAULT_EMULATORS_DIR, + emu_profiles: dict | None = None, + target_cores: set[str] | None = None, + data_dir_registry: dict | None = None, + **narrowing: Unpack[PlatformNarrowing], +) -> dict: + """Verify all BIOS files for a platform, including cross-reference gaps. + + ``no_game_data`` reports on the pack built with --no-game-data: the + game data cut as the builder cuts it, and named in ``left_out``. + + A region priority list narrows the report to the files a pack built with the + same list would carry, using the same selection function as the builder. + ``system_filter`` does the same for a pack built with --system: the + systems it keeps and the core extras those systems own. + ``required_only`` reports on the pack built with --required-only: the + declarations, trees and core extras marked ``required: false`` are left + out before any of them takes a path, as the builder leaves them out. + """ + unknown = sorted(set(narrowing) - set(PlatformNarrowing.__annotations__)) + if unknown: + raise TypeError(f"verify_platform() got an unexpected keyword argument '{unknown[0]}'") + regions = narrowing.get("regions") + system_filter = narrowing.get("system_filter") + no_game_data = narrowing.get("no_game_data", False) + required_only = narrowing.get("required_only", False) + left_out: list[str] = [] + if no_game_data: + config, emu_profiles, left_out = _cut_game_data( + config, emu_profiles, emulators_dir, data_dir_registry, target_cores, + system_filter, + ) + # Normalized once: a typo in a platform YAML must not verify with one + # mode and be scored with another. + mode = normalize_mode(config.get("verification_mode")) + platform = config.get("platform", "unknown") + + # The builder settles a destination claimed by both layers, and this must read + # the same decision, or the two tools describe different packs. + has_zipped = any( + fe.get("zipped_file") + for sys in config.get("systems", {}).values() + for fe in sys.get("files", []) + ) + zip_contents = build_zip_contents_index(db) if has_zipped else {} + + # Loaded before the slot overrides: a caller passing no profiles (the + # README's coverage) got no override and reported a discrepancy at a slot + # the pack settles. + profiles = ( + emu_profiles + if emu_profiles is not None + else load_emulator_profiles(emulators_dir) + ) + base_dest = config.get("base_destination", "") + pack_overrides = slots.pack_overrides( + config, profiles, db, zip_contents, data_dir_registry, + target_cores=target_cores, + ) + slot_overrides = { + (key[len(base_dest) + 1:] if base_dest and key.startswith(f"{base_dest}/") else key): path + for key, path in pack_overrides.items() + } + + # Build HLE + validation indexes from emulator profiles + # Ground truth comes from the emulators the platform runs. A standalone + # profile that loads a same-named file of its own (ZEsarUX's 48K + # cpc6128.rom against cap32's 32K one) has nothing to say about a + # RetroArch pack, nor does its HLE: dosbox-x's FONT.ROM fallback turned a + # missing required Batocera BIOS into INFO. + plat_cores = resolve_platform_cores(config, profiles) + platform_profiles = {name: profiles[name] for name in plat_cores} + hle_index = { + f.get("name", ""): True + for profile in platform_profiles.values() + for f in profile.get("files", []) + if f.get("hle_fallback") + } + validation_index = _build_validation_index(platform_profiles) + validation_owners = destination_owners(platform_profiles) + + verify_systems = platform_scope_systems(config, profiles, target_cores, system_filter) + if required_only: + verify_systems = _required_declarations(verify_systems) + + categories = EntryCategories(config, profiles, data_dir_registry) + run = _PlatformRun( + config, db, emulators_dir, emu_profiles, profiles, target_cores, + data_dir_registry, zip_contents, system_filter, required_only, mode, base_dest, + ) + + region_drops: set[str] = set() + region_fallbacks: list[str] = [] + region_extra_dests: dict[tuple[str, str, str], str] = {} + if regions: + region_drops, region_fallbacks, region_extra_dests = _region_pass( + run, verify_systems, pack_overrides, regions, + ) + + # A destination two systems declare with two hashes ships one file, the + # one the builder prefers. The other declaration is scored against that + # file, as the frontend will score it after installation: RetroDECK's + # xroar component hashes bios/disk.rom and finds the PC-88 ROM. + preferred_entries, winners = _twin_index( + verify_systems, db, base_dest, zip_contents + ) + tally = _PlatformTally( + run, platform, + _DeclarationResolver( + db, zip_contents, data_dir_registry, slot_overrides, mode, + platform_profiles, preferred_entries, winners, base_dest, + ), + region_drops, validation_index, validation_owners, hle_index, categories, + ) + for sys_id, system in verify_systems.items(): + for file_entry in system.get("files", []): + tally.judge(sys_id, file_entry) + tally.settle_groups() + + shipped, occupied = _builder_placement( + tally.packed_order, bool(config.get("case_insensitive_fs", False)) + ) + undeclared, placed, placed_kind = _platform_gaps( + run, occupied, region_drops, region_extra_dests, validation_index, + validation_owners, + ) + # What the builder places from the cores, one per pack path, by category: + # several entries claim one path (rom.key from three Amiga cores) and the + # builder ships one file there. The category travels on the extra: a copy + # the second pass makes has no gap report entry to look it up by. + packed_extras = {"bios": 0, "game_data": 0} + for category in placed_kind.values(): + packed_extras["game_data" if category == "game_data" else "bios"] += 1 + if not reads_file_contents(mode): + tally.credit_placed(placed) + + counts, not_firmware = tally.severity_counts() + file_status = tally.file_status + + # Held but refused: on a hash platform the builder leaves out a file whose + # declared hash the local copy contradicts. Counted apart, so a coverage + # figure never calls present what the pack does not carry. + excluded = sorted( + dest for dest, status in file_status.items() + if status == Status.UNTESTED and dest not in tally.shipped_keys + ) + + # Count by file status (ok/untested/missing) + status_counts: dict[str, int] = {} + for s in file_status.values(): + status_counts[s] = status_counts.get(s, 0) + 1 + + exclusions = find_exclusion_notes( + config, emulators_dir, emu_profiles, target_cores=target_cores + ) + + with_validation, with_profile = _profile_coverage( + profiles, verify_systems, file_status, validation_index, + ) + total = len(file_status) + + # The paths a pack built from this report holds, as written in the ZIP + # (base_destination stripped, as the builder flattens it). The pipeline + # compares this set with the archive: equal counts can hide one file + # credited here and another written there. + from packs.paths import _flat + + pack_destinations = sorted( + {_flat(dest, base_dest, True) for dest in shipped} | { + _flat(dest, base_dest, True) for dest in placed + } + ) + + return { + "platform": platform, + **({"systems": sorted(verify_systems)} if system_filter else {}), + "verification_mode": mode, + "total_files": total, + "pack_destinations": pack_destinations, + "severity_counts": counts, + "status_counts": status_counts, + "missing_not_firmware": {k: sorted(v) for k, v in sorted(not_firmware.items())}, + "excluded_files": excluded, + "packed_extras": packed_extras, + "undeclared_files": undeclared, + # Reported apart, never scored: no severity, count or exit code reads it. + "launcher_reads_not_held": launcher_reads_not_held( + {config.get("_key", platform): config}, db, profiles, data_dir_registry + ), + # Records a config file does not prove: listed, never consumed. + "launcher_unproven": launcher_unproven({config.get("_key", platform): config}, profiles), + "exclusion_notes": exclusions, + "region_fallbacks": sorted(region_fallbacks), + **({"left_out": left_out} if no_game_data else {}), + # Every tree of the registry answers a declaration by its tail, so + # one that was never refreshed leaves its files missing here while + # an online pack build refreshes it and packs them. + "data_dir_notices": sorted( + key for key, entry in (data_dir_registry or {}).items() + if not os.path.isdir(entry.get("local_cache", "")) + ), + "details": tally.details, + "ground_truth_coverage": { + "with_validation": with_validation, + "with_profile": with_profile, + "platform_only": total - with_validation, + "total": total, + "applicable": bool(resolve_platform_cores(config, profiles)), + }, + } diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py new file mode 100644 index 000000000..08d16d81e --- /dev/null +++ b/scripts/packs/crossref.py @@ -0,0 +1,1444 @@ +"""Emulator profiles against platform declarations: what the cores load that a platform omits.""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json +import sys +import zipfile +import zlib +from collections import Counter +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, TypedDict + +from core.hashing import parse_hash_list, parse_md5_list +from core.paths import REPO_ROOT +from model.alternatives import set_keys, set_requirements, settle_sets +from model.database import get_mame_clone_map +from model.declarations import OUTER_ROOTS +from model.platforms import load_platform_config +from model.registry import list_registered_platforms, load_data_dir_registry +from model.systems import _norm_system_id +from resolve.archives import archive_entry +from resolve.content import content_fits, name_match_size_ok +from resolve.directories import directory_members, expand_directory_entries +from resolve.launchers import ( + LauncherLayer, + _directories as launcher_directories, + _names as launcher_names, + bound_launchers, + catalogued_model_files, + held_record, + name_settings, + set_by, + setting_readers, + suffixed_stem, +) +from resolve.layout import system_dir_path +from resolve.localfile import resolve_local_file +from resolve.ownership import _foreign_tree, _owner_tokens +from resolve.standalone import platform_layouts +from resolve.validation import ( + case_folded_slots, + declaration_settles, + inner_rom_check, + installed_with_emulator, + outside_gap_scope, + read_from_save_dir, + unread_on, + with_archive_members, +) + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +DEFAULT_PLATFORMS_DIR = "platforms" + + +def load_platform_files( + platforms_dir: str, + platforms: list[str] | None = None, +) -> tuple[dict[str, set[str]], dict[str, set[str]]]: + """Collect declared filenames + data_directories per system. + + Restricted to *platforms* when given, otherwise every registered platform. + Keyed by the normalized system ID: a profile writes `sega-megacd` where + RetroArch writes `sega-mega-cd`, and an exact match called 924 declared + files undeclared. + """ + declared: dict[str, set[str]] = {} + platform_data_dirs: dict[str, set[str]] = {} + for platform_name in platforms or list_registered_platforms( + platforms_dir + ): + config = load_platform_config(platform_name, platforms_dir) + for sys_id, system in config.get("systems", {}).items(): + for fe in system.get("files", []): + name = fe.get("name", "") + if name: + declared.setdefault(_norm_system_id(sys_id), set()).add(name) + for dd in system.get("data_directories", []): + ref = dd.get("ref", "") + if ref: + platform_data_dirs.setdefault(_norm_system_id(sys_id), set()).add(ref) + return declared, platform_data_dirs + + +def declared_names( + platforms_dir: str, platforms: list[str] | None, db: dict +) -> dict[str, list[tuple[int | None, str]]]: + """Every name the platforms declare, with each declaration's size and slot. + + The report judged "undeclared" per normalized system id, which does not + bring bk and elektronika-bk, or nintendo-sgb and nintendo-super-game-boy, + together: 646 entries whose exact name a platform declares were counted + undeclared, while verify and the site read one flat index. + """ + from model.declarations import merged_platform_declarations + + return merged_platform_declarations( + [ + load_platform_config(platform_name, platforms_dir) + for platform_name in platforms or list_registered_platforms( + platforms_dir + ) + ], + db, + ) + + +def folded_declared_slots( + platforms_dir: str, platforms: list[str] | None, db: dict +) -> frozenset[str]: + """The slots platforms whose filesystem folds case fill, any spelling. + + 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 model.declarations import platform_declarations + + slots: set[str] = set() + for platform_name in platforms or list_registered_platforms( + platforms_dir + ): + config = load_platform_config(platform_name, platforms_dir) + slots |= case_folded_slots(config, platform_declarations(config, db)) + return frozenset(slots) + + +def _build_supplemental_index( + data_root: str = "data", bios_root: str = "bios" +) -> set[str]: + """Build a set of filenames and directory names in data/ and inside bios/ ZIPs. + + A directory is indexed only with its trailing slash: a bare name matched a + file entry of the same name, and BasiliskII's required `ROM` read as held + because cpcemu keeps a directory called ROM. + """ + names: set[str] = set() + root_path = Path(data_root) + if root_path.is_dir(): + for fpath in root_path.rglob("*"): + if fpath.name.startswith("."): + continue + if fpath.is_file(): + names.add(fpath.name) + names.add(fpath.name.lower()) + else: + names.add(fpath.name + "/") + names.add(fpath.name.lower() + "/") + if fpath.is_dir(): + # Also index relative path from data/subdir/ for directory entries + parts = fpath.relative_to(root_path).parts + if len(parts) > 1: + rel = "/".join(parts[1:]) + names.add(rel + "/") + names.add(rel.lower() + "/") + bios_path = Path(bios_root) + if bios_path.is_dir(): + # Index directory names for directory-type entries (e.g., "nestopia/samples/moepro/") + for dpath in bios_path.rglob("*"): + if dpath.is_dir() and not dpath.name.startswith("."): + names.add(dpath.name + "/") + names.add(dpath.name.lower() + "/") + names |= _zip_member_names(bios_path) + return names + + +def _zip_member_names(bios_path: Path) -> set[str]: + """Basenames of the files inside every ZIP under bios/, both cases.""" + import zipfile + + names: set[str] = set() + for zpath in bios_path.rglob("*.zip"): + try: + with zipfile.ZipFile(zpath) as zf: + members = [m for m in zf.namelist() if not m.endswith("/")] + except (zipfile.BadZipFile, OSError) as exc: + print(f" WARNING: unreadable archive {zpath}: {exc}", file=sys.stderr) + continue + for member in members: + basename = member.rsplit("/", 1)[-1] + names.update((basename, basename.lower())) + return names + + +def _resolve_source( + fname: str, + by_name: dict[str, list], + by_name_lower: dict[str, str], + data_names: set[str] | None = None, + by_path_suffix: dict | None = None, + file_entry: dict | None = None, + db_files: dict | None = None, + bios_dir: str | None = None, +) -> str | None: + """Return the source category for a file, or None if not found. + + Returns ``"bios"`` (in database.json / bios/), ``"data"`` (in data/), + or ``None`` (not available anywhere). + + A name hit whose size contradicts a size the emulator verifies is not the + file, so it does not count as available. Nor is one whose bytes carry + none of the hashes the entry declares: a name never wins over a declared + hash, and zquestclassic's ending.mid read as held because Hydra Castle + Labyrinth has another file of that name. + + Another casing of the name in another emulator's tree proves nothing, as + in resolve_local_file's case-insensitive step: dosbox-x's et4000.bin read + as held through pcem's et4000.BIN, which the pack and the installer + refuse it. + """ + declared = _declared_content(file_entry or {}) + owners = _owner_tokens(file_entry or {}) + + def _can_be(sha1s: list | str) -> bool: + if not file_entry or db_files is None: + return True + if not isinstance(sha1s, list): + sha1s = [sha1s] + return any( + name_match_size_ok(file_entry, db_files.get(sha1, {}).get("size")) + and content_fits(file_entry, db_files.get(sha1, {}).get("path", "")) + and _record_carries(sha1, db_files.get(sha1, {}), declared) + for sha1 in sha1s + ) + + def _name_hit(name: str) -> bool: + """Whether the files indexed under *name* can be this entry.""" + return _can_be(by_name.get(name) or []) + + def _folded_hit(name: str) -> bool: + """_name_hit for a name matched in another casing.""" + return _can_be([ + sha1 for sha1 in by_name.get(name) or [] + if db_files is None + or not _foreign_tree(db_files.get(sha1, {}).get("path", ""), owners) + ]) + + # bios/ via database.json by_name + if fname in by_name and _name_hit(fname): + return "bios" + stripped = fname.rstrip("/") + basename = stripped.rsplit("/", 1)[-1] if "/" in stripped else None + if basename and basename in by_name and _name_hit(basename): + return "bios" + key = fname.lower() + if key in by_name_lower and _folded_hit(by_name_lower[key]): + return "bios" + if basename and basename.lower() in by_name_lower and _folded_hit( + by_name_lower[basename.lower()] + ): + return "bios" + # bios/ via by_path_suffix (regional variants) + if by_path_suffix and fname in by_path_suffix and _can_be(by_path_suffix[fname]): + return "bios" + # bios/ under the canonical MAME set name, as resolve_local_file does: + # a renamed archive is held once, under the name the dedup kept. + canonical = get_mame_clone_map(bios_dir).get(fname) + if canonical and canonical != fname: + if canonical in by_name and _name_hit(canonical): + return "bios" + if canonical.lower() in by_name_lower and _folded_hit( + by_name_lower[canonical.lower()] + ): + return "bios" + if data_names and _data_hit(fname, basename, file_entry, data_names): + return "data" + return None + + +def _data_hit( + fname: str, basename: str | None, file_entry: dict | None, data_names: set[str] +) -> bool: + """Whether data/ or a ZIP holds the name: a directory entry looks for a + directory, a file entry for a file. A file entry that declares a hash is + held only by a copy carrying it: touchhle's LiberationMono-Regular.ttf + read as held because idtech4a++'s extras.zip has another font of that + name.""" + looked_up = [fname, fname.lower()] + ([basename, basename.lower()] if basename else []) + if fname.endswith("/") or (file_entry or {}).get("type") == "directory": + looked_up = [name.rstrip("/") + "/" for name in looked_up] + return any(name in data_names for name in looked_up) + if not any(name in data_names for name in looked_up): + return False + declared = _declared_content(file_entry or {}) + if not declared: + return True + return any( + _content_matches(location, declared) + for location in _supplemental_locations().get((basename or fname).lower(), ()) + ) + + +_HASH_FIELDS = ("sha1", "md5", "sha256", "crc32") + + +def _record_carries(sha1: str, record: dict, declared: dict[str, set[str]]) -> bool: + """Whether a database record has one of the declared hashes, or none is declared.""" + if not declared: + return True + actual = { + "sha1": sha1.lower(), + **{field: str(record.get(field) or "").lower() for field in ("md5", "sha256", "crc32")}, + } + return any( + actual[field] and actual[field] in values + for field, values in declared.items() + ) + + +def _declared_content(file_entry: dict) -> dict[str, set[str]]: + """The hashes an entry declares, lowercased, by algorithm.""" + declared: dict[str, set[str]] = {} + for field in _HASH_FIELDS: + found = set(parse_hash_list(file_entry.get(field))) + if found: + declared[field] = found + return declared + + +_locations_cache: dict[tuple[str, str], dict[str, list[tuple[str, str]]]] = {} + + +def _supplemental_locations( + data_root: str = "data", bios_root: str = "bios" +) -> dict[str, list[tuple[str, str]]]: + """Where each name of the supplemental index sits: a data/ file, or a + member of a ZIP under bios/, keyed by lowercased basename.""" + key = (data_root, bios_root) + if key in _locations_cache: + return _locations_cache[key] + found: dict[str, list[tuple[str, str]]] = {} + root = Path(data_root) + if root.is_dir(): + for path in root.rglob("*"): + if path.is_file() and not path.name.startswith("."): + found.setdefault(path.name.lower(), []).append((str(path), "")) + for zpath in Path(bios_root).rglob("*.zip") if Path(bios_root).is_dir() else (): + try: + with zipfile.ZipFile(zpath) as zf: + members = [m for m in zf.namelist() if not m.endswith("/")] + except (zipfile.BadZipFile, OSError) as exc: + print(f" WARNING: unreadable archive {zpath}: {exc}", file=sys.stderr) + continue + for member in members: + found.setdefault(member.rsplit("/", 1)[-1].lower(), []).append( + (str(zpath), member) + ) + _locations_cache[key] = found + return found + + +def _content_matches(location: tuple[str, str], declared: dict[str, set[str]]) -> bool: + """Whether the file or member at *location* carries a declared hash.""" + path, member = location + try: + if member: + with zipfile.ZipFile(path) as zf: + if set(declared) == {"crc32"}: + return f"{zf.getinfo(member).CRC:08x}" in declared["crc32"] + data = zf.read(member) + else: + data = Path(path).read_bytes() + except (zipfile.BadZipFile, KeyError, OSError) as exc: + print(f" WARNING: cannot read {path} {member}: {exc}", file=sys.stderr) + return False + actual = { + "sha1": hashlib.sha1(data).hexdigest(), + "md5": hashlib.md5(data).hexdigest(), + "sha256": hashlib.sha256(data).hexdigest(), + "crc32": f"{zlib.crc32(data) & 0xFFFFFFFF:08x}", + } + return any(actual[field] in values for field, values in declared.items()) + + +_tree_cache: dict[tuple[str, str], list[str]] = {} + + +def _trees(data_root: str, bios_root: str) -> list[str]: + """Every directory under data/ and bios/, as a path with a trailing slash.""" + key = (data_root, bios_root) + if key not in _tree_cache: + _tree_cache[key] = sorted( + f"{path.as_posix()}/" + for root in (data_root, bios_root) if Path(root).is_dir() + for path in Path(root).rglob("*") + if path.is_dir() + and not any(p.startswith(".") for p in path.relative_to(root).parts) + ) + return _tree_cache[key] + + +def held_copy( + entry: dict, data_root: str = "data", bios_root: str = "bios" +) -> tuple[str, str] | None: + """The data/ file, directory or bios/ ZIP member holding an entry. + + The database indexes the files under bios/, and an entry held otherwise + (specmate.rom as a member of spectrum_opus.zip, Dolphin's fonts in its + data directory) read as held with no word of where. Returns (path, + member), the member empty for a file or a directory. A file entry that + declares a hash is held only by a copy carrying it, as _data_hit judges. + """ + names = [entry.get("name", ""), entry.get("path") or "", *(entry.get("aliases") or [])] + names = [str(n) for n in names if n] + if entry.get("type") == "directory" or any(n.endswith("/") for n in names[:1]): + for name in names: + tail = "/" + name.strip("/") + "/" + for tree in _trees(data_root, bios_root): + if tree.endswith(tail): + return tree, "" + return None + declared = _declared_content(entry) + locations = _supplemental_locations(data_root, bios_root) + for name in names: + for location in locations.get(name.rsplit("/", 1)[-1].lower(), ()): + if not declared or _content_matches(location, declared): + return location + return None + + +class FileConsumers: + """Who reads each collected file, joined through the resolver. + + The site joined database files to emulators and platforms by bare name: + each of the four pak0.pk3 of four games was attributed to every engine + reading a pak0.pk3. A consumer here is an entry that resolves to the + file by the evidence the pack uses, so a homonym is nobody's file. + """ + + def __init__( + self, db: dict, zip_contents: dict | None = None, + data_dir_registry: dict | None = None, + ) -> None: + self._db = db + self._zip_contents = zip_contents + # The builder resolves with the data trees: Dolphin's codehandler.bin + # comes from data/dolphin-sys, and without them the name step gave it + # Dolphin-MMJR's copy, which the site then said Dolphin reads. + self._data_dir_registry = ( + data_dir_registry if data_dir_registry is not None + else load_data_dir_registry( + str(REPO_ROOT / DEFAULT_PLATFORMS_DIR) + ) + ) + self._sha1_by_path = { + path: sha1 + for sha1, entry in db.get("files", {}).items() + for path in {entry.get("path", ""), *entry.get("paths", [])} + if path + } + self.platforms: dict[str, set[str]] = {} + # Under which of its systems each platform declares a file, so a + # link can land on that section rather than the page top. + self.platform_systems: dict[str, dict[str, set[str]]] = {} + # Where each platform puts the file in its BIOS directory. + self.platform_destinations: dict[str, dict[str, set[str]]] = {} + self.emulators: dict[str, set[str]] = {} + # The entry that reads each file, by its position in the profile's + # files: a link lands on that entry's card, not the page top. + self.emulator_entries: dict[str, dict[str, int]] = {} + self.emulator_files: dict[str, list] = {} + # Where each platform's pack installs the file, its cores' files + # included: the platform's own list names a fraction of them. + self.installed: dict[str, dict[str, set[str]]] = {} + + def sha1_of(self, entry: dict, dest: str = "", owner: str = "") -> str | None: + """The collected file an entry resolves to, or None. + + A profile entry names its owner, as the builder does: without it the + name step chose another tree's copy, and the page credited the file + the pack does not ship. + """ + if not entry.get("name"): + return None + if owner: + entry = {**entry, "source_profile": owner} + path, status = resolve_local_file( + entry, self._db, self._zip_contents, dest_hint=dest, + data_dir_registry=self._data_dir_registry, + ) + if not path or status == "not_found": + return None + # Batocera pins naomi2.zip by the md5 of a ROM inside it: the resolver + # hands back the archive as a mismatch, and the member settles it as + # the builder does. + if status == "hash_mismatch" and not ( + entry.get("zipped_file") and inner_rom_check(entry, path) == "ok" + ): + return None + return self._sha1_by_path.get(path) + + def add_platforms(self, configs: dict[str, dict]) -> None: + for name, config in configs.items(): + for system_id, system in config.get("systems", {}).items(): + for entry in system.get("files", []): + # No destination hint, as the builder, the manifest and + # verify resolve a declaration: with one, RetroBat's 63 + # mame/hash lists credited another revision than the one + # its manifest installs. + sha1 = self.sha1_of(entry) + if sha1: + self.platforms.setdefault(sha1, set()).add(name) + self.platform_systems.setdefault(sha1, {}).setdefault( + name, set() + ).add(system_id) + where = str(entry.get("destination") or entry["name"]) + # EmuDeck matches by md5 alone: its entries carry a + # system:md5 key, not a place in the folder. + if ":" not in where: + self.platform_destinations.setdefault(sha1, {}).setdefault( + name, set() + ).add(where) + + def add_manifests(self, install_dir: str | Path) -> None: + """Read what each install manifest places, alternatives included.""" + for path in sorted(Path(install_dir).glob("*.json")): + try: + manifest = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + print(f"WARNING: {path}: {exc}", file=sys.stderr) + continue + platform = str(manifest.get("platform") or path.stem) + for entry in manifest.get("files") or []: + for sha1 in {entry.get("sha1"), *( + alt.get("sha1") for alt in entry.get("alternatives") or [] + )} - {None, ""}: + self.installed.setdefault(sha1, {}).setdefault( + platform, set()).add(str(entry.get("dest", ""))) + + def sha1_at(self, path: str) -> str | None: + """The file the database records at a collection path.""" + return self._sha1_by_path.get(path) + + def path_of(self, sha1: str) -> str: + """The collection path the database records for a file.""" + return str(self._db.get("files", {}).get(sha1, {}).get("path", "")) + + def directory_members(self, entry: dict) -> dict[str, str]: + """{destination: sha1} of the files a ``type: directory`` entry reads.""" + if entry.get("type") != "directory": + return {} + return { + member["path"]: member["sha1"] + for member in expand_directory_entries([entry], self._db) + if member is not entry + } + + def add_emulators(self, profiles: dict[str, dict]) -> None: + """Each file a profile entry resolves to, a directory's members included. + + A directory entry was resolved by its own name and found nothing: + 11,976 files under alephone's Plugins/, cdogs' and thextech's trees + named no emulator on their card. + """ + for name, profile in profiles.items(): + if profile.get("type") == "alias": + continue + files = profile.get("files") or [] + self.emulator_files[name] = files + # A file a profile names keeps its own entry over the directory + # that also holds it. + order = sorted( + (i for i, entry in enumerate(files) if isinstance(entry, dict)), + key=lambda i: files[i].get("type") == "directory", + ) + for index in order: + entry = files[index] + members = self.directory_members(entry) + if members: + found = [ + self.sha1_of({**entry, "name": dest, "path": dest, "sha1": sha1}, + dest, owner=name) + for dest, sha1 in members.items() + ] + else: + found = [self.sha1_of(*entry_target(entry, files), owner=name)] + for sha1 in found: + if sha1: + self.emulators.setdefault(sha1, set()).add(name) + self.emulator_entries.setdefault(sha1, {}).setdefault(name, index) + + +def entry_target(entry: dict, files: list[dict]) -> tuple[dict, str]: + """The entry a profile entry resolves through, and its destination. + + A ROM read inside an archive is the archive: FBNeo opens sm1.sm1 in + neogeo.zip, and resolved by its crc32 it credited a loose copy FBNeo + never opens, while no neogeo.zip card named FBNeo. The archive + members the profile reads decide between same-named copies, as in + the emulator pack and verify. + """ + if entry.get("archive"): + return archive_entry(entry["archive"], files), "" + return with_archive_members(entry, files), entry.get("path") or "" + + +def entry_source(f: dict, index: dict) -> str | None: + """Where the collection holds a profile entry, or None. + + By name, path and alias, then by any hash the entry declares. The gap + report and the site pages read this one function, so a file is held or + missing in the same way on both. + """ + by_name, by_name_lower = index["by_name"], index["by_name_lower"] + data_names, by_path_suffix = index.get("data_names"), index["by_path_suffix"] + db_files = index["db_files"] + fname = f.get("name", "") + path_field = f.get("path") or "" + # A directory is held when the collection holds files under it, the rule + # the pack and verify --emulator expand it by: a bare-name lookup missed + # cdogs' .wolf3d/, whose 695 files every pack carries. + if f.get("type") == "directory" and directory_members( + {"indexes": {"by_path_suffix": by_path_suffix}}, path_field or fname + ): + return "bios" + found = None + for candidate in [fname, *([path_field] if path_field != fname else []), + *(f.get("aliases") or [])]: + if not candidate: + continue + source = _resolve_source( + candidate, by_name, by_name_lower, data_names, by_path_suffix, f, db_files, + index.get("bios_dir"), + ) + if source == "bios": + return source + found = found or source + + def values(field: str) -> list[str]: + return parse_hash_list(f.get(field)) + + # The declared content anywhere in bios/ comes before a data/ copy, as in + # the resolver: the hash steps run before the data directories. + held = ( + any(index["by_md5"].get(v) for v in parse_md5_list(f.get("md5"))) + or any(v in db_files for v in values("sha1")) + # rust_dos names its SC-55 ROMs by sha256 alone + or any(v in index["by_sha256"] for v in values("sha256")) + or any(index["by_crc32"].get(v) for v in values("crc32")) + ) + return "bios" if held else found + + +def _resolve_archive_source( + archive_name: str, + by_name: dict[str, list], + by_name_lower: dict[str, str], + data_names: set[str] | None = None, + by_path_suffix: dict | None = None, +) -> str: + """Resolve source for an archive (ZIP) name, returning a source category string.""" + result = _resolve_source( + archive_name, by_name, by_name_lower, data_names, by_path_suffix, + ) + return result if result is not None else "missing" + + +def _first_hash(entry: dict) -> str: + """The first hash an entry declares, strongest first, or ''.""" + for field in ("sha1", "sha256", "md5", "crc32"): + value = entry.get(field) + if isinstance(value, list): + value = value[0] if value else "" + if value: + return f"{field}:{str(value).lower()}" + return "" + + +def slot_key(f: dict, standalone: bool = False) -> tuple: + """The slot a profile entry fills: its entries on one slot are the + versions its code accepts there, and holding any of them fills it. + + The path is the one the running build reads: b2's standalone build + reads MOS 3.20 and 3.50 from two directories, two slots, while the + entries share a name and no `path:`.""" + fname = f.get("name", "") + where = (f.get("standalone_path") if standalone else None) or f.get("path") + return ( + fname, + f.get("archive"), + system_dir_path(f, where or fname), + f.get("system"), + f.get("selection_slot"), + f.get("mode", "both"), + read_from_save_dir(f, standalone), + ) + + +# Why an entry is left out of the comparison, in the order they are printed. +SET_ASIDE = { + "other_versions": "other versions of a slot", + "not_read": "not read on this platform", + "outside_scope": "outside the pack", + "launcher": "filled by the platform's launcher", +} + + +def profile_breakdown(data: dict) -> str: + """Where each entry of a profile went, adding up to its file count. + + The heading said 261 files, 7 declared and 238 undeclared, and the 16 + others were nowhere: the versions a slot accepts, the entries the + platform never opens and the ones no pack carries. + """ + # A report built without the per-entry tally (a fixture, a saved --json + # of an earlier run) falls back to its row counts. + parts = [f"{data.get('declared_files', data['platform_covered'])} declared by platforms", + f"{data.get('undeclared_files', data['gaps'])} undeclared"] + unsourceable = data.get("unsourceable_files", len(data.get("unsourceable") or [])) + if unsourceable: + parts.append(f"{unsourceable} unsourceable") + aside = data.get("set_aside") or {} + detail = [f"{aside[key]} {label}" for key, label in SET_ASIDE.items() if aside.get(key)] + if detail: + parts.append(f"{sum(aside.values())} set aside ({', '.join(detail)})") + return ", ".join(parts) + + +def _effective_path(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: + # The destination the running build reads, as find_undeclared_files + # takes it: Batocera's standalone Cemu reads keys.txt at + # standalone_path, and the libretro Cemu/keys.txt reported here + # settled the declaration on a slot the platform never fills. + if is_standalone: + return f.get("standalone_path") or f.get("path") or fname + if save_root: + return f.get("path") or fname + return system_dir_path(f, f.get("path") or fname) + + +@dataclass +class _ProfileComparison: + """One profile's entries against the platforms' declarations.""" + + emu_name: str + profile: dict + index: dict + platform_names: set[str] + platform: str + layouts: list + versions: dict[tuple, list[dict]] = dataclasses.field(default_factory=dict) + position: dict[int, int] = dataclasses.field(default_factory=dict) + gaps: list[dict] = dataclasses.field(default_factory=list) + covered: list[dict] = dataclasses.field(default_factory=list) + unsourceable_list: list[dict] = dataclasses.field(default_factory=list) + archive_gaps: dict[tuple, dict] = dataclasses.field(default_factory=dict) + seen_files: set[tuple] = dataclasses.field(default_factory=set) + fates: dict[int, str] = dataclasses.field(default_factory=dict) + # Grouped entries met, as (set keys, entry, fills, the list holding + # its row, the row): settled once the profile is read. + set_records: list[tuple[tuple, dict, bool, list | None, dict | None]] = dataclasses.field( + default_factory=list + ) + archive_rows: list[dict] = dataclasses.field(default_factory=list) + + def fate(self, f: dict, what: str) -> None: + key = self.position[id(f)] + current = self.fates.get(key) + if current is None or (current in SET_ASIDE and what not in SET_ASIDE): + self.fates[key] = what + + def compare(self, f: dict, is_standalone: bool) -> None: + """File one entry of one build: declared, a gap, or set aside.""" + fname = f.get("name", "") + platform = self.platform + save_root = read_from_save_dir(f, is_standalone) + effective_path = _effective_path(f, fname, is_standalone, save_root) + slot = slot_key(f, is_standalone) + seen_key = slot + if len(self.layouts) > 1: + # One file read at one path by both builds counts once. + seen_key = (effective_path.casefold(), seen_key) + if not fname: + self.fate(f, "outside_scope") + return + if seen_key in self.seen_files: + self.fate(f, "other_versions") + return + if unread_on(f, platform): + self.fate(f, "not_read") + return + + # Collect unsourceable files separately (documented, not a gap) + unsourceable_reason = f.get("unsourceable", "") + keys = set_keys((self.emu_name, is_standalone), f) + if unsourceable_reason: + self.seen_files.add(seen_key) + self.fate(f, "unsourceable") + row = { + "name": fname, + "required": f.get("required", False), + "reason": unsourceable_reason, + "source_ref": f.get("source_ref", ""), + } + self.unsourceable_list.append(row) + self.set_records.append((keys, f, False, self.unsourceable_list, row)) + return + + if outside_gap_scope(f, is_standalone): + self.fate(f, "outside_scope") + return + + archive = f.get("archive") + + # Check platform declaration: by name, by an alias the core answers + # to (RetroArch lists amiberry's cd32.rom as kick40060.CD32), or by + # archive. + # A platform declares files of its BIOS tree: none answers for one + # the core reads below the save directory. + in_platform = not save_root and f.get("root") not in OUTER_ROOTS and declaration_settles( + f, fname, self.platform_names, effective_path, + self.index.get("folded_slots", frozenset()), + self.index.get("declared_contents"), + ) + + if in_platform: + self.seen_files.add(seen_key) + self.fate(f, "declared") + self.set_records.append((keys, f, True, None, None)) + self.covered.append({ + "name": fname, + "path": effective_path, + "required": f.get("required", False), + "in_platform": True, + }) + return + + self.seen_files.add(seen_key) + self.fate(f, "undeclared") + + if archive: + self._archive_gap(f, archive, is_standalone) + return + self._loose_gap(f, fname, is_standalone, save_root, effective_path, slot, keys) + + def _archive_gap(self, f: dict, archive: str, is_standalone: bool) -> None: + archive_key = ( + archive, + f.get("system"), + f.get("selection_slot"), + f.get("mode", "both"), + ) + if archive_key not in self.archive_gaps: + source = _resolve_archive_source( + archive, self.index["by_name"], self.index["by_name_lower"], + self.index["data_names"], self.index["by_path_suffix"], + ) + self.archive_gaps[archive_key] = { + "name": archive, + "path": archive, + "required": False, + "note": "", + "source_ref": "", + "in_platform": False, + "in_repo": source != "missing", + "source": source, + "archive": archive, + "archive_file_count": 0, + "archive_required_count": 0, + } + entry = self.archive_gaps[archive_key] + if entry["archive_file_count"] == 0: + # The archive's own declaration names its sets: an archive + # is a member like a loose file (Kronos' stvbios.zip). + own = archive_entry(archive, self.profile.get("files", [])) + self.set_records.append(( + set_keys((self.emu_name, is_standalone), own), own, + entry["in_repo"], self.archive_rows, entry, + )) + self.archive_rows.append(entry) + entry["archive_file_count"] += 1 + if f.get("required", False): + entry["archive_required_count"] += 1 + entry["required"] = True + if not entry["source_ref"] and f.get("source_ref"): + entry["source_ref"] = f["source_ref"] + + def _loose_gap( + self, f: dict, fname: str, is_standalone: bool, save_root: bool, + effective_path: str, slot: tuple, keys: tuple, + ) -> None: + emu_name = self.emu_name + platform = self.platform + # --- resolve source provenance --- + # A release asset is held when the database records it, as any other + # file: storage says where the bytes are served from, not that the + # collection has them (kenji-nx's user-picked firmware package). + source = next( + ( + found for version in self.versions[slot] + if (found := entry_source( + {**version, "source_profile": emu_name}, self.index, + )) is not None + ), + "missing", + ) + if source != "missing" and f.get("storage", "") in ("release", "large_file"): + source = "large_file" + + in_repo = source != "missing" + + entry = { + "name": fname, + "path": effective_path, + "required": f.get("required", False), + "bundled": installed_with_emulator(f, platform), + "note": f.get("note", ""), + "source_ref": f.get("source_ref", ""), + "in_platform": False, + "in_repo": in_repo, + "source": source, + # What tells this file from a homonym another emulator wants. + "identity": _first_hash(f), + } + if save_root: + entry["root"] = "save" + elif f.get("unplaced"): + entry["unplaced"] = f["unplaced"] + elif f.get("root") in OUTER_ROOTS: + entry["root"] = f["root"] + elif self.index.get("launcher_candidates") is not None: + # What verify hands the launcher layer for the same entry. + probe = { + **f, + "profile": emu_name, + "emulator": self.profile.get("emulator", emu_name), + "path": effective_path, + "in_repo": in_repo, + "bundled": entry["bundled"], + } + self.index["launcher_candidates"].append( + (emu_name, is_standalone, f, probe, entry) + ) + self.gaps.append(entry) + self.set_records.append((keys, f, in_repo, self.gaps, entry)) + + def settle(self) -> None: + # One need per set: a member another one fills is not a gap, and a set + # nobody holds is one gap under its first member (alternatives.py), as + # verify and the packs count it. + # Archive units rank first among equals, as the builder orders them. + grouped = sorted( + (r for r in self.set_records if r[0]), key=lambda r: r[3] is not self.archive_rows + ) + requirements = set_requirements(self.profile) + excused, standing = settle_sets( + [(keys, f, fills) for keys, f, fills, _l, _r in grouped], + lambda key: requirements.get(key[1], True), + ) + for at, (_keys, member, _fills, rows, set_row) in enumerate(grouped): + if set_row is None or rows is None: + continue + if at in standing: + set_row["alternatives"] = standing[at].others + set_row["required"] = standing[at].required + if at in excused: + rows.remove(set_row) + if id(member) in self.position: + self.fates[self.position[id(member)]] = "other_versions" + + for ag in sorted(self.archive_gaps.values(), key=lambda e: e["name"]): + if any(ag is row for row in self.archive_rows): + self.gaps.append(ag) + + def summary(self) -> dict: + tally = Counter(self.fates.values()) + profile = self.profile + return { + "emulator": profile.get("emulator", self.emu_name), + "systems": profile.get("systems", []), + "total_files": len(profile.get("files", [])), + "platform_covered": len(self.covered), + **_gap_counts(self.gaps), + "gap_details": self.gaps, + "unsourceable": self.unsourceable_list, + # Entries, not rows: an archive's members are one gap row. + "declared_files": tally["declared"], + "undeclared_files": tally["undeclared"], + "unsourceable_files": tally["unsourceable"], + "set_aside": {key: tally[key] for key in SET_ASIDE}, + } + + +def _cross_reference_profile( + emu_name: str, + profile: dict, + declared: dict[str, set[str]], + report: dict, + index: dict, + standalone_cores: set[str] | None = None, + platform: str = "", +) -> None: + """Compare one emulator profile against what the platforms declare. + + *platform* is the platform key under --platform, empty for the whole + tree. It decides, through the functions verify reads, which entries the + platform's launcher never opens and which ones its emulator package + already installs. + + Split out of cross_reference, where it was a 200-line loop body that + carried the whole function's branching: every file is resolved by name, + by path, by hash and by archive membership before it can be called a + gap. *index* carries the database lookups those steps share. + """ + all_declared = index["all_declared"] + systems = profile.get("systems", []) + + # Skip filename-agnostic profiles (BIOS detected without fixed names) + if profile.get("bios_mode") == "agnostic": + return + + if all_declared is not None: + platform_names = all_declared + else: + platform_names = set() + for sys_id in systems: + platform_names.update(declared.get(_norm_system_id(sys_id), set())) + + # The build a platform runs decides which entries it reads, as in + # find_undeclared_files: without a platform, the libretro build. + layouts = platform_layouts(emu_name, profile, standalone_cores or set()) + comparison = _ProfileComparison(emu_name, profile, index, platform_names, platform, layouts) + # Each file under each layout the platform gives the emulator: both, for + # one it launches as a libretro core and standalone. + layout_files = [(f, standalone) for view, standalone in layouts for f in view.get("files", [])] + + # The entries of one profile on one slot are the versions its code + # accepts there (raze's ten DUKE3D.GRP): holding any of them fills the + # slot, as verify --emulator credits it. + for f, is_standalone in layout_files: + comparison.versions.setdefault(slot_key(f, is_standalone), []).append(f) + + # What became of each entry, so the heading adds up: a file a platform + # declares, one it does not, or one set aside and why. An entry read by + # two builds keeps the first answer that compares it. Each layout lists + # the profile's entries in their order, so a position names one entry. + comparison.position = { + id(f): i for view, _ in layouts for i, f in enumerate(view.get("files", [])) + } + + for f, is_standalone in layout_files: + comparison.compare(f, is_standalone) + comparison.settle() + report[emu_name] = comparison.summary() + + +def _gap_counts(gaps: list[dict]) -> dict[str, int]: + """The per-source tallies of a profile's gap rows.""" + return { + "gaps": len(gaps), + "gap_in_repo": sum(1 for g in gaps if g["in_repo"]), + "gap_missing": sum(1 for g in gaps if g["source"] == "missing"), + "gap_bios": sum(1 for g in gaps if g["source"] == "bios"), + "gap_data": sum(1 for g in gaps if g["source"] == "data"), + "gap_large_file": sum(1 for g in gaps if g["source"] == "large_file"), + } + + +def _settle_launcher_places( + report: dict, + candidates: list[tuple[str, bool, dict, dict, dict]], + layer: LauncherLayer, + db: dict, +) -> None: + """Apply the platform's launcher places as find_undeclared_files does. + + Batocera's DuckStation generator fills the PAL slot with scph5502.bin, + yet the report listed duckstation's scph1002a.bin as a file the pack + carries, which neither the pack nor the manifest does. + """ + added, settled = layer.settle( + [(emu, standalone, f, probe) for emu, standalone, f, probe, _ in candidates], + lambda probe: held_record(probe, db), + ) + for emu, _standalone, _f, probe, gap in candidates: + if id(probe) not in settled: + continue + data = report[emu] + data["gap_details"] = [g for g in data["gap_details"] if g is not gap] + data["undeclared_files"] -= 1 + data["set_aside"]["launcher"] += 1 + for entry in added: + data = report[entry["profile"]] + data["gap_details"].append({ + "name": entry["name"], + "path": entry["path"], + "required": entry.get("required", False), + "bundled": False, + "note": "", + "source_ref": "", + "in_platform": False, + "in_repo": True, + "source": "bios", + "identity": entry.get("sha1") or "", + "launcher": entry["launcher"], + "launcher_of": entry["launcher_of"], + }) + for data in report.values(): + data.update(_gap_counts(data["gap_details"])) + + +# A package record names no file: it records what a package builds. +_NAMELESS_KINDS = frozenset({"package"}) + +# The folder of the platform's own launcher, as its scraper spells it: a +# program the launcher runs from there (RetroBat's xbox-iso-vfs.exe) is part +# of the platform, never a file to collect. +PLATFORM_OWN_FOLDERS = frozenset({""}) + + +def launcher_file_names(record: dict) -> list[str]: + """The concrete file names a launcher record reads, in code order. + + The names are read as the launcher layer reads them (`launchers._names`): + a label after the name is dropped ("neocd_z.rom (CDZ)"), and a name with + `<` or without an extension is not a file name (a folder the record + links, an option value such as hatari2014's "default"). A name with a + `{X}` placeholder is a template: Batocera's hatari tries tos{L}.img for + every language and ROCKNIX links one memory card per slot and region, + so its expansions say which variants the code accepts, not which file is + owed. A wildcard is a pattern the emulator matches. `search_dir` is a + folder and never a name, whatever the kind. + """ + if record.get("kind") in _NAMELESS_KINDS: + return [] + return [ + name for name in launcher_names({**record, "expands": {}}) if "*" not in name + ] + + +def _profile_names(profiles: dict[str, dict]) -> tuple[dict[str, list[dict]], dict[str, list[dict]]]: + """Profile entries by each name and alias they answer to, exact and folded.""" + exact: dict[str, list[dict]] = {} + folded: dict[str, list[dict]] = {} + for profile in profiles.values(): + if profile.get("type") in ("launcher", "alias"): + continue + for entry in profile.get("files") or []: + names = {str(entry.get("name") or "")} | {str(a) for a in entry.get("aliases") or []} + for name in names - {""}: + base = name.rsplit("/", 1)[-1] + exact.setdefault(base, []).append(entry) + folded.setdefault(base.casefold(), []).append(entry) + return exact, folded + + +class _NameHolder: + """Whether the collection holds a file under a launcher name. + + A name is held when database.json carries a file under it or under an + alias it indexes, when a profile entry that answers to the name (as its + name or an alias) resolves, or when resolve_local_file finds it in a data + directory. The database answers for files kept as release assets, absent + from a checkout. A copy known only under another casing is returned + apart: a launcher that matches names exactly does not open it. + """ + + def __init__( + self, db: dict, profiles: dict[str, dict], data_dir_registry: dict | None + ) -> None: + self.db = db + self.registry = data_dir_registry + files = db.get("files", {}) + self.by_name = { + name: sha1s + for name, sha1s in db.get("indexes", {}).get("by_name", {}).items() + if any(sha1 in files for sha1 in sha1s) + } + self.by_name_folded: dict[str, list[str]] = {} + for name in self.by_name: + self.by_name_folded.setdefault(name.casefold(), []).append(name) + self.exact, self.folded = _profile_names(profiles) + self._cache: dict[str, tuple[str, bool] | None] = {} + + def _entry_held(self, entry: dict) -> bool: + names = [str(entry.get("name") or "")] + [str(a) for a in entry.get("aliases") or []] + if any(n.rsplit("/", 1)[-1] in self.by_name for n in names if n): + return True + path, _status = resolve_local_file(entry, self.db, data_dir_registry=self.registry) + return path is not None + + def held(self, name: str) -> tuple[str, bool] | None: + """The name the collection holds *name* under, and whether its casing is exact.""" + if name in self._cache: + return self._cache[name] + base = name.rsplit("/", 1)[-1] + found: tuple[str, bool] | None = None + stem = suffixed_stem(base) + if base in self.by_name or any(map(self._entry_held, self.exact.get(base, []))) or stem is not None and any(map(self._entry_held, self.exact.get(stem, []))): + found = (base, True) + else: + path, _status = resolve_local_file( + {"name": name}, self.db, data_dir_registry=self.registry + ) + if path is not None: + found = (Path(path).name, Path(path).name == base) + elif base.casefold() in self.by_name_folded: + found = (self.by_name_folded[base.casefold()][0], False) + else: + entry = next( + (e for e in self.folded.get(base.casefold(), []) if self._entry_held(e)), + None, + ) + if entry is not None: + found = (str(entry.get("name") or ""), False) + self._cache[name] = found + return found + + +def _held_by_setting( + name: str, + settings: dict, + readers: list[str], + profiles: dict[str, dict], + holder: _NameHolder, + db: dict, +) -> bool: + """Whether the setting the name is written to reads a held file. + + A placeholder read from the setting takes the held dump the + catalogues name after the model the launcher's name spells. + """ + entries = [ + entry + for key in readers + for entry in profiles[key].get("files") or [] + if settings[name] and set_by(entry, settings[name]) + ] + return any(holder._entry_held(entry) for entry in entries) or any( + "<" in str(entry.get("name", "")) + and any( + name_match_size_ok(entry, found.get("size")) + for found in catalogued_model_files(name, db) + ) + for entry in entries + ) + + +def _unsourceable_names(readers: list[str], profiles: dict[str, dict]) -> dict[str, str]: + return { + str(n).rsplit("/", 1)[-1]: str(entry["unsourceable"]) + for key in readers + for entry in profiles[key].get("files") or [] + if entry.get("unsourceable") + for n in (entry.get("name"), *(entry.get("aliases") or [])) + if n + } + + +def _add_name_row( + by_key: dict[str, dict], + platform: str, + name: str, + found: tuple[str, bool] | None, + folds: bool, + reader: dict, + unsourceable: dict[str, str], +) -> None: + """Add a launcher record to the row of a name the collection lacks.""" + key = name.casefold() if folds else name + row = by_key.get(key) + if row is None: + row = by_key[key] = { + "platform": platform, + "name": name, + "emulators": [], + "readers": [], + } + if found: + row["held_as"] = found[0] + reason = unsourceable.get(name.rsplit("/", 1)[-1]) + if reason and "unsourceable" not in row: + row["unsourceable"] = reason + if reader["emulator"] not in row["emulators"]: + row["emulators"].append(reader["emulator"]) + if reader not in row["readers"]: + row["readers"].append(reader) + + +def launcher_reads_not_held( + configs: dict[str, dict], + db: dict, + profiles: dict[str, dict], + data_dir_registry: dict | None = None, + emulator: str = "", +) -> list[dict]: + """The file names a platform's launch code reads that the collection lacks. + + One row per platform and name, with every record that reads it. A + launcher that matches case-insensitively, or runs on a filesystem that + folds case, is satisfied by a copy under another casing. Elsewhere such + a copy is reported with `held_as`, since the launcher does not open it + under the name it asks for. *emulator* keeps the records whose emulator + name designates that profile. + + Three records ask for nothing the collection lacks. A search keeps the + first name it finds, so one held name fills it: RetroBat's Amiberry + launcher returns the first of kick34005.A500, kick34005.A500.rom and + amiga-os-130.rom that exists (Amiberry.Generator.cs:674-699). A copy + whose source lies outside the BIOS directory brings a file the platform + installs itself, from its own package or written by its own script + (RetroPie's lr-vecx copies $md_inst/system.bin), and so does a program + the launcher runs from its own folder. A file handed to the + setting a reader's profile entry is read from is that entry's file, + which the pack places under the launcher's name. + """ + holder = _NameHolder(db, profiles, data_dir_registry) + every_profile = set(profiles) + rows: list[dict] = [] + for platform, config in configs.items(): + by_key: dict[str, dict] = {} + # A record resting on a config file it cannot prove reads nothing + # yet: it is reported apart (launcher_unproven). + for record in bound_launchers(config, profiles): + names = launcher_file_names(record) + if not names: + continue + readers = sorted({ + key + for part in str(record.get("emulator", "")).split(",") + for key in LauncherLayer._profiles_named(part.strip(), profiles, every_profile) + }) + if not readers: + # RetroDECK names its frontend and the core option names the core. + readers = setting_readers( + str(record.get("passes_to") or ""), profiles, every_profile + ) + if emulator and emulator not in readers: + continue + folds = bool(record.get("case_insensitive") or config.get("case_insensitive_fs")) + base = str(config.get("base_destination") or "bios") + if record.get("kind") == "copies" and not launcher_directories(record, base): + continue + if str(record.get("search_dir") or "") in PLATFORM_OWN_FOLDERS: + continue + settings = name_settings(record, names) + by_model = { + name for name in names + if _held_by_setting(name, settings, readers, profiles, holder, db) + } + if record.get("kind") == "names_searched" and any( + (found := holder.held(name)) and (found[1] or folds) for name in names + ): + continue + reader = { + "emulator": str(record.get("emulator", "")), + "build": str(record.get("build", "")), + "kind": str(record.get("kind", "")), + "source_ref": str(record.get("source_ref", "")), + "profiles": readers, + } + # A name a reader's entry declares unsourceable is no gap: its + # row carries the reason and is counted apart. + unsourceable = _unsourceable_names(readers, profiles) + for name in names: + found = holder.held(name) + if found and (found[1] or folds) or name in by_model: + continue + _add_name_row(by_key, platform, name, found, folds, reader, unsourceable) + rows.extend(by_key[key] for key in sorted(by_key, key=str.casefold)) + return rows + + +class ReportScope(TypedDict, total=False): + """What a cross_reference run compares against and answers for.""" + + all_declared: dict[str, list[tuple[int | None, str]]] | None + standalone_cores: set[str] | None + folded_slots: frozenset[str] + platform: str + launcher_layer: LauncherLayer | None + declared_contents: dict[str, set[str]] | None + + +def cross_reference( + profiles: dict[str, dict], + declared: dict[str, set[str]], + db: dict, + platform_data_dirs: dict[str, set[str]] | None = None, + data_names: set[str] | None = None, + **scope: Unpack[ReportScope], +) -> dict: + """Compare emulator profiles against platform declarations. + + Returns a report with gaps (files emulators need but platforms don't list) + and coverage stats. Each gap entry carries a ``source`` field indicating + where the file is available: ``"bios"`` (bios/ via database.json), + ``"data"`` (data/ directory), ``"large_file"`` (GitHub release asset), + or ``"missing"`` (not available anywhere). + + The boolean ``in_repo`` is derived: ``source != "missing"``. + + When *all_declared* is provided (every filename declared by any platform + for any system, with its sizes and slots), it is used for the ``in_platform`` check + instead of the per-system lookup. This is appropriate for the global + gap analysis page where "undeclared" means "no platform declares it at all". + """ + unknown = sorted(set(scope) - set(ReportScope.__annotations__)) + if unknown: + raise TypeError(f"cross_reference() got an unexpected keyword argument '{unknown[0]}'") + all_declared = scope.get("all_declared") + standalone_cores = scope.get("standalone_cores") + folded_slots = scope.get("folded_slots", frozenset()) + platform = scope.get("platform", "") + launcher_layer = scope.get("launcher_layer") + declared_contents = scope.get("declared_contents") + platform_data_dirs = platform_data_dirs or {} + by_name = db.get("indexes", {}).get("by_name", {}) + by_name_lower = {k.lower(): k for k in by_name} + by_md5 = db.get("indexes", {}).get("by_md5", {}) + by_crc32 = db.get("indexes", {}).get("by_crc32", {}) + by_sha256 = db.get("indexes", {}).get("by_sha256", {}) + by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {}) + db_files = db.get("files", {}) + report: dict[str, dict] = {} + + index = { + "by_name": by_name, + "by_name_lower": by_name_lower, + "by_md5": by_md5, + "by_crc32": by_crc32, + "by_sha256": by_sha256, + "by_path_suffix": by_path_suffix, + "db_files": db_files, + "data_names": data_names, + "all_declared": all_declared, + "folded_slots": folded_slots, + "declared_contents": declared_contents, + "bios_dir": db.get("bios_dir"), + "launcher_candidates": [] if launcher_layer else None, + } + for emu_name, profile in profiles.items(): + _cross_reference_profile( + emu_name, profile, declared, report, index, standalone_cores, + platform, + ) + if launcher_layer: + _settle_launcher_places(report, index["launcher_candidates"], launcher_layer, db) + + return report diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py new file mode 100644 index 000000000..01945b454 --- /dev/null +++ b/scripts/packs/datadirs.py @@ -0,0 +1,646 @@ +"""The cached data directories: the lock readers hold on them, and their refresh from upstream.""" + +from __future__ import annotations + +import contextlib +import json +import logging +import os +import shutil +import tarfile +import tempfile +import time +import urllib.request +import zipfile +from collections.abc import Callable, Iterator +from pathlib import Path + +try: + import yaml +except ImportError: + yaml = None + +from core.artifacts import file_lock as _file_lock, set_plain_mode +from core.cli import InputMissing +from core.github import github_token +from model.safeparse import yaml_load + + +log = logging.getLogger(__name__) + +DEFAULT_REGISTRY = "platforms/_data_dirs.yml" +VERSIONS_FILE = "data/.versions.json" +USER_AGENT = "retrobios/1.0" +REQUEST_TIMEOUT = 30 +DOWNLOAD_TIMEOUT = 300 +# A mirror sometimes answers with a page that is not the archive: the +# buildbot's ScummVM.zip failed CI once as "File is not a zip file" and +# downloaded fine minutes later. Seconds to wait before each retry. +DOWNLOAD_RETRY_WAITS = (5, 20) +_TRANSIENT = (urllib.error.URLError, OSError, tarfile.TarError, zipfile.BadZipFile, EOFError) + + +def load_registry(registry_path: str = DEFAULT_REGISTRY) -> dict[str, dict]: + if yaml is None: + raise ImportError("PyYAML required: pip install pyyaml") + path = Path(registry_path) + if not path.exists(): + raise InputMissing(f"Registry not found: {registry_path}") + with open(path) as f: + data = yaml_load(f) or {} + return data.get("data_directories", {}) + + +def cache_lock( + cache_dir: str | Path, shared: bool = False +) -> contextlib.AbstractContextManager[None]: + """The lock a refresh holds while it swaps cache_dir. + + A reader takes it shared: a pack walking data/sdlpal while another run + swapped the tree shipped part of it, or nothing. + """ + cache_dir = Path(cache_dir) + return _announced_lock(cache_dir.with_name(f".{cache_dir.name}.lock"), shared, cache_dir) + + +def _wait_message(lock_path: Path, shared: bool, cache_dir: Path) -> str: + """Who to wait for, and, for a refresh, how not to. + + The bare "another run holds it" named neither the lock nor its holder, + and the build waited with no limit. + """ + message = ( + f"waiting for {cache_dir}: another run holds {lock_path} " + f"(lsof {lock_path} names it)" + ) + if not shared: + message += ( + ". generate_pack.py --no-refresh-data, or --offline there and in" + " pipeline.py, builds from the cache as it is without waiting" + ) + return message + + +@contextlib.contextmanager +def _announced_lock(lock_path: Path, shared: bool, cache_dir: Path) -> Iterator[None]: + """file_lock, saying so when it has to wait. + + A pipeline holds every cache for its whole run: a refresh started beside + it waited hours with nothing on screen. + """ + try: + import fcntl + except ImportError: + with _file_lock(lock_path, shared=shared): + yield + return + lock_path.parent.mkdir(parents=True, exist_ok=True) + mode = fcntl.LOCK_SH if shared else fcntl.LOCK_EX + with open(lock_path, "a") as handle: + try: + fcntl.flock(handle, mode | fcntl.LOCK_NB) + except BlockingIOError: + log.warning(_wait_message(lock_path, shared, cache_dir)) + fcntl.flock(handle, mode) + try: + yield + finally: + fcntl.flock(handle, fcntl.LOCK_UN) + + +def hold_data_dirs(stack: contextlib.ExitStack, registry: dict) -> None: + """Hold every cached data directory shared for the life of *stack*. + + A pack resolves names against a tree, then copies the file minutes + later. A refresh swapping the tree in between shipped bytes nobody + verified, or died on a file the new tree no longer has. A refresh waits + for the holders. Never called before a refresh in the same process: + the exclusive lock would wait on this one. A cache not yet on disk is + held too: the lock sits beside the tree, and skipped, a refresh could + install the tree after verify ran and before the packs read it. + """ + for entry in registry.values(): + cache = entry.get("local_cache", "") + if cache: + stack.enter_context(cache_lock(cache, shared=True)) + + +def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]: + path = Path(versions_path) + if not path.exists(): + return {} + with open(path) as f: + return json.load(f) + + +def _save_versions( + versions: dict[str, dict], versions_path: str = VERSIONS_FILE +) -> None: + """Write the version file whole or not at all. + + Truncating in place let a concurrent reader load an empty file and die + on JSONDecodeError. The scratch file sits beside the target so the + rename stays on one filesystem. + """ + path = Path(versions_path) + path.parent.mkdir(parents=True, exist_ok=True) + handle, scratch = tempfile.mkstemp( + dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" + ) + try: + with os.fdopen(handle, "w") as f: + json.dump(versions, f, indent=2, sort_keys=True) + f.write("\n") + set_plain_mode(scratch) + os.replace(scratch, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(scratch) + raise + + +def _record_version(key: str, record: dict, versions_path: str) -> None: + """Set one key under the file lock, so two writers keep both updates.""" + path = Path(versions_path) + with _file_lock(path.with_name(f".{path.name}.lock")): + versions = _load_versions(versions_path) + versions[key] = record + _save_versions(versions, versions_path) + + +def _staging_dir(cache_dir: Path) -> tempfile.TemporaryDirectory: + """Scratch space beside the cache, on its filesystem. + + /tmp is a 4 GB tmpfs here: staging there filled it and turned the + promotion into a copy, during which the cache held a partial tree. + """ + cache_dir.parent.mkdir(parents=True, exist_ok=True) + return tempfile.TemporaryDirectory( + dir=cache_dir.parent, prefix=f".{cache_dir.name}-" + ) + + +def _promote(extract_dir: Path, cache_dir: Path, scratch: Path) -> None: + """Swap the new tree in by renames alone. + + The old tree steps aside into the run's own scratch directory, never a + fixed sibling name another run could be using, and comes back if the + new one cannot be moved in. + """ + previous = scratch / "previous" + if cache_dir.exists(): + os.replace(cache_dir, previous) + try: + os.replace(extract_dir, cache_dir) + except BaseException: + if previous.exists() and not cache_dir.exists(): + os.replace(previous, cache_dir) + raise + + +def _api_request(url: str) -> dict: + req = urllib.request.Request( + url, + headers={ + "User-Agent": USER_AGENT, + "Accept": "application/json", + }, + ) + token = github_token() + if token and "github" in url: + req.add_header("Authorization", f"token {token}") + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: + return json.loads(resp.read()) + + +def _parse_repo_from_url(source_url: str) -> tuple[str, str, str]: + """Extract (host_type, owner, repo) from a tarball URL. + + Returns host_type as 'github' or 'gitlab'. + """ + if "github.com" in source_url: + # https://github.com/owner/repo/archive/{version}.tar.gz + parts = source_url.split("github.com/")[1].split("/") + return "github", parts[0], parts[1] + if "gitlab.com" in source_url: + parts = source_url.split("gitlab.com/")[1].split("/") + return "gitlab", parts[0], parts[1] + raise ValueError(f"Unsupported host in URL: {source_url}") + + +def get_remote_sha(source_url: str, version: str) -> str | None: + """Fetch the current commit SHA for a branch/tag from GitHub or GitLab.""" + try: + host_type, owner, repo = _parse_repo_from_url(source_url) + except ValueError: + log.warning("cannot parse repo from URL: %s", source_url) + return None + + try: + if host_type == "github": + url = f"https://api.github.com/repos/{owner}/{repo}/commits/{version}" + data = _api_request(url) + return data["sha"] + else: + encoded = f"{owner}%2F{repo}" + url = f"https://gitlab.com/api/v4/projects/{encoded}/repository/branches/{version}" + data = _api_request(url) + return data["commit"]["id"] + except (urllib.error.URLError, KeyError, OSError) as exc: + log.warning( + "failed to fetch remote SHA for %s/%s@%s: %s", owner, repo, version, exc + ) + return None + + +class NothingExtractedError(Exception): + """An archive that yields no file for the cache. + + Promoting it replaced the cache with an empty directory, recorded the new + version and reported success, so the next run read "up to date" and the + packs left without the directory. + """ + + +def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool: + """Reject path traversal, absolute paths, and symlinks in tar members.""" + if member.issym() or member.islnk(): + return False + if member.name.startswith("/") or ".." in member.name.split("/"): + return False + resolved = (dest / member.name).resolve() + dest_str = str(dest.resolve()) + os.sep + return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve()) + + +def _download_and_extract( + source_url: str, + source_path: str, + local_cache: str, + exclude: list[str] | None = None, + measured: Callable[[int], None] | None = None, +) -> int: + """Download tarball, extract source_path subtree to local_cache. + + Returns the number of files extracted. measured receives the size of + the archive downloaded. + """ + exclude = exclude or [] + cache_dir = Path(local_cache) + + with _staging_dir(cache_dir) as tmpdir: + tarball_path = Path(tmpdir) / "archive.tar.gz" + log.info("downloading %s", source_url) + + req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(tarball_path, "wb") as f: + while True: + chunk = resp.read(65536) + if not chunk: + break + f.write(chunk) + if measured is not None: + measured(tarball_path.stat().st_size) + + log.info("extracting %s -> %s", source_path, local_cache) + + prefix = source_path.rstrip("/") + "/" + file_count = 0 + + with tarfile.open(tarball_path, "r:gz") as tf: + extract_dir = Path(tmpdir) / "extract" + extract_dir.mkdir() + + for member in tf.getmembers(): + if not member.name.startswith(prefix) and member.name != source_path: + continue + + rel = member.name[len(prefix) :] + if not rel: + continue + + # skip excluded subdirectories + top_component = rel.split("/")[0] + if top_component in exclude: + continue + + if not _is_safe_tar_member(member, extract_dir): + log.warning("skipping unsafe tar member: %s", member.name) + continue + + # rewrite member name to relative path + member_copy = tarfile.TarInfo(name=rel) + member_copy.size = member.size + member_copy.mode = member.mode + member_copy.type = member.type + + if member.isdir(): + (extract_dir / rel).mkdir(parents=True, exist_ok=True) + elif member.isfile(): + dest_file = extract_dir / rel + dest_file.parent.mkdir(parents=True, exist_ok=True) + src = tf.extractfile(member) + if src is None: + continue + with src, open(dest_file, "wb") as dst: + shutil.copyfileobj(src, dst) + file_count += 1 + + if not file_count: + raise NothingExtractedError(f"no file under {source_path} in the archive") + _promote(extract_dir, cache_dir, Path(tmpdir)) + + return file_count + + +def _download_and_extract_zip( + source_url: str, + local_cache: str, + exclude: list[str] | None = None, + strip_components: int = 0, + measured: Callable[[int], None] | None = None, +) -> int: + """Download ZIP, extract to local_cache. Returns file count. + + strip_components removes N leading path components from each entry + (like tar --strip-components). Useful when a ZIP has a single root + directory that should be flattened. + """ + exclude = exclude or [] + cache_dir = Path(local_cache) + + with _staging_dir(cache_dir) as tmpdir: + zip_path = Path(tmpdir) / "archive.zip" + log.info("downloading %s", source_url) + + req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(zip_path, "wb") as f: + while True: + chunk = resp.read(65536) + if not chunk: + break + f.write(chunk) + if measured is not None: + measured(zip_path.stat().st_size) + + extract_dir = Path(tmpdir) / "extract" + extract_dir.mkdir() + file_count = 0 + + with zipfile.ZipFile(zip_path) as zf: + for info in zf.infolist(): + if info.is_dir(): + continue + name = info.filename + if ".." in name or name.startswith("/"): + continue + # strip leading path components + parts = name.split("/") + if strip_components > 0: + if len(parts) <= strip_components: + continue + parts = parts[strip_components:] + name = "/".join(parts) + # skip excludes (check against stripped path) + top = parts[0] if parts else "" + if top in exclude: + continue + dest = extract_dir / name + dest.parent.mkdir(parents=True, exist_ok=True) + with zf.open(info) as src, open(dest, "wb") as dst: + shutil.copyfileobj(src, dst) + file_count += 1 + + if not file_count: + raise NothingExtractedError("the archive holds no file to extract") + # The old tree is stepped aside rather than deleted: removing it + # first and then failing to move the new one in left the cache with + # nothing at all, and the next run reads that as "never fetched". + _promote(extract_dir, cache_dir, Path(tmpdir)) + + return file_count + + +def _measure_archive(source_url: str) -> int | None: + """The size of the archive at source_url, read by streaming it: a + tarball GitHub builds on request is sent without a Content-Length.""" + req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) + size = 0 + try: + with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp: + while chunk := resp.read(65536): + size += len(chunk) + except _TRANSIENT as exc: + log.warning("could not measure %s: %s", source_url, exc) + return None + return size or None + + +def _record_archive_size(key: str, entry: dict, versions_path: str) -> None: + """Record the archive size of a tree current since before it was kept. + + The installer announces a tree's download as that size: a tarball + whose tree is 10 KB is a download of 21 MB. Measured, not refetched, + so the tree the packs carry stays the one recorded. + """ + path = Path(versions_path) + with _file_lock(path.with_name(f".{path.name}.lock")): + versions = _load_versions(versions_path) + record = versions.get(key) + if record is None or "archive_size" in record: + return + version = entry.get("version", "master") + size = _measure_archive(entry["source_url"].format(version=version)) + if size is None: + return + with _file_lock(path.with_name(f".{path.name}.lock")): + versions = _load_versions(versions_path) + if key in versions and "archive_size" not in versions[key]: + versions[key]["archive_size"] = size + _save_versions(versions, versions_path) + log.info("[%s] archive size recorded: %d bytes", key, size) + + +def _get_remote_etag(source_url: str) -> str | None: + """HEAD request to get ETag or Last-Modified for freshness check.""" + try: + req = urllib.request.Request( + source_url, method="HEAD", headers={"User-Agent": USER_AGENT} + ) + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: + return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "" + except (urllib.error.URLError, OSError): + return None + + +def _short_tag(tag: str | None) -> str: + """A commit sha or ETag cut for a log line, quotes dropped first: a + quoted ETag cut at 12 characters kept its opening quote only.""" + if not tag: + return "none" + return tag.strip().removeprefix("W/").strip('"')[:12] or "none" + + +def refresh_entry( + key: str, + entry: dict, + *, + force: bool = False, + dry_run: bool = False, + versions_path: str = VERSIONS_FILE, +) -> bool | None: + """Refresh a single data directory entry. + + Returns True if the entry was refreshed (or would be in dry-run mode). + The decision and the swap run under one lock per directory: a run that + waited for another session re-reads the version it recorded and finds + nothing left to do. + + The exclusive lock waits for every reader, and a pipeline reads the + trees for its whole run: a second build sat on "waiting" for a tree the + remote check would have found current. The check is made first without + it, and only a tree to replace waits. + """ + if dry_run: + return _refresh_entry(key, entry, force, dry_run, versions_path) + if not force: + needs, _remote, cached_tag = _decide(key, entry, False, versions_path) + if needs is None: + return None + if not needs: + log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag)) + _record_archive_size(key, entry, versions_path) + return False + with cache_lock(entry["local_cache"]): + return _refresh_entry(key, entry, force, dry_run, versions_path) + + +def _decide( + key: str, entry: dict, force: bool, versions_path: str +) -> tuple[bool | None, str | None, str | None]: + """(whether the tree needs a refresh, the remote tag read, the recorded + tag). None when the remote could not be read.""" + version = entry.get("version", "master") + cached = _load_versions(versions_path).get(key, {}) + cached_tag = cached.get("sha") or cached.get("etag") + if force or not Path(entry["local_cache"]).exists(): + return True, None, cached_tag + if entry.get("source_type", "tarball") == "zip": + remote_tag = _get_remote_etag(entry["source_url"].format(version=version)) + else: + remote_tag = get_remote_sha(entry["source_url"], version) + if remote_tag is None: + log.warning("[%s] could not check remote, skipping", key) + return None, None, cached_tag + return remote_tag != cached_tag, remote_tag, cached_tag + + +def _refresh_entry( + key: str, entry: dict, force: bool, dry_run: bool, versions_path: str +) -> bool | None: + source_type = entry.get("source_type", "tarball") + version = entry.get("version", "master") + source_url = entry["source_url"].format(version=version) + local_cache = entry["local_cache"] + exclude = entry.get("exclude", []) + + needs_refresh, remote_tag, cached_tag = _decide(key, entry, force, versions_path) + if needs_refresh is None: + return None + if not needs_refresh: + log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag)) + return False + + if dry_run: + if remote_tag is not None: + reason = f"cached: {_short_tag(cached_tag)}, remote: {_short_tag(remote_tag)}" + elif force: + reason = "forced" + else: + reason = "not cached" + log.info("[%s] would refresh (type: %s, %s)", key, source_type, reason) + return True + + if remote_tag is None: + # Read before the download. A release published in between then + # leaves an older tag on newer content, which the next run refreshes. + # Read after, it left a newer tag on older content, trusted for good. + if source_type == "zip": + remote_tag = _get_remote_etag(source_url) + else: + remote_tag = get_remote_sha(entry["source_url"], version) + + archive_sizes: list[int] = [] + + def fetch() -> int: + archive_sizes.clear() + if source_type == "zip": + return _download_and_extract_zip( + source_url, local_cache, exclude, entry.get("strip_components", 0), + measured=archive_sizes.append, + ) + source_path = entry["source_path"].format(version=version) + return _download_and_extract( + source_url, source_path, local_cache, exclude, measured=archive_sizes.append + ) + + # An archive that reads but holds nothing under the path is the same on + # every try: only a failed or unreadable download is tried again. + for attempt, wait in enumerate((*DOWNLOAD_RETRY_WAITS, None), start=1): + try: + file_count = fetch() + break + except NothingExtractedError as exc: + log.warning("[%s] download failed: %s", key, exc) + return None + except _TRANSIENT as exc: + if wait is None: + log.warning("[%s] download failed after %d tries: %s", key, attempt, exc) + return None + log.warning("[%s] download failed (%s), trying again in %d s", key, exc, wait) + time.sleep(wait) + + record = {"sha": remote_tag or "", "version": version} + if archive_sizes: + record["archive_size"] = archive_sizes[-1] + _record_version(key, record, versions_path) + + log.info("[%s] refreshed: %d files extracted to %s", key, file_count, local_cache) + return True + + +def refresh_all( + registry: dict[str, dict], + *, + force: bool = False, + dry_run: bool = False, + versions_path: str = VERSIONS_FILE, + platform: str | None = None, +) -> dict[str, bool | None]: + """Refresh all entries in the registry. + + If platform is set, only refresh entries whose for_platforms + includes that platform (or entries with no for_platforms restriction). + Returns a dict mapping key -> True when refreshed, False when already up + to date, None when the refresh failed. A single boolean conflated the last + two, so a run that reached no remote at all exited 0 like a run with + nothing to do. + """ + results = {} + for key, entry in registry.items(): + allowed = entry.get("for_platforms") + if platform and allowed and platform not in allowed: + continue + results[key] = refresh_entry( + key, + entry, + force=force, + dry_run=dry_run, + versions_path=versions_path, + ) + if any(results.values()): + # A cache the resolver indexed in this process has changed under it. + from resolve.datadirs import forget_data_dir_index + + forget_data_dir_index() + return results diff --git a/scripts/packs/datatrees.py b/scripts/packs/datatrees.py new file mode 100644 index 000000000..753ff8bcd --- /dev/null +++ b/scripts/packs/datatrees.py @@ -0,0 +1,400 @@ +"""The data directory trees a pack carries, and the cores that read them.""" + +from __future__ import annotations + +import json +import os +import zipfile +from collections.abc import Iterable, Iterator +from pathlib import Path +from typing import TYPE_CHECKING, TypedDict + +from core.hashing import compute_hashes +from model.declarations import declared_root +from model.profiles import entry_system_ids, installed_data_refs +from model.systems import _norm_system_id +from packs.archive import PackRecord, _add_pack_member, _reject_unknown +from packs.datadirs import cache_lock +from packs.extras import prefixed_destination +from packs.paths import MEDIA_MARKER, _has_path_conflict, _register_path, lands_on_android +from resolve.cores import resolve_platform_cores as _platform_cores +from resolve.layout import core_system_dirs +from resolve.standalone import platform_layouts, standalone_set +from resolve.validation import deliverable, read_from_system_dir + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def pack_markers( + platform_name: str, target_name: str | None, platforms_dir: str +) -> 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 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 () + + +def core_data_trees( + config: dict, + profiles: dict[str, dict], + platform_name: str, + data_registry: dict | None, + target_cores: set[str] | None = None, +) -> list[dict]: + """The data directories the platform's cores read, as tree references. + + A profile's ``data_directories`` reach the pack of every platform that + runs the core as a libretro core, below the system directory it hands + the core (and the build's own folder, ``pack_structure``), as the + emulator pack lays them out. Left out: a tree the platform's package + installs, for this core or another reading the same tree + (``installed_data_refs``), one the build bundles or the platform never + opens (``deliverable``), and one whose registry entry names the + platforms it serves (``for_platforms``) without this one. A standalone build reads its data below its own folder, which a + tree's destination does not describe, so its trees stay out, as does a + tree read beside the content (``load_from``). + + Each reference carries the profile's systems (``source_systems``, as a + core extra does), which --system and --split narrow on. + """ + if not data_registry: + return [] + installed = installed_data_refs(platform_name) + handed = standalone_set(config) + # Relative to base_destination, which the members are written under. A + # platform with none writes its BIOS folder into every destination, and + # the trees go there as the core extras do. + root = declared_root(config) + trees: list[dict] = [] + seen: dict[tuple[str, str], int] = {} + for core in sorted(_platform_cores(config, profiles, target_cores)): + profile = profiles[core] + if all(standalone for _view, standalone in platform_layouts(core, profile, handed)): + continue + declared = [t for t in profile.get("data_directories") or [] if isinstance(t, dict)] + directories = core_system_dirs(core, profile, handed) + structure = str((profile.get("pack_structure") or {}).get("libretro") or "") + for tree in deliverable(declared, False, platform_name): + if not read_from_system_dir(tree): + continue + ref = str(tree.get("ref") or "") + entry = data_registry.get(ref) + if entry is None or ref in installed: + continue + allowed = entry.get("for_platforms") + if allowed and platform_name not in allowed: + continue + for directory in [""] if directories is None else directories: + destination = prefixed_destination("/".join( + part.strip("/") + for part in (directory, structure, str(tree.get("destination") or "")) + if part.strip("/") + ), root) or root + if (ref, destination) in seen: + # One tree, read by a second core: the manifest says both + # (tree_readers), the pack writes it once. + first = trees[seen[(ref, destination)]] + if core not in first["readers"]: + first["readers"].append(core) + continue + seen[(ref, destination)] = len(trees) + trees.append({ + "ref": ref, + "destination": destination, + "required": tree.get("required"), + "core": core, + "readers": [core], + "source_systems": entry_system_ids(tree, profile), + }) + return trees + + +def _in_data_cache(path: str, data_registry: dict | None) -> bool: + """Whether a resolved file lies in one of the data directory caches.""" + real = os.path.realpath(path) + return any( + real.startswith(os.path.realpath(entry["local_cache"]) + os.sep) + for entry in (data_registry or {}).values() + if entry.get("local_cache") + ) + + +def _tree_references( + pack_systems: dict, core_trees: Iterable[dict], +) -> Iterator[tuple[tuple[str, ...], dict]]: + """(systems, reference) for each tree a pack carries: those its systems + declare, then those its cores read.""" + for sys_id, system in sorted(pack_systems.items()): + for dd in system.get("data_directories", []): + yield (sys_id,), dd + for tree in core_trees: + yield tuple(tree["source_systems"]), tree + + +class _TreeWalkOptions(TypedDict, total=False): + """The keyword options of _data_directory_members.""" + + refs_out: dict | None + required_only: bool + core_trees: Iterable[dict] + reclaim: dict[str, str] | None + + +def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> str | None: + """The cache folder of a tree reference the pack carries, or None.""" + ref_key = dd.get("ref", "") + if not ref_key or not data_registry or ref_key not in data_registry: + return None + if ref_key in installed_data_refs(platform_name): + return None + entry = data_registry[ref_key] + allowed = entry.get("for_platforms") + if allowed and platform_name not in allowed: + return None + local_path = entry.get("local_cache", "") + if not local_path or not os.path.isdir(local_path): + print( + f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)" + ) + _MISSING_DATA_DIRS.add(ref_key) + return None + return local_path + + +def _tree_files(local_path: str, dd_prefix: str) -> Iterator[tuple[str, str]]: + """(source, destination) of every file of a cached tree.""" + for root, _dirs, filenames in os.walk(local_path): + for fname in filenames: + src = os.path.join(root, fname) + rel = os.path.relpath(src, local_path) + yield src, f"{dd_prefix}/{rel}" if dd_prefix else rel + + +def _data_directory_members( + pack_systems: dict, + data_registry: dict | None, + platform_name: str, + base_dest: str, + case_insensitive: bool, + seen_destinations: set, + seen_lower: set, + seen_parents: set, + **options: Unpack[_TreeWalkOptions], +) -> Iterator[tuple[str, str]]: + """Yield (source, destination) for the cached data directories a + platform's systems declare, then those its cores read (``core_trees``, + from core_data_trees). + + ``reclaim`` maps a destination already taken to the cache file it was + resolved to: the manifest found the platform's entry there and cannot + list it as a file, so the tree yields it once more and the installer + gets it from the tree's archive. + + ``refs_out``, when given, maps each yielded destination to + (registry key, system ids, directory destination, whether the core + needs the tree), for the manifest. + + These are not BIOS and carry no hash of their own: they are whole + trees an emulator reads, refreshed from upstream, so what ships is + whatever the cache holds. The pack and the install manifest both read + this, the first to write the files and the second to count them. + ``required_only`` leaves out a tree declared ``required: false``, one the + core runs without, as it leaves out such a file. + """ + _reject_unknown("_data_directory_members", options, _TreeWalkOptions.__optional_keys__) + refs_out = options.get("refs_out") + reclaim = options.get("reclaim") + required_only = options.get("required_only", False) + core_trees = options.get("core_trees", ()) + # Data directories from _data_dirs.yml + for systems, dd in _tree_references(pack_systems, core_trees): + needed = dd.get("required") is not False + if required_only and not needed: + continue + local_path = _carried_tree(dd, data_registry, platform_name) + if local_path is None: + continue + ref_key = dd.get("ref", "") + dd_dest = dd.get("destination", "") + dd_prefix = f"{base_dest}/{dd_dest}" if base_dest and dd_dest else base_dest or dd_dest + # Held while the caller writes what is yielded: a refresh swapping + # the tree waits until the walk is done. + with cache_lock(local_path, shared=True): + for src, full in _tree_files(local_path, dd_prefix): + if reclaim and full in reclaim and ( + os.path.normpath(reclaim[full]) == os.path.normpath(src) + ): + del reclaim[full] + elif full in seen_destinations or ( + full.lower() in seen_lower and case_insensitive + ) or _has_path_conflict(full, seen_destinations, seen_parents): + continue + else: + seen_destinations.add(full) + _register_path(full, seen_destinations, seen_parents) + if case_insensitive: + seen_lower.add(full.lower()) + if refs_out is not None: + refs_out[full] = (ref_key, systems, dd_prefix, needed) + yield src, full + + +def _pack_data_tree( + zf: zipfile.ZipFile | PackRecord, + local_cache: str, + dd_dest: str, + seen_destinations: set[str], + seen_parents: set[str], + seen_lower: set[str], + packed_at: dict[str, str] | None = None, +) -> int: + """Write one data directory into an emulator pack, under its shared lock. + + A refresh swaps the tree by rename. Without the lock a walk half done + read the old tree and wrote files of the new one. ``packed_at`` records + each member, so a later profile asking for the same bytes there is + served rather than reported missing. + """ + added = 0 + with cache_lock(local_cache, shared=True): + for root, _dirs, filenames in os.walk(local_cache): + for fname in filenames: + src = os.path.join(root, fname) + rel = os.path.relpath(src, local_cache) + full = f"{dd_dest}/{rel}" if dd_dest else rel + if full.lower() in seen_lower or _has_path_conflict( + full, seen_destinations, seen_parents + ): + continue + seen_destinations.add(full) + _register_path(full, seen_destinations, seen_parents) + seen_lower.add(full.lower()) + _add_pack_member(zf, src, full) + if packed_at is not None: + packed_at[full.lower()] = src + added += 1 + return added + + +# Data directories a pack needed and the cache did not hold. The pack is +# written without them, so the run cannot exit as if it were complete: a +# refresh refused by a quota left the PPSSPP pack with 2 files, exit 0. +_MISSING_DATA_DIRS: set[str] = set() + + +def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, list[str]]: + """The cores that read each tree, for a tree only cores read. A tree a + platform system declares is the system's, whatever core runs it, and + gets no entry. Every reference counts: two cores reading one tree yield + its files once.""" + cores: dict[str, set[str]] = {} + declared: set[str] = set() + for _systems, dd in _tree_references(pack_systems, core_trees): + ref = str(dd.get("ref") or "") + if dd.get("core"): + cores.setdefault(ref, set()).update(str(core) for core in dd.get("readers") or [dd["core"]]) + else: + declared.add(ref) + return {ref: sorted(names) for ref, names in cores.items() if ref not in declared} + + +def _tree_group( + ref: str, prefix: str, entry: dict, base_dest: str, versions: dict[str, dict[str, dict]], +) -> dict: + """The manifest record of one data directory, before its files. + + ``versions`` caches each .versions.json read, by path. + """ + version = str(entry.get("version", "master")) + dest = prefix + if base_dest and (dest == base_dest or dest.startswith(base_dest + "/")): + dest = dest[len(base_dest):].lstrip("/") + group: dict = { + "ref": ref, + "dest": dest, + "url": str(entry.get("source_url", "")).format(version=version), + "type": "zip" if entry.get("source_type") == "zip" else "tarball", + "systems": [], + "files": {}, + } + if group["type"] == "zip": + group["strip_components"] = int(entry.get("strip_components", 0)) + else: + group["source_path"] = str(entry.get("source_path", "")).format(version=version) + if entry.get("exclude"): + group["exclude"] = [str(e) for e in entry["exclude"]] + cache = entry.get("local_cache") + if cache: + recorded = Path(cache).parent / ".versions.json" + if str(recorded) not in versions: + try: + versions[str(recorded)] = json.loads(recorded.read_text()) + except FileNotFoundError: + versions[str(recorded)] = {} + size = versions[str(recorded)].get(ref, {}).get("archive_size") + if isinstance(size, int) and size > 0: + group["archive_size"] = size + return group + + +def _manifest_data_directories( + members: list[tuple[str, str]], + refs: dict[str, tuple[str, tuple[str, ...], str, bool]], + registry: dict, + base_dest: str, + readers: dict[str, list[str]] | None = None, + platform_systems: Iterable[str] | None = None, +) -> list[dict]: + """Each data directory the pack carries, as the installer rebuilds it. + + The source archive and the rule that maps its members onto the tree + (strip_components for a ZIP, source_path for a tarball, exclude) come + from _data_dirs.yml, the same refresh_data_dirs applies. Every file + carries the sha1 and size the cache holds, so a member the source + changed since is refused rather than installed. archive_size is the + size of the archive refresh_data_dirs last downloaded, what fetching + the tree costs: a tarball whose tree is 10 KB is a download of 21 MB. + ``systems`` are the platform's ids (``platform_systems``) the tree's + systems normalize to, as a core extra's are: a tree no platform system + serves has none, and goes with the files of no system, as the pack + built with --system puts it in the part of its own. FBNeo's cheats + carried sega-megadrive where RetroArch's list says sega-mega-drive. + ``optional`` marks a tree every core reading it runs without + (``required: false``): install.py --required-only leaves it out, as the + pack built with --required-only does. ``cores`` names the cores that + read a tree no platform system declares (``readers``): an install for + the games of a card keeps it only when its plan runs one of them. + """ + grouped: dict[tuple[str, str], dict] = {} + versions: dict[str, dict[str, dict]] = {} + by_norm: dict[str, list[str]] = {} + for sys_id in sorted(platform_systems or ()): + by_norm.setdefault(_norm_system_id(sys_id), []).append(sys_id) + for src, full in members: + ref, systems, prefix, needed = refs[full] + if platform_systems is not None: + systems = tuple(own for sid in systems for own in by_norm.get(_norm_system_id(sid), ())) + key = (ref, prefix) + group = grouped.get(key) + if group is None: + group = grouped[key] = _tree_group( + ref, prefix, registry.get(ref, {}), base_dest, versions + ) + if needed: + group["needed"] = True + group["systems"].extend(s for s in systems if s not in group["systems"]) + rel = full[len(prefix):].lstrip("/") if prefix else full + hashes = compute_hashes(src, frozenset({"sha1"})) + group["files"][rel] = {"sha1": hashes["sha1"], "size": os.path.getsize(src)} + trees = [] + for key in sorted(grouped): + group = grouped[key] + if not group.pop("needed", False): + group["optional"] = True + if readers and group["ref"] in readers: + group["cores"] = readers[group["ref"]] + trees.append(group) + return trees diff --git a/scripts/packs/emulatorcheck.py b/scripts/packs/emulatorcheck.py new file mode 100644 index 000000000..6021a381f --- /dev/null +++ b/scripts/packs/emulatorcheck.py @@ -0,0 +1,762 @@ +"""Coverage of one emulator or one system, as the emulator reads its files.""" + +from __future__ import annotations + +import os +import sys +from collections.abc import Callable +from dataclasses import dataclass, field + +from core.cli import suggest_names +from core.hashing import compute_hashes +from core.paths import REPO_ROOT +from core.ziptools import build_zip_contents_index +from model.alternatives import set_requirements, settle_sets, slot_set_keys +from model.profiles import ( + ProfileSelectionError, + entry_serves_systems, + load_emulator_profiles, + profiles_for_systems, + select_emulator_profiles, +) +from model.registry import load_data_dir_registry +from model.systems import system_index +from packs.verdicts import ( + DEFAULT_BIOS_DIR, + RELEASE_ASSET_PENDING, + Severity, + Status, + _SEVERITY_ORDER, + _STATUS_ORDER, + _emulator_severity, + _storage_verdict, +) +from resolve.archives import archive_entry, archive_is_optional +from resolve.directories import expand_directory_entries +from resolve.validation import ( + _build_validation_index, + build_ground_truth, + deliverable, + validated_choice, + with_archive_members, +) + + +# The repository's platforms wherever the script runs from, for library calls +# that pass no directory. +_REPO_PLATFORMS = str(REPO_ROOT / "platforms") + + +def _effective_validation_label(details: list[dict], validation_index: dict) -> str: + """Determine the bracket label for the report. + + Returns the union of all check types used, e.g. [crc32+existence+size]. + """ + all_checks: set[str] = set() + has_files = False + for d in details: + fname = d.get("name", "") + if d.get("note"): + continue # skip informational entries (empty profiles) + has_files = True + entry = validation_index.get(fname) + if entry: + all_checks.update(entry["checks"]) + else: + all_checks.add("existence") + if not has_files: + return "existence" + return "+".join(sorted(all_checks)) + + +def _select_profiles( + profile_names: list[str], + all_profiles: dict, + standalone: bool, +) -> list[tuple[str, dict]]: + """Resolve the named profiles, stopping the run on a bad name.""" + try: + return select_emulator_profiles(profile_names, all_profiles, standalone) + except ProfileSelectionError as exc: + print(f"Error: {exc}", file=sys.stderr) + sys.exit(1) + + +_HASH_CONTRADICTED = "declared hash contradicted by the local file" + +# Reduced in the order generate_emulator_pack chooses, so the +# destination's status is the one the pack reports: a slot it +# fills with a contradicted copy, or counts as refused by the +# core, is not missing because another alternative is absent. +_SLOT_PREFERENCE: tuple[Callable[[tuple], bool], ...] = ( + lambda a: a[0]["status"] == Status.OK, + lambda a: a[0]["status"] == Status.UNTESTED + and a[0].get("reason") == _HASH_CONTRADICTED, + lambda a: a[0]["status"] != Status.MISSING, +) + + +def _emulator_files( + emu_name: str, + profile: dict, + db: dict, + standalone: bool, + all_profiles: dict, + system_ids: list[str] | None, + required_only: bool, + region_drops: set[str], +) -> list[dict]: + """The entries of a profile the emulator pack carries.""" + from packs.extras import expand_agnostic_entries + from packs.paths import _resolve_destination + + files = expand_agnostic_entries( + expand_directory_entries( + deliverable(profile.get("files", []), standalone), + db, + standalone, + ), + emu_name, profile, db, standalone, all_profiles, + ) + if system_ids: + files = [fe for fe in files if entry_serves_systems(fe, profile, system_ids)] + if required_only: + optional_archives = { + fe["archive"] for fe in files + if fe.get("archive") + and archive_is_optional(archive_entry(fe["archive"], files), fe["archive"], files) + } + files = [ + fe for fe in files + if fe.get("archive") not in optional_archives + and (fe.get("archive") or fe.get("required") is not False) + ] + if region_drops: + # Loose files only, as the emulator pack: an archive ships whole, + # and dropping kronos' regional stvbios.zip members rebuilt the + # archive here from 4 of its 14 members and changed its required. + files = [ + fe + for fe in files + if fe.get("archive") + or _resolve_destination(fe, standalone) not in region_drops + ] + return files + + +def _archive_result( + archive: str, required: bool, local_path: str | None, resolve_status: str, +) -> dict: + """The verdict on an archive unit, from its resolution.""" + if local_path and resolve_status == "hash_mismatch": + # Same policy as the loose-file branch below: the name + # matched while the bytes contradict the hash the profile + # declares on the container. Reporting it covered says the + # collection holds an archive it does not. + return { + "name": archive, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": "declared hash contradicted by the local file", + } + if local_path: + result = { + "name": archive, + "status": Status.OK, + "required": required, + "path": local_path, + } + if resolve_status == RELEASE_ASSET_PENDING: + result["release_asset"] = local_path + return result + return { + "name": archive, + "status": Status.MISSING, + "required": required, + } + + +PlacedResult = tuple[str, dict, bool, bool, list[dict]] + + +@dataclass +class _EmulatorPack: + """The emulator pack as verify_emulator retraces it, and its report.""" + + db: dict + standalone: bool + required_only: bool + validation_index: dict + zip_contents: dict + data_registry: dict | None + details: list[dict] = field(default_factory=list) + # Members of a set another member fills, or that the set's first member + # stands for: not missing, and out of every count. + set_members: list[dict] = field(default_factory=list) + file_status: dict[str, str] = field(default_factory=dict) + file_severity: dict[str, str] = field(default_factory=dict) + dest_to_name: dict[str, str] = field(default_factory=dict) + data_dir_notices: list[str] = field(default_factory=list) + # The paths the emulator pack writes a profile file to. A copy whose hash + # the profile contradicts is written too (UNTESTED here, a DISCREPANCY in + # the pack), so the status alone does not say what the pack holds. + packed_dests: set[str] = field(default_factory=set) + # The emulator pack walks profiles in name order and keeps the first + # file at a path, folding case: a later profile's different file there + # (zesarux pentagon.rom after speccy's PENTAGON.ROM) is not in the pack. + sha1_by_path: dict = field(init=False) + # Destination -> (file packed there, its profile, the path as written). + # Archives and data trees take paths too, before and after the loose + # files of their profile, as the pack writes them. + placed: dict[str, tuple[str | None, str, str]] = field(default_factory=dict) + placed_files: set[str] = field(default_factory=set) + placed_parents: set[str] = field(default_factory=set) + content_ids: dict[str, str | None] = field(default_factory=dict) + + def __post_init__(self) -> None: + self.sha1_by_path = { + entry.get("path"): sha1 for sha1, entry in self.db.get("files", {}).items() + } + + def pending(self, entry: dict, local_path: str | None, status: str) -> tuple[str | None, str]: + from resolve.packfiles import pending_release_asset, run_is_offline + + # Read from disk and the cache, as _resolve_for_platform does: a + # release asset the cache lacks is fetched by an online build + # (generate_emulator_pack resolves with offline=offline). + if status in ("not_found", "hash_mismatch") and not run_is_offline(): + asset = pending_release_asset(entry, self.db) + if asset: + return asset, RELEASE_ASSET_PENDING + return local_path, status + + def content_id(self, path: str | None) -> str | None: + if not path: + return None + if path not in self.content_ids: + self.content_ids[path] = self.sha1_by_path.get(path) or ( + compute_hashes(path)["sha1"] if os.path.isfile(path) else None + ) + return self.content_ids[path] + + def block(self, dest: str) -> str | None: + from packs.paths import placement_block + + return placement_block( + dest, self.placed_files, set(self.placed), self.placed_parents, True + ) + + def occupy(self, dest: str, path: str | None, owner: str) -> None: + from packs.paths import _register_path + + if self.block(dest): + return + self.placed[dest.lower()] = (path, owner, dest) + _register_path(dest, self.placed_files, self.placed_parents) + + def occupy_trees(self, emu_name: str, profile: dict) -> None: + """The profile's data trees follow its files in the pack, which + writes them even when the system filter leaves it no file: + bluemsx's Machines/ tree holds msx-emu's coleco.rom path in a + --system colecovision pack.""" + for dd in deliverable(profile.get("data_directories", []), self.standalone): + if self.required_only and dd.get("required") is False: + continue + cache = (self.data_registry or {}).get(dd.get("ref", ""), {}).get("local_cache", "") + if not cache or not os.path.isdir(cache): + continue + dd_dest = dd.get("destination", "") + structure = profile.get("pack_structure") + prefix = ( + structure.get("standalone" if self.standalone else "libretro", "") + if structure else "" + ) + if prefix: + dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix + for root, _dirs, names in os.walk(cache): + for fname in names: + src = os.path.join(root, fname) + rel = os.path.relpath(src, cache).replace(os.sep, "/") + self.occupy(f"{dd_dest}/{rel}" if dd_dest else rel, src, emu_name) + + def note_data_dirs(self, profile: dict) -> None: + # Check data directories (only notice if not cached) + for dd in deliverable( + profile.get("data_directories", []), self.standalone + ): + if self.required_only and dd.get("required") is False: + continue + ref = dd.get("ref", "") + if not ref: + continue + if self.data_registry and ref in self.data_registry: + cache_path = self.data_registry[ref].get("local_cache", "") + if cache_path and os.path.isdir(cache_path): + continue # cached, no notice needed + self.data_dir_notices.append(ref) + + def verify_profile( + self, emu_name: str, profile: dict, files: list[dict], spares: set[str], + ) -> None: + """Verify one profile's entries and add them to the report.""" + self.note_data_dirs(profile) + + if not files: + self.details.append( + { + "name": f"({emu_name})", + "status": Status.OK, + "required": False, + "system": "", + "note": f"No files needed for {profile.get('emulator', emu_name)}", + "ground_truth": [], + } + ) + self.occupy_trees(emu_name, profile) + return + + # Each destination's outcome, settled by set once the profile is + # read: an archive unit is a member like a loose file (Kronos reads + # kronos/stvbios.zip, else stvbios.zip). + placed_results = self._archive_results(emu_name, profile, files, spares) + self._place_loose(emu_name, self._loose_results(emu_name, files), placed_results) + self._settle(emu_name, profile, placed_results) + self.occupy_trees(emu_name, profile) + + def _archive_results( + self, emu_name: str, profile: dict, files: list[dict], spares: set[str], + ) -> list[PlacedResult]: + # Verify archives as units (e.g., neogeo.zip, aes.zip) + from packs.paths import _archive_destination + from resolve.packfiles import resolve_file + + placed_results: list[PlacedResult] = [] + seen_archives: set[str] = set() + for file_entry in files: + archive = file_entry.get("archive") + if not archive or archive in seen_archives: + continue + seen_archives.add(archive) + own_entry = archive_entry(archive, files) + # Where the pack puts it: an archive_prefix or pack_structure + # moves it, and a loose same-named entry is another file. + dest = _archive_destination( + archive, profile.get("archive_prefix", ""), + profile.get("pack_structure"), self.standalone, + ) + if dest in spares: + continue + local_path, resolve_status = self.pending(own_entry, *resolve_file( + own_entry, + self.db, + DEFAULT_BIOS_DIR, + self.zip_contents, + data_dir_registry=self.data_registry, + offline=True, + )) + required = any( + f.get("archive") == archive and f.get("required", True) + for f in files + ) + result = _archive_result(archive, required, local_path, resolve_status) + result["system"] = file_entry.get("system", "") + result["hle_fallback"] = False + result["ground_truth"] = build_ground_truth(archive, self.validation_index) + result["destination"] = dest + block = self.block(dest) + if block and local_path and result["status"] != Status.MISSING: + other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", "")) + if block == "path_conflict" or self.content_id(local_path) != self.content_id(other_path): + # The pack serves the other profile's file here: this + # archive is not in it, whatever this profile resolves. + result["status"] = Status.MISSING + result["reason"] = ( + "a packed file occupies its directory" if block == "path_conflict" + else f"the pack holds {owner}'s {other_dest} at this path" + ) + elif local_path: + self.occupy(dest, local_path, emu_name) + self.packed_dests.add(dest) + placed_results.append((dest, result, required, False, [own_entry])) + return placed_results + + def _loose_results( + self, emu_name: str, files: list[dict], + ) -> dict[str, list[tuple[dict, bool, bool, dict]]]: + from packs.paths import _resolve_destination + from resolve.packfiles import resolve_file + + # Results of this emulator, by destination. Several entries of one + # profile on one destination are the releases the code accepts + # there (a shareware and a retail HOG, each GRP in a size table): + # holding one of them fills the slot, and the others are not gaps. + emu_results: dict[str, list[tuple[dict, bool, bool, dict]]] = {} + + for file_entry in files: + # Skip archive members (verified as archive units above) + if file_entry.get("archive"): + continue + + dest_hint = file_entry.get("path", "") + # The emulator pack's resolution, release assets included. + local_path, resolve_status = self.pending(file_entry, *resolve_file( + {**with_archive_members(file_entry, files), "source_profile": emu_name}, + self.db, + DEFAULT_BIOS_DIR, + self.zip_contents, + dest_hint=dest_hint, + data_dir_registry=self.data_registry, + offline=True, + )) + if resolve_status in ("not_found", "user_provided", "external"): + local_path = None + name = file_entry.get("name", "") + required = file_entry.get("required", True) + hle = file_entry.get("hle_fallback", False) + + result = self._loose_result( + file_entry, name, required, local_path, resolve_status, emu_name, + ) + result["system"] = file_entry.get("system", "") + result["hle_fallback"] = hle + result["ground_truth"] = build_ground_truth(name, self.validation_index) + # The slot the emulator pack places this entry in: standalone_path + # under --standalone, the sanitised path. + dest = _resolve_destination(file_entry, self.standalone) or name + emu_results.setdefault(dest, []).append((result, required, hle, file_entry)) + return emu_results + + def _loose_result( + self, file_entry: dict, name: str, required: bool, local_path: str | None, + resolve_status: str, emu_name: str, + ) -> dict: + """The verdict on a loose profile entry, from its resolution.""" + stored = _storage_verdict(file_entry, emulator_pack=True) + if stored is not None: + return stored + if resolve_status == RELEASE_ASSET_PENDING: + return { + "name": name, + "status": Status.OK, + "required": required, + "path": local_path, + "release_asset": local_path, + "reason": "release asset, fetched when the pack is built", + } + if not local_path: + result = {"name": name, "status": Status.MISSING, "required": required} + # An entry the profile documents as unsourceable is absent by + # design: a per-user key, a slot the user fills, a dump nobody + # has made. Counting it beside a file somebody could still + # find invites the wrong repair: dropping the flag, or + # chasing a vendor's whole install tree. + unsourceable = file_entry.get("unsourceable") + if unsourceable: + result["unsourceable"] = ( + unsourceable if isinstance(unsourceable, str) else "" + ) + return result + # Apply emulator validation + # Judged by this emulator's own entries, as it runs its check, + # through the selection the emulator pack makes. + chosen, disagreement = validated_choice( + file_entry, local_path, self.db, self.validation_index, DEFAULT_BIOS_DIR, + None, emulators={emu_name}, + ) + if disagreement: + return { + "name": name, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": disagreement.split(" says ", 1)[-1], + } + if chosen != local_path: + return { + "name": name, + "status": Status.OK, + "required": required, + "path": chosen, + } + if resolve_status == "hash_mismatch": + # Nothing in validation: caught it, but the name matched + # while the bytes contradict the hash the profile + # declares. That is a different file wearing the right + # name (config.ini and ROM collide across systems), so + # calling it covered reports the collection as holding + # something it does not. Validation runs first because it + # names the specific field that disagrees. + return { + "name": name, + "status": Status.UNTESTED, + "required": required, + "path": local_path, + "reason": "declared hash contradicted by the local file", + } + return { + "name": name, + "status": Status.OK, + "required": required, + "path": local_path, + } + + def _place_loose( + self, emu_name: str, + emu_results: dict[str, list[tuple[dict, bool, bool, dict]]], + placed_results: list[PlacedResult], + ) -> None: + for dest, alternatives in emu_results.items(): + # What the emulator pack places here: an accepted file, else a + # file whose hash the profile contradicts. A refused copy is held + # but never packed. + slot_entries = [a[3] for a in alternatives] + kept = _preferred_alternatives(alternatives) + packed = next( + (a[0].get("path") for a in kept + if a[0]["status"] == Status.OK and a[0].get("path")), + None, + ) or next( + (a[0].get("path") for a in kept + if a[0]["status"] == Status.UNTESTED + and a[0].get("reason") == _HASH_CONTRADICTED and a[0].get("path")), + None, + ) + held = packed or next( + (a[0].get("path") for a in kept + if a[0]["status"] != Status.MISSING and a[0].get("path")), + None, + ) + block = self.block(dest) + block_reason = "" + if block and held is not None: + block_reason = self._block_reason(dest, block, held) + elif not block and packed is not None: + self.occupy(dest, packed, emu_name) + self.packed_dests.add(dest) + for result, required, hle, _file_entry in kept: + if block_reason and result["status"] != Status.MISSING: + result["status"] = Status.MISSING + result["reason"] = block_reason + result["destination"] = dest + placed_results.append((dest, result, required, hle, slot_entries)) + + def _block_reason(self, dest: str, block: str, held: str) -> str: + other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", "")) + same = self.content_id(held) is not None and self.content_id(held) == self.content_id( + other_path + ) + if block == "path_conflict": + return "a packed file occupies its directory" + if block == "case_twin": + return ( + f"packed only as {other_dest}, from {owner}" + if same + else f"the pack holds {owner}'s {other_dest} at this path" + ) + if not same: + return f"the pack holds {owner}'s {other_dest} at this path" + return "" + + def _settle(self, emu_name: str, profile: dict, placed_results: list[PlacedResult]) -> None: + # A set the code takes one member of is one need: once a member is + # in the pack the others are not missing, and a set nobody holds is + # one gap under its first member. Settled per profile, before the + # destinations of several profiles are merged. + excused, standing = settle_sets([ + ( + slot_set_keys(emu_name, entries), + entries[0], + result["status"] == Status.OK + or (result["status"] == Status.UNTESTED + and result.get("reason") == _HASH_CONTRADICTED), + ) + for _dest, result, _required, _hle, entries in placed_results + ], lambda key: set_requirements(profile).get(key[1], True)) + for position, (dest, result, required, hle, _fe) in enumerate(placed_results): + if position in excused and result["status"] == Status.MISSING: + self.set_members.append(result) + continue + if position in standing: + result["alternatives"] = standing[position].others + result["required"] = required = standing[position].required + self.details.append(result) + + # Aggregate by destination (path if available, else name) + self.dest_to_name[dest] = result["name"] + cur = result["status"] + prev = self.file_status.get(dest) + if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get( + prev, 0 + ): + self.file_status[dest] = cur + sev = _emulator_severity(cur, required, hle) + prev_sev = self.file_severity.get(dest) + if prev_sev is None or _SEVERITY_ORDER.get( + sev, 0 + ) > _SEVERITY_ORDER.get(prev_sev, 0): + self.file_severity[dest] = sev + + +def _preferred_alternatives( + alternatives: list[tuple[dict, bool, bool, dict]], +) -> list[tuple[dict, bool, bool, dict]]: + """The one alternative the emulator pack places at a destination.""" + if len(alternatives) > 1: + for keep in _SLOT_PREFERENCE: + chosen = [a for a in alternatives if keep(a)] + if chosen: + return chosen[:1] + return alternatives + + +def verify_emulator( + profile_names: list[str], + emulators_dir: str, + db: dict, + standalone: bool = False, + regions: list[str] | None = None, + platforms_dir: str = _REPO_PLATFORMS, + system_ids: list[str] | None = None, + required_only: bool = False, +) -> dict: + """Verify files for specific emulator profiles. + + A region priority list narrows the report the same way a pack built with the + same list would be narrowed, through the emulator pack's own drop set. + `system_ids` keeps the entries of those systems, as the system pack does. + `required_only` reports on the pack built with --required-only: a loose + file or tree marked ``required: false`` is left out, and an archive when + it and every member it carries are optional, as the builder leaves them. + """ + from packs.paths import _resolve_destination + + # Also load aliases for redirect messages + all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) + + selected = _select_profiles(profile_names, all_profiles, standalone) + # The member index only answers a zipped_file entry, and decompressing + # every archive took 23 of the 24 seconds of a run that had none. + zip_contents = ( + build_zip_contents_index(db) + if any(f.get("zipped_file") for _name, profile in selected + for f in profile.get("files") or []) + else {} + ) + + # Build validation index from selected profiles only + selected_profiles = dict(selected) + validation_index = _build_validation_index(selected_profiles) + data_registry = load_data_dir_registry(platforms_dir) + + pack = _EmulatorPack( + db, standalone, required_only, validation_index, zip_contents, data_registry, + ) + + # The emulator pack withdraws these, and the report withdraws the same. + region_drops: set[str] = set() + if regions: + from packs.extras import emulator_region_drops + + region_drops = emulator_region_drops( + selected, standalone, regions, required_only, db=db, + zip_contents=zip_contents, data_registry=data_registry, + ) + + for emu_name, profile in sorted(selected): + files = _emulator_files( + emu_name, profile, db, standalone, all_profiles, system_ids, + required_only, region_drops, + ) + spares: set[str] = set() + if required_only: + from packs.extras import emulator_required_spares + + spares = emulator_required_spares( + emu_name, profile, files, standalone, region_drops, db, + validation_index, zip_contents, data_registry=data_registry, + ) + files = [ + fe for fe in files + if fe.get("archive") or _resolve_destination(fe, standalone) not in spares + ] + pack.verify_profile(emu_name, profile, files, spares) + + counts = { + Severity.OK: 0, + Severity.INFO: 0, + Severity.WARNING: 0, + Severity.CRITICAL: 0, + } + for s in pack.file_severity.values(): + counts[s] = counts.get(s, 0) + 1 + status_counts: dict[str, int] = {} + for s in pack.file_status.values(): + status_counts[s] = status_counts.get(s, 0) + 1 + + label = _effective_validation_label(pack.details, validation_index) + + gt_filenames = set(validation_index) + total = len(pack.file_status) + with_validation = sum( + 1 for dest in pack.file_status if pack.dest_to_name.get(dest, "") in gt_filenames + ) + + return { + "emulators": [n for n, _ in selected], + "verification_mode": label, + "total_files": total, + # The paths the emulator pack fills with the profile's files, for the + # pipeline's comparison with the pack built in memory. + "pack_destinations": sorted(pack.packed_dests), + "severity_counts": counts, + "status_counts": status_counts, + "details": pack.details, + "set_members": pack.set_members, + "data_dir_notices": sorted(set(pack.data_dir_notices)), + "ground_truth_coverage": { + "with_validation": with_validation, + "platform_only": total - with_validation, + "total": total, + }, + } + + +def verify_system( + system_ids: list[str], + emulators_dir: str, + db: dict, + standalone: bool = False, + regions: list[str] | None = None, + platforms_dir: str = _REPO_PLATFORMS, + required_only: bool = False, +) -> dict: + """Verify files for all emulators supporting given system IDs.""" + profiles = load_emulator_profiles(emulators_dir) + matching = profiles_for_systems(profiles, system_ids, standalone) + + if not matching: + all_systems: set[str] = set() + for p in profiles.values(): + all_systems.update(p.get("systems", [])) + if standalone: + print( + f"No standalone emulators found for system(s): {', '.join(system_ids)}", + file=sys.stderr, + ) + else: + print( + f"No emulators found for system(s): {', '.join(system_ids)}", + file=sys.stderr, + ) + # --list-systems merges spellings that differ in case or separator: + # the hint counted 579 spellings for the 532 lines it prints. + print(suggest_names(system_ids, sorted(all_systems), "--list-systems", + listed=len(system_index(profiles))), + file=sys.stderr) + sys.exit(1) + + return verify_emulator( + matching, emulators_dir, db, standalone, regions=regions, + platforms_dir=platforms_dir, system_ids=system_ids, required_only=required_only, + ) diff --git a/scripts/packs/emulatorpack.py b/scripts/packs/emulatorpack.py new file mode 100644 index 000000000..c07d622ce --- /dev/null +++ b/scripts/packs/emulatorpack.py @@ -0,0 +1,642 @@ +"""Packs for one emulator or one system.""" + +from __future__ import annotations + +import contextlib +import functools +import os +import shutil +import sys +import tempfile +import zipfile +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict + +from core.cli import suggest_names +from core.paths import REPO_ROOT +from core.ziptools import build_zip_contents_index +from model.alternatives import settle_sets, slot_set_keys +from model.profiles import ( + ProfileSelectionError, + entry_serves_systems, + load_emulator_profiles, + profiles_for_systems, + select_emulator_profiles, +) +from model.registry import load_data_dir_registry +from model.systems import MANUFACTURER_PREFIXES, system_index +from packs.archive import ( + PackRecord, + _Placed, + _add_pack_member, + _add_zip_to_pack, + _reject_unknown, + _same_bytes, + _write_generated_member, + _writing_pack, +) +from packs.datatrees import _MISSING_DATA_DIRS, _pack_data_tree +from packs.extras import emulator_region_drops, emulator_required_spares, expand_agnostic_entries +from packs.naming import _bounded_join, _bounded_pack_name, _name_part, _narrowings +from packs.paths import _archive_destination, _resolve_destination +from resolve import packfiles as packresolve +from resolve.archives import archive_entry, archive_is_optional +from resolve.directories import expand_directory_entries +from resolve.packfiles import download_external, resolve_file +from resolve.validation import ( + _build_validation_index, + deliverable, + validated_choice, + with_archive_members, +) + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +if TYPE_CHECKING: + # What a destination came to: its entries, whether it was filled, and the + # report to make if no other member of its set fills it. + _Outcome = tuple[list[dict], bool, "Callable[[], None] | None"] + + +class EmulatorPackOptions(TypedDict, total=False): + """The keyword options of generate_emulator_pack.""" + + zip_contents: dict | None + offline: bool | None + platforms_dir: str | None + pack_name: str | None + system_ids: list[str] | None + final_dir: str | None + record: PackRecord | None + + +@dataclass +class _EmulatorPackBuild: + """One emulator pack being written, and what each destination came to.""" + + db: dict + bios_dir: str + standalone: bool + required_only: bool + zip_contents: dict + data_registry: dict + validation_index: dict + region_drops: set[str] + all_profiles: dict + zf: zipfile.ZipFile | PackRecord + offline: bool | None = None + system_ids: list[str] | None = None + record: PackRecord | None = None + total_files: int = 0 + data_files: int = 0 + missing_files: list[str] = field(default_factory=list) + rejected_files: list[str] = field(default_factory=list) + discrepancies: list[str] = field(default_factory=list) + unsourceable_files: list[str] = field(default_factory=list) + instruction_files: list[str] = field(default_factory=list) + placed: _Placed = field(default_factory=lambda: _Placed(True)) + seen_hashes: set[str] = field(default_factory=set) # SHA1 dedup for same file, different path + # Loose file packed at each folded destination, to tell a profile asking + # for the same file there from one asking for other bytes. + packed_at: dict[str, str] = field(default_factory=dict) + # A destination is missing once, however many profiles ask for it: + # verify --emulator counts by destination. + missing_at: set[str] = field(default_factory=set) + data_dir_notices: list[str] = field(default_factory=list) + + def report_missing(self, name: str, destination: str) -> None: + if destination not in self.missing_at: + self.missing_at.add(destination) + self.missing_files.append(name) + + def _add(self, local_path: str, dest: str, fe: dict | None) -> None: + """Write a loose file or an archive at dest and count it.""" + if fe is not None and local_path.endswith(".zip"): + _add_zip_to_pack(local_path, dest, self.zf, fe) + else: + _add_pack_member(self.zf, local_path, dest) + self.placed.take(dest) + self.total_files += 1 + if self.record is not None: + self.record.files.append(dest) + + def pack_profile(self, emu_name: str, profile: dict) -> None: + pack_structure = profile.get("pack_structure") + files = expand_agnostic_entries( + expand_directory_entries( + deliverable(profile.get("files", []), self.standalone), + self.db, + self.standalone, + ), + emu_name, profile, self.db, self.standalone, self.all_profiles, + ) + if self.system_ids: + files = [ + fe for fe in files if entry_serves_systems(fe, profile, self.system_ids) + ] + if not files and not profile.get("data_directories"): + print(f" No files needed for {profile.get('emulator', emu_name)}") + + # What each destination came to, settled by set once the + # profile is read: a member another member fills is not missing, + # and a set nobody holds is reported once (alternatives.py). An + # archive unit is a member like a loose file. + outcomes: list[_Outcome] = [] + spares = emulator_required_spares( + emu_name, profile, files, self.standalone, self.region_drops, self.db, + self.validation_index, self.zip_contents, data_registry=self.data_registry, + ) if self.required_only else set() + + # Pack archives as units + archive_prefix = profile.get("archive_prefix", "") + for archive_name in sorted({fe["archive"] for fe in files if fe.get("archive")}): + archive_dest = _archive_destination( + archive_name, archive_prefix, pack_structure, self.standalone + ) + own_entry = archive_entry(archive_name, files) + if self.required_only and archive_is_optional(own_entry, archive_name, files): + continue + if archive_dest in spares: + continue + outcomes.append(self._pack_archive(own_entry, archive_name, archive_dest)) + + for dest, alternatives in self._slots(files, spares).items(): + outcome = self._pack_slot(emu_name, files, dest, alternatives) + if outcome is not None: + outcomes.append(outcome) + + excused, _standing = settle_sets([ + (slot_set_keys(emu_name, entries), entries[0], fills) + for entries, fills, _report in outcomes + ]) + for position, (_entries, _fills, report) in enumerate(outcomes): + if report is not None and position not in excused: + report() + self._pack_trees(profile, pack_structure) + + def _pack_archive(self, own_entry: dict, archive_name: str, archive_dest: str) -> _Outcome: + local_path, status = resolve_file( + own_entry, + self.db, + self.bios_dir, + self.zip_contents, + data_dir_registry=self.data_registry, + offline=self.offline, + ) + taken = archive_dest.lower() in self.placed.lower + if taken or self.placed.conflicts(archive_dest): + # Another profile's file holds this path. The same archive + # asked for twice is served. Anything else leaves this + # profile without its archive, which used to pass in + # silence: a neocdz.zip lacking 000-lo.lo shipped as the + # one the second core needs. + if not (taken and local_path and _same_bytes( + local_path, self.packed_at.get(archive_dest.lower()) + )): + return ([own_entry], False, functools.partial( + self.report_missing, archive_name, archive_dest + )) + return ([own_entry], True, None) + if local_path and status not in ("not_found",): + self._add(local_path, archive_dest, own_entry) + self.packed_at[archive_dest.lower()] = local_path + return ([own_entry], True, None) + return ([own_entry], False, functools.partial( + self.report_missing, archive_name, archive_dest + )) + + def _slots(self, files: list[dict], spares: set) -> dict[str, list[dict]]: + # Pack individual files (skip archive members). The entries of one + # profile on one destination are the releases the code accepts + # there (raze's seven SW.GRP): the first one the core accepts + # fills the slot, as verify --emulator credits it, and the slot + # has one outcome however many alternatives it lists. + slots: dict[str, list[dict]] = {} + for fe in files: + if self.required_only and fe.get("required") is False: + continue + if fe.get("archive"): + continue + dest = _resolve_destination(fe, self.standalone) + if not dest or dest in spares: + continue + if self.region_drops and dest in self.region_drops: + continue + slots.setdefault(dest, []).append(fe) + return slots + + def _write_instructions(self, provided: dict, dest: str) -> None: + # Instructions, not a file: written beside the slot the + # user fills, and counted apart from what the pack holds. + self.placed.take(dest) + instr = provided.get("instructions", "Please provide this file manually.") + folder = dest.rsplit("/", 1)[0] + "/" if "/" in dest else "" + _write_generated_member( + self.zf, + f"{folder}INSTRUCTIONS_{provided['name']}.txt", + f"File needed: {provided['name']}\n\n{instr}\n", + ) + # verify --emulator counts an unsourceable one as such. + (self.unsourceable_files if provided.get("unsourceable") else self.instruction_files).append( + provided["name"] + ) + + def _choose( + self, emu_name: str, files: list[dict], alternatives: list[dict], + ) -> tuple[tuple[dict, str, str | None] | None, str | None, str | None]: + """The alternative the core accepts, with the refusal of the first + one it turned away and that copy.""" + fallback: tuple[dict, str, str | None] | None = None + refusal: str | None = None + refused_path: str | None = None + for fe in alternatives: + local_path, status = resolve_file( + {**with_archive_members(fe, files), "source_profile": emu_name}, + self.db, + self.bios_dir, + self.zip_contents, + dest_hint=fe.get("path", ""), + data_dir_registry=self.data_registry, + offline=self.offline, + ) + if status == "external": + return (fe, "", "external"), refusal, refused_path + if status in ("not_found", "user_provided") or not local_path: + continue + # The file verify --emulator credits is the one shipped: + # a dump the core's own check rejects gives way to a held + # one it accepts (azahar's otp.bin, dolphin's dsp_rom.bin). + better, disagreement = validated_choice( + fe, local_path, self.db, self.validation_index, self.bios_dir, None, + emulators={emu_name}, + ) + if disagreement: + reason = disagreement.split(" says ", 1)[-1] + refusal = refusal or f"{fe['name']}: {reason}" + refused_path = refused_path or local_path + continue + if better != local_path: + return (fe, better, None), refusal, refused_path + if status == "hash_mismatch": + # Not a check the core runs, so the file still serves, + # but it is not the dump the profile documents. + fallback = fallback or (fe, local_path, "mismatch") + continue + return (fe, local_path, None), refusal, refused_path + return fallback, refusal, refused_path + + def _pack_slot( + self, emu_name: str, files: list[dict], dest: str, alternatives: list[dict], + ) -> _Outcome | None: + # Name order, first file wins, case folded: verify replays + # the rule and reports a later profile's file as missing. + block = self.placed.block(dest) + + provided = next( + (fe for fe in alternatives if fe.get("storage") == "user_provided"), + None, + ) + if provided is not None: + if not block: + self._write_instructions(provided, dest) + return None + + chosen, refusal, refused_path = self._choose(emu_name, files, alternatives) + if block: + held = ( + chosen[1] if chosen is not None and chosen[2] != "external" + else None if chosen is not None else refused_path + ) + if chosen is not None or held is not None: + if block == "taken" and held and _same_bytes( + held, self.packed_at.get(dest.lower()) + ): + # The file already at this path, asked for twice. + return (alternatives, True, None) + return (alternatives, False, functools.partial( + self.report_missing, alternatives[0]["name"], dest + )) + + if chosen is None: + return self._unfilled(alternatives, dest, refusal) + fe, local_path, how = chosen + if how == "external": + return self._pack_external(fe, dest, alternatives) + if how == "mismatch": + self.discrepancies.append( + f"{fe['name']}: not the dump the {emu_name} profile declares" + ) + + # SHA1 dedup: skip if same physical file AND same destination + # (but allow same file to be packed under different destinations, + # e.g., IPL.bin in GC/USA/ and GC/EUR/ from same source) + dedup_key_hash = f"{os.path.realpath(local_path)}:{dest}" + if dedup_key_hash not in self.seen_hashes: + self.seen_hashes.add(dedup_key_hash) + self._add(local_path, dest, fe) + self.packed_at[dest.lower()] = local_path + return (alternatives, True, None) + + def _unfilled(self, alternatives: list[dict], dest: str, refusal: str | None) -> _Outcome: + if refusal: + self.rejected_files.append(refusal) + return (alternatives, False, None) + if all(fe.get("unsourceable") for fe in alternatives): + return (alternatives, False, functools.partial( + self.unsourceable_files.append, alternatives[0]["name"] + )) + return (alternatives, False, functools.partial( + self.report_missing, alternatives[0]["name"], dest + )) + + def _pack_external(self, fe: dict, dest: str, alternatives: list[dict]) -> _Outcome: + file_ext = os.path.splitext(fe["name"])[1] or "" + with tempfile.NamedTemporaryFile( + delete=False, suffix=file_ext, dir=packresolve.scratch_dir() + ) as tmp: + tmp_path = tmp.name + try: + # Built in memory, nothing is fetched: verify --emulator + # cannot fetch either and reports the file missing. + if self.record is None and download_external(fe, tmp_path): + self._add(tmp_path, dest, None) + return (alternatives, True, None) + return (alternatives, False, functools.partial( + self.missing_files.append, fe["name"] + )) + finally: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + + def _pack_trees(self, profile: dict, pack_structure: dict | None) -> None: + # The trees after the files, as in a platform pack: a dump the + # profile declares wins over the copy a tree bundles at the same + # path (Dolphin's real dsp_rom.bin over Sys/GC's free one). + # A tree only one build reads follows that build, like a file. + required_only = self.required_only + for dd in deliverable( + profile.get("data_directories", []), self.standalone + ): + if required_only and dd.get("required") is False: + continue + ref_key = dd.get("ref", "") + if not ref_key or not self.data_registry or ref_key not in self.data_registry: + if ref_key: + self.data_dir_notices.append(ref_key) + continue + local_cache = self.data_registry[ref_key].get("local_cache", "") + if not local_cache or not os.path.isdir(local_cache): + self.data_dir_notices.append(ref_key) + continue + dd_dest = dd.get("destination", "") + if pack_structure: + mode_key = "standalone" if self.standalone else "libretro" + prefix = pack_structure.get(mode_key, "") + if prefix: + dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix + self.data_files += _pack_data_tree( + self.zf, local_cache, dd_dest, self.placed.destinations, + self.placed.parents, self.placed.lower, self.packed_at, + ) + + def nothing_needed(self) -> bool: + return self.total_files + self.data_files == 0 and not ( + self.missing_files or self.rejected_files or self.instruction_files + or self.unsourceable_files + ) + + def report(self, shown: str) -> None: + # Report. The members of data trees are counted apart: verify --emulator + # counts the profile's files, and folding 3500 tree members into the + # same number made the two impossible to compare. + parts = [f"{self.total_files} files packed"] + if self.data_files: + parts.append(f"{self.data_files} from data directories") + if self.missing_files: + parts.append(f"{len(self.missing_files)} missing") + if self.rejected_files: + parts.append(f"{len(self.rejected_files)} refused by the core") + if self.unsourceable_files: + parts.append(f"{len(self.unsourceable_files)} unsourceable") + if self.instruction_files: + parts.append(f"{len(self.instruction_files)} to provide") + print(f" {shown}: {', '.join(parts)}") + for name in self.missing_files: + print(f" MISSING: {name}") + for name in self.unsourceable_files: + print(f" UNSOURCEABLE: {name}") + for name in self.instruction_files: + print(f" TO PROVIDE: {name} (instructions in the pack)") + for line in self.rejected_files: + print(f" REFUSED: {line}") + for line in self.discrepancies: + print(f" DISCREPANCY: {line}") + for ref in sorted(set(self.data_dir_notices)): + print( + f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)" + ) + _MISSING_DATA_DIRS.update(self.data_dir_notices) + + +def generate_emulator_pack( + profile_names: list[str], + emulators_dir: str, + db: dict, + bios_dir: str, + output_dir: str, + standalone: bool = False, + *, + required_only: bool = False, + regions: list[str] | None = None, + **options: Unpack[EmulatorPackOptions], +) -> str | None: + """Generate a ZIP pack for specific emulator profiles. + + Returns the path, "" when no file is needed (verify --emulator reports + 0/0 OK), None on failure. + + `pack_name` is the caller's own file name: the system pack names its + archive after the system, and joining 23 SNES emulator names went past + the 255 bytes a file name may hold. `system_ids` keeps only the entries + of those systems, as a platform pack narrows core extras. `final_dir` + is where the caller moves the archive, the path the report names. + `record` builds the pack in memory instead (PackRecord): nothing is + written or read, and the paths are kept on it. + """ + _reject_unknown("generate_emulator_pack", options, EmulatorPackOptions.__optional_keys__) + all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) + zip_contents = options.get("zip_contents") + if zip_contents is None: + zip_contents = build_zip_contents_index(db) + + try: + selected = select_emulator_profiles(profile_names, all_profiles, standalone) + except ProfileSelectionError as exc: + print(f"Error: {exc}", file=sys.stderr) + return None + + record = options.get("record") + # ZIP naming + display_names = [_name_part(p.get("emulator", n)) for n, p in selected] + validation_index = _build_validation_index(dict(selected)) + narrow_tags = "".join( + tag + for tag, _label in _narrowings( + "full", regions, None, False, required_only, standalone + ) + ) + zip_name = options.get("pack_name") or _bounded_pack_name( + display_names, [n for n, _p in selected], f"{narrow_tags}_BIOS_Pack.zip" + ) + zip_path = os.path.join(output_dir, zip_name) + if record is None: + os.makedirs(output_dir, exist_ok=True) + + data_registry = load_data_dir_registry( + options.get("platforms_dir") or str(REPO_ROOT / "platforms") + ) + region_drops: set[str] = ( + emulator_region_drops( + selected, standalone, regions, required_only, db, + zip_contents=zip_contents, data_registry=data_registry, + ) + if regions + else set() + ) + with ( + contextlib.nullcontext(record) if record is not None + else _writing_pack(zip_path) + ) as zf: + build = _EmulatorPackBuild( + db, bios_dir, standalone, required_only, zip_contents, data_registry, + validation_index, region_drops, all_profiles, zf, + offline=options.get("offline"), system_ids=options.get("system_ids"), record=record, + ) + for emu_name, profile in sorted(selected): + build.pack_profile(emu_name, profile) + + # Remove empty ZIP (no files packed and no missing = nothing to ship) + if record is None and build.nothing_needed(): + os.unlink(zip_path) + # What verify --emulator reports as 0/0 OK: no file is needed, so + # no pack is written and the run succeeds. Printed with the path, + # the run named a file it had just removed and exited 1. + print(f" {', '.join(display_names)}: no file needed, no pack written") + return "" + + final_dir = options.get("final_dir") + build.report(os.path.join(final_dir, zip_name) if final_dir else zip_path) + return None if build.nothing_needed() else zip_path + + +class SystemPackOptions(TypedDict, total=False): + """The keyword options of generate_system_pack.""" + + required_only: bool + regions: list[str] | None + offline: bool | None + platforms_dir: str | None + + +def generate_system_pack( + system_ids: list[str], + emulators_dir: str, + db: dict, + bios_dir: str, + output_dir: str, + standalone: bool = False, + zip_contents: dict | None = None, + **options: Unpack[SystemPackOptions], +) -> str | None: + """Generate a ZIP pack for all emulators supporting given system IDs. + + Returns the path, "" when no file is needed, None on failure. + """ + _reject_unknown("generate_system_pack", options, SystemPackOptions.__optional_keys__) + required_only = options.get("required_only", False) + regions = options.get("regions") + offline = options.get("offline") + platforms_dir = options.get("platforms_dir") + profiles = load_emulator_profiles(emulators_dir) + matching = profiles_for_systems(profiles, system_ids, standalone) + + if not matching: + all_systems: set[str] = set() + for p in profiles.values(): + all_systems.update(p.get("systems", [])) + if standalone: + print( + f"No standalone emulators found for system(s): {', '.join(system_ids)}", + file=sys.stderr, + ) + else: + print( + f"No emulators found for system(s): {', '.join(system_ids)}", + file=sys.stderr, + ) + # --list-systems merges spellings that differ in case or separator: + # the hint counted 579 spellings for the 532 lines it prints. + print(suggest_names(system_ids, sorted(all_systems), "--list-systems", + listed=len(system_index(profiles))), + file=sys.stderr) + return None + + # Named like the platform's --system tag: one spelling of a system is + # one file name, and one selection. + sys_display = _bounded_join( + [_system_display_name(sid) for sid in system_ids], list(system_ids) + ) + # Built in a scratch directory: under its emulator name in output_dir it + # overwrote, then carried away, an --emulator pack already there. + os.makedirs(output_dir, exist_ok=True) + # Every dimension goes through the one list: keeping only the region + # tag made --system X --required-only overwrite the pack built without it. + tags = "".join( + tag + for tag, _label in _narrowings( + "full", regions, None, False, required_only, standalone=standalone + ) + ) + # The selection mode is part of the name: `--system sega-triforce` + # and `--emulator triforce` both wrote Triforce_BIOS_Pack.zip, and + # the second run replaced the first without a word. + final_name = f"{sys_display}_System{tags}_BIOS_Pack.zip" + scratch = tempfile.mkdtemp(prefix=".system-", dir=output_dir) + try: + result = generate_emulator_pack( + matching, + emulators_dir, + db, + bios_dir, + scratch, + standalone, + zip_contents=zip_contents, + required_only=required_only, + regions=regions, + offline=offline, + platforms_dir=platforms_dir, + pack_name=final_name, + system_ids=system_ids, + final_dir=output_dir, + ) + if not result: + return result + new_path = os.path.join(output_dir, final_name) + os.replace(result, new_path) + return new_path + finally: + shutil.rmtree(scratch, ignore_errors=True) + + +def _system_display_name(system_id: str) -> str: + """Convert system ID to display name for ZIP naming.""" + s = system_id.lower().replace("_", "-") + for prefix in MANUFACTURER_PREFIXES: + if s.startswith(prefix): + s = s[len(prefix) :] + break + parts = s.split("-") + return "_".join(p.title() for p in parts if p) diff --git a/scripts/packextras.py b/scripts/packs/extras.py similarity index 99% rename from scripts/packextras.py rename to scripts/packs/extras.py index 6731659c2..4c4171e56 100644 --- a/scripts/packextras.py +++ b/scripts/packs/extras.py @@ -26,7 +26,7 @@ from model.declarations 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 packs.paths import libretro_systems, save_destination, save_layout from resolve.regions import FILE_GROUP if TYPE_CHECKING: @@ -329,7 +329,7 @@ class ExtraResolver: def resolve(self, fe: dict, dest: str) -> tuple[str | None, str, str]: """(local copy or None, resolver status, the core's disagreement).""" - from packresolve import pending_release_asset, resolve_file, run_is_offline + from resolve.packfiles import pending_release_asset, resolve_file, run_is_offline from resolve.validation import core_size_refusal, validated_choice local_path, status = resolve_file( @@ -410,7 +410,7 @@ def hidden_extras( ``required_only`` are the builder's for a --source truth or a --required-only pack: an optional extra is skipped before it takes a path. """ - from packpaths import _register_path, placement_block + from packs.paths import _register_path, placement_block reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__) report = options.get("report") @@ -1402,7 +1402,7 @@ def undeclared_report( """The gap report _collect_emulator_extras reads, for a caller that collects the extras more than once with these arguments: the region grouping and the pack or manifest phase 2 each computed it in full.""" - from verify import find_undeclared_files + from packs.gaps import find_undeclared_files return find_undeclared_files( config, emulators_dir, db, emu_profiles, target_cores=target_cores, @@ -2123,7 +2123,7 @@ def _ships( Resolved with the builder's own inputs: without the data directories, AmberELEC's bluemsx config.ini read as missing while the pack held it. """ - from packresolve import resolve_declaration + from resolve.packfiles import resolve_declaration from resolve.validation import baseline_verdict path, status = resolve_declaration( @@ -2322,7 +2322,7 @@ def emulator_region_drops( emulator pack resolves with. """ from resolve import regions as resolve_regions - from packpaths import _resolve_destination + from packs.paths import _resolve_destination from resolve.validation import _build_validation_index, filter_files_by_mode region_index = resolve_regions.build_region_index(dict(selected)) @@ -2370,7 +2370,7 @@ def emulator_required_spares( stvbios.zip. The pack and verify --emulator both read this.""" from model.alternatives import groups_of, rank_in, required_groups from resolve.archives import archive_entry - from packpaths import _archive_destination, _resolve_destination + from packs.paths import _archive_destination, _resolve_destination reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__) data_registry = options.get("data_registry") @@ -2415,7 +2415,7 @@ def _emulator_ships( directories, dolphin-mmjr2's nwc24msg.cfg read as missing while the pack held it. """ - from packresolve import resolve_file + from resolve.packfiles import resolve_file from resolve.validation import validated_choice, with_archive_members local, status = resolve_file( diff --git a/scripts/packs/finalize.py b/scripts/packs/finalize.py new file mode 100644 index 000000000..742144c4f --- /dev/null +++ b/scripts/packs/finalize.py @@ -0,0 +1,239 @@ +"""Built packs checked against their platform and given their manifest.""" + +from __future__ import annotations + +import json +import os +import shutil +import sys +import tempfile +import zipfile +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, TypedDict + +from core.artifacts import set_plain_mode +from model.registry import list_registered_platforms +from model.targets import load_target_config +from packs.archive import _reject_unknown, _write_generated_member +from packs.integrity import generate_sha256sums, verify_pack, verify_pack_against_platform +from packs.naming import _expected_pack_names, _narrows_contents, _pack_archives +from packs.scope import annotate_pack_systems + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def _baseline_shortfall(excluded: int, absent: int) -> list[str]: + """Why a verified pack holds fewer baseline files than the platform declares.""" + parts = [] + if excluded: + parts.append(f"{excluded} unsafe excluded") + if absent: + parts.append(f"{absent} not in the collection") + return parts + + +def inject_manifest(zip_path: str, manifest: dict) -> None: + """Inject manifest.json into an existing ZIP pack. + + The pack is rewritten beside its final name and swapped in, as + _writing_pack builds it: appending in place rewrites the central + directory last, so a process killed in between left an unreadable ZIP + where a valid pack had been. + """ + manifest_json = json.dumps(manifest, indent=2, ensure_ascii=False) + + with zipfile.ZipFile(zip_path, "r") as zf: + has_manifest = "manifest.json" in zf.namelist() + + directory = os.path.dirname(zip_path) or "." + fd, scratch = tempfile.mkstemp( + prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory + ) + os.close(fd) + try: + if not has_manifest: + # Append to a copy. Append mode defaults to ZIP_STORED, which + # would leave the manifest uncompressed and give the same pack + # two different byte layouts depending on the path taken here. + shutil.copyfile(zip_path, scratch) + with zipfile.ZipFile(scratch, "a", zipfile.ZIP_DEFLATED) as zf: + _write_generated_member(zf, "manifest.json", manifest_json) + else: + with zipfile.ZipFile(zip_path, "r") as src, \ + zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as dst: + for item in src.infolist(): + if item.filename == "manifest.json": + continue + dst.writestr(item, src.read(item.filename)) + _write_generated_member(dst, "manifest.json", manifest_json) + set_plain_mode(scratch) + os.replace(scratch, zip_path) + except BaseException: + Path(scratch).unlink(missing_ok=True) + raise + + +def _target_cores_for( + platform_name: str, target_name: str | None, platforms_dir: str +) -> set[str] | None: + """Cores a target leaves available, or None when no target was asked for. + + Called on a platform the build already packed under the target, so the + target is known to it: a platform without one is left out of the run. + """ + if not target_name: + return None + return load_target_config(platform_name, target_name, platforms_dir) + + +class FinalizeOptions(TypedDict, total=False): + """The keyword options of verify_and_finalize_packs.""" + + platforms_dir: str + skip_conformance: bool + data_registry: dict | None + regions: list[str] | None + target_name: str | None + emulators_dir: str + no_game_data: bool + pack_systems_by_name: dict[str, dict] | None + built: Iterable[str] | None + + +@dataclass(frozen=True) +class _FinalizeSettings: + """FinalizeOptions with their defaults.""" + + platforms_dir: str = "platforms" + skip_conformance: bool = False + data_registry: dict | None = None + regions: list[str] | None = None + target_name: str | None = None + emulators_dir: str = "emulators" + no_game_data: bool = False + pack_systems_by_name: dict[str, dict] | None = None + built: Iterable[str] | None = None + + +def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> bool: + """Stage 2 for one platform of a pack: extract and verify against its + config. Prints the platform's line and its errors.""" + ( + p_ok, + _total, + _matched, + p_errors, + bl_checked, + bl_present, + core_checked, + core_present, + bl_excluded, + bl_absent, + ) = verify_pack_against_platform( + zip_path, + pname, + opts.platforms_dir, + db=db, + emulators_dir=opts.emulators_dir, + regions=opts.regions, + data_registry=opts.data_registry, + target_cores=_target_cores_for(pname, opts.target_name, opts.platforms_dir), + no_game_data=opts.no_game_data, + ) + status = "OK" if p_ok else "FAILED" + exclusion_note = "".join( + f", {part}" for part in _baseline_shortfall(bl_excluded, bl_absent) + ) + print( + f" platform {pname}: {bl_present}/{bl_checked} baseline present" + f"{exclusion_note}, " + f"{core_present}/{core_checked} cores present, {status}" + ) + if not p_ok: + for err in p_errors: + print(f" {err}") + return p_ok + + +def verify_and_finalize_packs( + output_dir: str, + db: dict, + **options: Unpack[FinalizeOptions], +) -> bool: + """Verify all packs, inject manifests, generate SHA256SUMS. + + pack_systems_by_name gives, per pack file name, the systems its + manifest.json records (pack_systems). + + ``built`` names the packs this run wrote, and only those are verified + and get a manifest. A pack another run left in the directory was + reopened, recompressed and given a manifest without its pack_systems, + which made the installer refuse to narrow it. None takes every pack. + + Two-stage verification: + 1. Hash check against database.json (integrity) + 2. Extract + verify against platform config (conformance) + + Returns True if all packs pass verification. + """ + _reject_unknown("verify_and_finalize_packs", options, FinalizeOptions.__optional_keys__) + opts = _FinalizeSettings(**options) + all_ok = True + + # Map ZIP names to platform names + # By the exact name this run's reduction gives a platform's pack, never by + # substring: a _Custom or regional pack left by another run was judged + # against this run's expectation and failed it. + registered = list_registered_platforms(opts.platforms_dir) + expected = _expected_pack_names( + registered, opts.platforms_dir, opts.regions, opts.target_name, + no_game_data=opts.no_game_data, + ) + packs = _pack_archives(output_dir) + if opts.built is not None: + packs = [name for name in packs if name in set(opts.built)] + pack_to_platform: dict[str, list[str]] = {} + for name in packs: + for pname in registered: + if name in expected[pname]: + pack_to_platform.setdefault(name, []).append(pname) + + failing: list[str] = [] + for name in packs: + zip_path = os.path.join(output_dir, name) + + # Stage 1: database integrity + ok, manifest = verify_pack(zip_path, db, data_registry=opts.data_registry) + summary = manifest["summary"] + status = "OK" if ok else "ERRORS" + print( + f" verify {name}: {summary['verified']}/{summary['total_files']} verified, " + f"{summary['untracked']} untracked, {summary['errors']} errors [{status}]" + ) + if not ok: + for err in manifest["errors"]: + print(f" ERROR: {err}") + all_ok = False + failing.append(name) + annotate_pack_systems(manifest, (opts.pack_systems_by_name or {}).get(name)) + inject_manifest(zip_path, manifest) + + # Stage 2: platform conformance (extract + verify) + # Skipped for filtered/split/custom packs (intentionally partial) + if opts.skip_conformance: + continue + if _narrows_contents(name): + continue + for pname in pack_to_platform.get(name, []): + if not _conforms(zip_path, pname, db, opts): + all_ok = False + failing.append(f"{name} ({pname})") + + generate_sha256sums(output_dir) + if failing: + # Named at the end, where a 4,000-line log is read, and on stderr. + print(f"ERROR: packs failed verification: {', '.join(failing)}", file=sys.stderr) + return all_ok diff --git a/scripts/packs/gaps.py b/scripts/packs/gaps.py new file mode 100644 index 000000000..c707bdf0b --- /dev/null +++ b/scripts/packs/gaps.py @@ -0,0 +1,703 @@ +"""Files the cores load that a platform does not declare, and why some are left out.""" + +from __future__ import annotations + +import functools +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field + +from model.alternatives import set_fields, set_keys, set_requirements, settle_sets +from model.declarations import OUTER_ROOTS, platform_declarations, platform_declared_contents +from model.profiles import PROFILE_IDENTITY_FIELDS, entry_system_ids, load_emulator_profiles +from packs.paths import core_save_folder +from resolve.archives import archive_entry, archive_members +from resolve.cores import resolve_platform_cores +from resolve.directories import expand_directory_entries +from resolve.launchers import LauncherLayer, declared_destinations, held_record +from resolve.layout import runs_standalone, system_dir_path +from resolve.localfile import resolve_local_file +from resolve.nativemode import hash_mismatch_excludes_file +from resolve.ownership import _foreign_tree, _owner_tokens +from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set +from resolve.validation import ( + _parse_validation, + case_folded_slots, + core_size_refusal, + declaration_settles, + installed_with_emulator, + outside_gap_scope, + read_from_save_dir, + same_slot_entries, + unread_on, + with_archive_members, +) + + +def _build_expected(file_entry: dict, checks: list[str]) -> dict: + """Extract expected validation values from an emulator profile file entry.""" + expected: dict = {} + if not checks: + return expected + if "size" in checks: + for key in ("size", "min_size", "max_size", "size_multiple"): + if file_entry.get(key) is not None: + expected[key] = file_entry[key] + for hash_type in ("crc32", "md5", "sha1", "sha256"): + if hash_type in checks and file_entry.get(hash_type): + expected[hash_type] = file_entry[hash_type] + adler_val = file_entry.get("known_hash_adler32") or file_entry.get("adler32") + if adler_val: + expected["adler32"] = adler_val + return expected + + +def _in_foreign_tree(db: dict, owners: set[str], sha1: str) -> bool: + """Whether the collection keeps this sha1 in another emulator's tree.""" + return _foreign_tree(db.get("files", {}).get(sha1, {}).get("path", ""), owners) + + +def _name_in_index( + name: str, + by_name: dict, + by_path_suffix: dict | None = None, + data_names: set[str] | None = None, + by_name_lower: dict[str, str] | None = None, + foreign: Callable[[str], bool] | None = None, +) -> bool: + """Check if a name is resolvable in the database indexes or data directories. + + *foreign* tells a copy in another emulator's tree from the sha1 of a + name: matched in another casing, such a copy is not the asker's, as in + resolve_local_file's case-insensitive step. + """ + # Strip trailing slash for directory-type entries (e.g. nestopia/samples/foo/) + name = name.rstrip("/") + if name in by_name: + return True + basename = name.rsplit("/", 1)[-1] if "/" in name else name + if basename != name and basename in by_name: + return True + if by_name_lower: + for key in {name.lower(), basename.lower()}: + if key in by_name_lower and not ( + foreign and all(foreign(s) for s in by_name[by_name_lower[key]]) + ): + return True + if by_path_suffix and name in by_path_suffix: + return True + if data_names: + if name in data_names or name.lower() in data_names: + return True + if basename != name and ( + basename in data_names or basename.lower() in data_names + ): + return True + return False + + +def _candidate_verdict( + file_entry: dict, + fname: str, + is_standalone: bool, + include_all: bool, + declared_names: Mapping[str, list[tuple[int | None, str]]] | set[str], + dest: str = "", + folded_slots: frozenset[str] = frozenset(), + declared_contents: Mapping[str, set[str]] | None = None, +) -> str: + """Whether a profile entry can be a gap, and whether it is settled. + + Three answers. "keep" means it is a candidate. "settled" means something + has answered for it (the platform declares it, or the profile documents + it as unsourceable), so the same requirement reached from another profile + must not be reconsidered. "skip" means it does not apply in this context, + which leaves it open for a profile where it does: the same file can be + libretro-only here and standalone-only there. + """ + if file_entry.get("unsourceable"): + return "settled" + if outside_gap_scope(file_entry, is_standalone): + return "skip" + if not include_all and declaration_settles( + file_entry, fname, declared_names, dest, folded_slots, declared_contents + ): + return "settled" + return "keep" + + +def _identity_of(entry: dict) -> dict: + """The fields that tell a profile's file apart from a same-named one.""" + return { + field: entry.get(field) + for field in PROFILE_IDENTITY_FIELDS + if entry.get(field) not in (None, "", []) + } + + +def _gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: + """The destination a gap entry is keyed and reported at.""" + # One destination rule for the dedup key and for the entry: a + # standalone build without standalone_path falls back on path. + # The key used to skip that fallback, so clk's Acorn/basic.rom and + # Electron/basic.rom both keyed as "basic.rom" under Batocera's + # standalone clk and the second was dropped. + # A file the libretro build reads below the save directory is + # placed there, apart from the system directory the platform + # lays out: no declaration of the BIOS tree answers for it. + if is_standalone: + return f.get("standalone_path") or f.get("path") or fname + if save_root: + return f.get("path") or fname + return system_dir_path(f, f.get("path") or fname) + + +def _region_key(f: dict) -> tuple[str, ...]: + raw_regions = f.get("region") or [] + return tuple( + str(value) for value in ( + raw_regions if isinstance(raw_regions, list) else [raw_regions] + ) + ) + + +SetRecord = tuple[tuple, dict, bool, "tuple[dict, dict | None] | None"] + + +@dataclass +class _GapScan: + """What find_undeclared_files reads and gathers while it walks the cores.""" + + config: dict + db: dict + data_names: set[str] | None + include_all: bool + declared_names: Mapping[str, list[tuple[int | None, str]]] + folded_slots: frozenset[str] + declared_contents: Mapping[str, set[str]] + # Whether the builder drops a file whose local copy contradicts its + # declared hash, which decides if such a copy counts as held here. + shipped_on_mismatch: bool + launcher_layer: LauncherLayer + by_name: dict = field(init=False) + by_name_lower: dict[str, str] = field(init=False) + by_path_suffix: dict = field(init=False) + launcher_candidates: list[tuple[str, bool, dict, dict]] = field(default_factory=list) + # Each grouped requirement met, as (set keys, entry, fills, (reported + # entry, the entry it is a claim on)): settled once every core is read. + set_records: list[SetRecord] = field(default_factory=list) + undeclared: list[dict] = field(default_factory=list) + seen_files: set[tuple] = field(default_factory=set) + # Key -> the entry reported for it. A later profile reading the same + # requirement is kept on that entry rather than counted again: a pack + # built without the first profile still has to name the file. + reported: dict[tuple, dict] = field(default_factory=dict) + # Track archives: archive_name -> {in_repo, emulator, files: [...], ...} + archive_entries: dict[tuple, dict] = field(default_factory=dict) + + def __post_init__(self) -> None: + self.by_name = self.db.get("indexes", {}).get("by_name", {}) + self.by_name_lower = {k.lower(): k for k in self.by_name} + self.by_path_suffix = self.db.get("indexes", {}).get("by_path_suffix", {}) + + def scan_file(self, emu_name: str, layout: dict, is_standalone: bool, f: dict) -> None: + """Consider one profile entry of one build as a gap.""" + fname = f.get("name", "") + save_root = read_from_save_dir(f, is_standalone) + dest = _gap_destination(f, fname, is_standalone, save_root) + region_key = _region_key(f) + # Same-name requirements at different paths, for different systems, + # or in distinct variant groups are not interchangeable. + seen_key = ( + fname, + f.get("archive"), + dest, + f.get("system"), + f.get("selection_slot"), + region_key, + # Below the save directory each core is handed a folder + # of its own: two cores reading hiscore.dat there read + # two files. + ("save", core_save_folder(layout)) if save_root + else (f["root"],) if f.get("root") in OUTER_ROOTS + # In the emulator's own folder: no other core reads it. + else ("emulator", emu_name) if f.get("unplaced") else None, + ) + config = self.config + if not fname or unread_on(f, config.get("_key", "")): + return + first = self.reported.get(seen_key) + duplicate = seen_key in self.seen_files + if duplicate and (first is None or first["profile"] == emu_name): + return + outer = save_root or f.get("root") in OUTER_ROOTS + # Nor does it answer for one read below the roms directory. + verdict = _candidate_verdict( + f, fname, is_standalone, self.include_all, + {} if outer else self.declared_names, + dest, self.folded_slots, + None if outer else self.declared_contents, + ) + if verdict == "settled": + self.seen_files.add(seen_key) + if (self.launcher_layer and not f.get("unsourceable") and not outer + and not f.get("unplaced")): + self.launcher_layer.declared_elsewhere(emu_name, is_standalone, f) + # Answered by the platform's own declaration, which its + # report covers: the set it belongs to is spoken for. + self.set_records.append((set_keys((emu_name, is_standalone), f), f, True, None)) + return + if verdict == "skip": + return + + archive = f.get("archive") + self.seen_files.add(seen_key) + + if archive: + self._count_archive_member(emu_name, layout, is_standalone, f, region_key) + return + + in_repo = self._held(emu_name, layout, f, fname, dest) + entry = self._gap_entry(emu_name, layout, f, fname, dest, in_repo, save_root) + if self.launcher_layer and not outer: + # One read outside the BIOS tree is still served where a + # launcher links that very file: RetroDECK links Cemu's + # keys.txt to bios/cemu/keys.txt. + self.launcher_candidates.append((emu_name, is_standalone, f, entry)) + keys = set_keys((emu_name, is_standalone), f) + if duplicate and first is not None: + first.setdefault("other_claims", []).append(entry) + self.set_records.append((keys, f, in_repo, (entry, first))) + return + self.reported[seen_key] = entry + self.undeclared.append(entry) + self.set_records.append((keys, f, in_repo, (entry, None))) + + def _count_archive_member( + self, emu_name: str, layout: dict, is_standalone: bool, f: dict, + region_key: tuple[str, ...], + ) -> None: + archive = f["archive"] + archive_key = ( + archive, + f.get("system_dir"), + f.get("system"), + f.get("selection_slot"), + region_key, + is_standalone, + ) + if archive_key not in self.archive_entries: + in_repo = _name_in_index( + archive, self.by_name, self.by_path_suffix, self.data_names, + self.by_name_lower, + ) + self.archive_entries[archive_key] = { + "profile": emu_name, + "emulator": layout.get("emulator", emu_name), + "systems": entry_system_ids(f, layout), + "system": f.get("system"), + "region": f.get("region"), + "selection_slot": f.get("selection_slot"), + "name": archive, + "archive": archive, + "path": system_dir_path(f, archive), + "required": False, + "hle_fallback": False, + "category": f.get("category", "bios"), + "in_repo": in_repo, + "note": "", + "checks": [], + "source_ref": None, + "expected": {}, + "archive_file_count": 0, + "archive_required_count": 0, + "members": archive_members(archive, layout.get("files", [])), + } + if f.get("system_dir"): + self.archive_entries[archive_key]["system_dir"] = f["system_dir"] + # The archive's own declaration names its sets: an + # archive is a member like a loose file. + own = archive_entry(archive, layout.get("files", [])) + self.archive_entries[archive_key].update(set_fields(own, layout)) + self.set_records.append(( + set_keys((emu_name, is_standalone), own), own, in_repo, + (self.archive_entries[archive_key], None), + )) + entry = self.archive_entries[archive_key] + entry["archive_file_count"] += 1 + if f.get("required", False): + entry["archive_required_count"] += 1 + entry["required"] = True + + def _held(self, emu_name: str, layout: dict, f: dict, fname: str, dest: str) -> bool: + """Whether the collection holds the file as the builder would ship it.""" + # Resolution: name, then path basename + # storage: release names where the bytes are served from, not + # that the collection holds them: resolved like any file. + # Resolved as the asker, as the builder's ExtraResolver does: + # another casing of the name in another emulator's tree is + # not this emulator's file (dosbox-x's et4000.bin and pcem's + # et4000.BIN). + owned = {**f, "source_profile": emu_name} + if self.shipped_on_mismatch and (f.get("md5") or f.get("sha1")): + # The entry states what its content should be and the builder + # drops a copy that contradicts it, so content decides here + # too. A name match would not do: generic names collide across + # systems, and answering yes on one describes a pack that will + # not contain the file. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + return _lp is not None and _st != "hash_mismatch" + in_repo = self._held_by_name(owned, f, fname, dest) + if in_repo and "size" in _parse_validation(f.get("validation")): + # On any platform the core measures what it opens: a + # copy it turns away by its own size check is not + # held for it, the rule the builder's lookup applies + # (packextras.ExtraResolver). The Apple IIGS' 128 KB + # ROM is not Basilisk II's ROM. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + if core_size_refusal( + f, _lp, same_slot_entries(layout.get("files"), fname, dest) + ): + in_repo = False + return in_repo + + def _held_by_name(self, owned: dict, f: dict, fname: str, dest: str) -> bool: + foreign = functools.partial(_in_foreign_tree, self.db, _owner_tokens(owned)) + in_repo = _name_in_index( + fname, self.by_name, self.by_path_suffix, self.data_names, self.by_name_lower, + foreign, + ) + if not in_repo and dest != fname: + path_base = dest.rsplit("/", 1)[-1] + in_repo = _name_in_index( + path_base, self.by_name, self.by_path_suffix, self.data_names, + self.by_name_lower, foreign, + ) + if in_repo and not any( + f.get(h) for h in ("sha1", "md5", "crc32", "sha256") + ): + # A name alone answers nothing when every copy of that + # name fails the size the code checks: the resolver + # rejects them all. NanoBoyAdvance's 16 KB bios.bin met + # only PCem's and QEMU's PC BIOS images of that name. + # The fallback below then decides as for any mismatch. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + if _st == "hash_mismatch": + in_repo = False + if not in_repo: + # Hash fallback: the repo may hold the content under a + # different filename (exos21.rom vs exos21.bin). + # + # A copy contradicting the declared hash counts as held + # only where the builder would ship it. Under existence + # the frontend never opens the file, so the pack carries + # it and reports the divergence. Under a digest mode the + # frontend would reject it, the builder leaves it out, and + # calling it available here would describe a pack that + # does not contain it. + _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) + in_repo = _st != "not_found" and _lp is not None + if in_repo and _st == "hash_mismatch" and self.shipped_on_mismatch: + in_repo = False + return in_repo + + def _gap_entry( + self, emu_name: str, layout: dict, f: dict, fname: str, dest: str, + in_repo: bool, save_root: bool, + ) -> dict: + checks = _parse_validation(f.get("validation")) + entry = { + "profile": emu_name, + "emulator": layout.get("emulator", emu_name), + "systems": entry_system_ids(f, layout), + "system": f.get("system"), + "region": f.get("region"), + "selection_slot": f.get("selection_slot"), + "name": fname, + "path": dest, + "required": f.get("required", False), + "hle_fallback": f.get("hle_fallback", False), + "bundled": installed_with_emulator(f, self.config.get("_key", "")), + "category": f.get("category", "bios"), + "in_repo": in_repo, + "note": f.get("note", ""), + "checks": sorted(checks) if checks else [], + **set_fields(f, layout), + "source_ref": f.get("source_ref"), + "expected": _build_expected(f, checks), + **_identity_of(f), + "sha1": f.get("sha1"), + "md5": f.get("md5"), + } + if f.get("contents"): + entry["contents"] = f["contents"] + if save_root: + entry["root"] = "save" + folder = core_save_folder(layout) + if folder is not None: + entry["core_folder"] = folder + elif f.get("system_dir"): + entry["system_dir"] = f["system_dir"] + members = with_archive_members(f, layout.get("files", [])).get("members") + if members: + entry["members"] = members + if f.get("layout_path"): + entry["layout_path"] = f["layout_path"] + if f.get("unprefixed"): + entry["unprefixed"] = True + if f.get("unplaced"): + entry["unplaced"] = f["unplaced"] + elif f.get("root") in OUTER_ROOTS: + # Read below the roms directory (ROCKNIX's roms/pico-8) + # or in an emulator folder (RetroBat's emulators/pico8). + entry["root"] = f["root"] + return entry + + +def find_undeclared_files( + config: dict, + emulators_dir: str, + db: dict, + emu_profiles: dict | None = None, + target_cores: set[str] | None = None, + data_names: set[str] | None = None, + include_all: bool = False, + declared_names: Mapping[str, list[tuple[int | None, str]]] | None = None, +) -> list[dict]: + """Find files needed by cores but not declared in platform config. + + declared_names overrides the default enriched declarations from + platform_declarations. Pass the strict ones (YAML names only) when + building packs so alias-only names still get packed. + """ + if declared_names is None: + declared_names = platform_declarations(config, db) + folded_slots = case_folded_slots(config, declared_names) + declared_contents = platform_declared_contents(config, db) + + profiles = ( + emu_profiles + if emu_profiles is not None + else load_emulator_profiles(emulators_dir) + ) + + relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) + standalone_set = platform_standalone_set(config) + # What the platform's own launchers open, matched to the cores it runs: + # the one decision the builder and this report both read. + launcher_layer = LauncherLayer( + config, profiles, relevant, db, declared_destinations(config) + ) + scan = _GapScan( + config, db, data_names, include_all, declared_names, folded_slots, + declared_contents, + hash_mismatch_excludes_file(config.get("verification_mode")), + launcher_layer, + ) + + for emu_name, profile in sorted(profiles.items()): + if profile.get("type") in ("launcher", "alias"): + continue + if emu_name not in relevant: + continue + + # A filename-agnostic profile is served by the scan (packextras), all + # but the entries its layout reads outside the BIOS tree: those are + # named here, or a launcher folder drops them without a word + # (ARMSX2's arcade/proverb.zip once ROCKNIX binds bios/armsx2). + agnostic = profile.get("bios_mode") == "agnostic" + + for layout, is_standalone in platform_layouts(emu_name, profile, standalone_set): + for f in expand_directory_entries( + layout.get("files", []), db, is_standalone + ): + if agnostic and not f.get("unplaced"): + continue + scan.scan_file(emu_name, layout, is_standalone, f) + + undeclared = scan.undeclared + settled: set[int] = set() + if launcher_layer: + added, settled = launcher_layer.settle( + scan.launcher_candidates, lambda report: held_record(report, db) + ) + undeclared = [u for u in undeclared if id(u) not in settled] + undeclared.extend(added) + + undeclared.extend(sorted(scan.archive_entries.values(), key=lambda e: e["name"])) + + return _split_bundled_claims( + _settle_core_sets(undeclared, scan.set_records, settled, profiles) + ) + + +def _split_bundled_claims(undeclared: list[dict]) -> list[dict]: + """A file one emulator installs itself, another reads from the pack. + + The first profile reading a requirement hosts the claims of the others, + and a host installed with its emulator is left out of the pack with all + of them: DraStic brings its own usrcheat.dat, and ROCKNIX's DSPerate, + which reads the same file, lost it wherever DraStic runs too. Built for + a board without DraStic, the pack carried it. + """ + out: list[dict] = [] + for entry in undeclared: + claims = entry.get("other_claims") or [] + rest = [c for c in claims if not c.get("bundled")] + if not entry.get("bundled") or not rest: + out.append(entry) + continue + own = [c for c in claims if c.get("bundled")] + kept = {k: v for k, v in entry.items() if k != "other_claims"} + if own: + kept["other_claims"] = own + promoted = dict(rest[0]) + if rest[1:]: + promoted["other_claims"] = rest[1:] + out += [kept, promoted] + return out + + +def _settle_core_sets( + undeclared: list[dict], + records: list[tuple[tuple, dict, bool, tuple[dict, dict | None] | None]], + launcher_settled: set[int], + profiles: dict[str, dict], +) -> list[dict]: + """The core complement with each set of alternatives settled. + + A member the collection lacks is dropped when another member is held, + declared by the platform or placed by its launcher, and a set nobody + holds keeps one entry, its first member, naming the others. A claim + another profile shares stays: its own core may need that very file. + """ + # Archive units rank first among equals, as the builder orders them. + grouped = sorted( + (r for r in records if r[0]), + key=lambda r: not (r[3] is not None and r[3][0].get("archive")), + ) + if not grouped: + return undeclared + excused, standing = settle_sets([ + (keys, f, fills or (ref is not None and id(ref[0]) in launcher_settled)) + for keys, f, fills, ref in grouped + ], lambda key: set_requirements(profiles.get(key[0][0], {})).get(key[1], True)) + declared_sets = { + key for keys, _f, _fills, ref in grouped if ref is None for key in keys + } + dropped: set[int] = set() + for position, (keys, _f, _fills, ref) in enumerate(grouped): + if ref is None: + continue + entry, host = ref + required_keys = [k for k in keys if k[1] in entry.get("required_groups", ())] + if required_keys and all(k in declared_sets for k in required_keys): + # The platform declares a member of each of its required sets: + # under --required-only that declaration carries them. + entry["set_declared"] = True + if position in standing: + entry["alternatives"] = standing[position].others + entry["required"] = standing[position].required + if position not in excused: + continue + if host is not None: + host["other_claims"] = [c for c in host.get("other_claims", []) if c is not entry] + if not host["other_claims"]: + del host["other_claims"] + else: + dropped.add(id(entry)) + out: list[dict] = [] + for entry in undeclared: + if id(entry) not in dropped: + out.append(entry) + continue + # Another core reading the same requirement still needs it. + claims = entry.get("other_claims") or [] + if claims: + promoted = dict(claims[0]) + if claims[1:]: + promoted["other_claims"] = claims[1:] + out.append(promoted) + return out + + +def find_exclusion_notes( + config: dict, + emulators_dir: str, + emu_profiles: dict | None = None, + target_cores: set[str] | None = None, +) -> list[dict]: + """Document why certain emulator files are intentionally excluded. + + Reports: + - Launchers (BIOS managed by standalone emulator) + - Standalone-only files (not needed in libretro mode) + - Frozen snapshots with files: [] (code doesn't load .info firmware) + - Files covered by data_directories + """ + profiles = ( + emu_profiles + if emu_profiles is not None + else load_emulator_profiles(emulators_dir) + ) + platform_systems = set() + for sys_id in config.get("systems", {}): + platform_systems.add(sys_id) + + relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) + notes = [] + for emu_name, profile in sorted(profiles.items()): + emu_systems = set(profile.get("systems", [])) + # Match by core resolution OR system intersection (documents all potential emulators) + if emu_name not in relevant and not (emu_systems & platform_systems): + continue + + emu_display = profile.get("emulator", emu_name) + + if profile.get("type") == "launcher": + notes.append( + { + "emulator": emu_display, + "reason": "launcher", + "detail": profile.get( + "exclusion_note", "BIOS managed by standalone emulator" + ), + } + ) + continue + + # Profile-level exclusion note (frozen snapshots, etc.) + exclusion_note = profile.get("exclusion_note") + if exclusion_note: + notes.append( + { + "emulator": emu_display, + "reason": "exclusion_note", + "detail": exclusion_note, + } + ) + continue + + # Count standalone-only files, but only report as excluded if the + # platform does NOT use this emulator in standalone mode + standalone_set = platform_standalone_set(config) + is_standalone = runs_standalone(emu_name, profile, standalone_set) + if not is_standalone: + standalone_files = [ + f for f in profile.get("files", []) if f.get("mode") == "standalone" + ] + if standalone_files: + names = [f["name"] for f in standalone_files[:3]] + more = ( + f" +{len(standalone_files) - 3}" + if len(standalone_files) > 3 + else "" + ) + notes.append( + { + "emulator": emu_display, + "reason": "standalone_only", + "detail": f"{len(standalone_files)} files for standalone mode only ({', '.join(names)}{more})", + } + ) + + return notes diff --git a/scripts/packverify.py b/scripts/packs/integrity.py similarity index 99% rename from scripts/packverify.py rename to scripts/packs/integrity.py index d5c4398d8..18b7418e1 100644 --- a/scripts/packverify.py +++ b/scripts/packs/integrity.py @@ -10,9 +10,9 @@ from collections import Counter from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict -from verify import DEFAULT_BIOS_DIR +from packs.verdicts import DEFAULT_BIOS_DIR from core.artifacts import _build_timestamp -from packpaths import MEDIA_MARKER, _has_path_conflict +from packs.paths import MEDIA_MARKER, _has_path_conflict from core.ziptools import build_zip_contents_index from core.ziptools import check_inside_zip from resolve.nativemode import digest_algorithm @@ -28,12 +28,12 @@ import io 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 +from packs.extras import platform_region_groups +from packs.paths import _flat from resolve.nativemode import reads_file_contents from resolve import regions as resolve_regions -import slots -from packresolve import resolve_declaration, resolve_file +from packs import slots +from resolve.packfiles import resolve_declaration, resolve_file from resolve.categories import BIOS, EntryCategories from resolve.gamedata import without_game_data from resolve.cores import resolve_platform_cores @@ -615,7 +615,7 @@ def _builder_extras( refuses, is left free, since the builder then places a core's file there: taken by the refused file, that core file was never compared. """ - from packextras import ExtraResolver, hidden_extras + from packs.extras import ExtraResolver, hidden_extras from resolve.validation import _build_validation_index, destination_owners config, emu_profiles = expect.config, expect.emu_profiles diff --git a/scripts/packs/manifest.py b/scripts/packs/manifest.py new file mode 100644 index 000000000..1de539782 --- /dev/null +++ b/scripts/packs/manifest.py @@ -0,0 +1,868 @@ +"""The install manifest of a platform.""" + +from __future__ import annotations + +import contextlib +import io +import os +from collections.abc import Callable, Iterator +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict + +from core.artifacts import _build_timestamp +from core.paths import REPO_ROOT, sanitize_pack_path +from model.declarations import OUTER_ROOTS, declared_root, outer_layout +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from model.registry import load_data_dir_registry +from model.safeparse import yaml_load +from model.systems import platform_system_names +from packs import slots +from packs.archive import CASE_FOLDING_OS, PACK_DOCUMENTS, _Placed, _reject_unknown +from packs.datatrees import ( + _data_directory_members, + _in_data_cache, + _manifest_data_directories, + core_data_trees, + pack_markers, + tree_readers, +) +from packs.extras import ( + _collect_emulator_extras, + extra_region_key, + save_entry_fields, + save_manifest_dest, + undeclared_report, +) +from packs.manifestcores import ( + _downloaded_cores, + _manifest_core_entries, + _manifest_core_index, + _manifest_selection, + _offered_boards, +) +from packs.manifestentry import ( + MANIFEST_OUTER_FIELDS, + _ClaimContext, + _attach_claims, + _manifest_dest_of, + _manifest_entry, + _record_absent, + _record_slot_choices, + _record_unplaceable, +) +from packs.manifestselect import SelectionIndex +from packs.paths import save_layout +from packs.scope import platform_list_version, system_titles +from packs.standalone import _standalone_copies, _standalone_layouts +from resolve.contentlayout import TARGET_KEY +from resolve.cores import filter_systems_by_target, resolve_platform_cores as _platform_cores +from resolve.gamedata import GAME_DATA, is_game_data, platform_game_data, without_game_data +from resolve.nativemode import digest_algorithm, reads_file_contents +from resolve.packfiles import preferred_entries as _preferred_entries, resolve_declaration +from resolve.validation import ( + _build_validation_index, + agnostic_substitute, + baseline_verdict, + destination_owners, + validated_choice, +) + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +if TYPE_CHECKING: + # How a manifest settles a platform declaration: the copy served, or None + # and why not. + _Settle = Callable[[dict, str, str, "str | None"], "tuple[str | None, str]"] + + +class InstallListOptions(TypedDict, total=False): + """The keyword options of generate_install_list, which it hands to + generate_manifest.""" + + emulators_dir: str + zip_contents: dict | None + emu_profiles: dict | None + target_cores: set[str] | None + source: str + regions: list[str] | None + target_name: str | None + offline: bool | None + required_only: bool + data_registry: dict | None + fold_case: bool | None + no_game_data: bool + one_per_slot: bool + + +class ManifestOptions(InstallListOptions, total=False): + """The keyword options of generate_manifest.""" + + known_slot_choices: dict | None + build_out: dict | None + + +@dataclass(frozen=True) +class _ManifestSettings: + """ManifestOptions with their defaults.""" + + emulators_dir: str = "emulators" + zip_contents: dict | None = None + emu_profiles: dict | None = None + target_cores: set[str] | None = None + source: str = "full" + regions: list[str] | None = None + target_name: str | None = None + offline: bool | None = None + required_only: bool = False + data_registry: dict | None = None + fold_case: bool | None = None + no_game_data: bool = False + one_per_slot: bool = False + known_slot_choices: dict | None = None + build_out: dict | None = None + + +@dataclass +class _ManifestBuild: + """One install manifest being listed: its files, omissions and the slots + they take, settled by the rules the pack builder follows.""" + + platform_name: str + platforms_dir: str + db: dict + bios_dir: str + opts: _ManifestSettings + config: dict + emu_profiles: dict + zip_contents: dict + data_registry: dict + game_entries: set[int] + install_section: dict + repo_root: str + pack_systems: dict + manifest_profiles: dict = field(default_factory=dict) + manifest_validation: dict = field(default_factory=dict) + manifest_owners: dict = field(default_factory=dict) + game_destinations: set[str] = field(default_factory=set) + placed: _Placed = field(init=False) + # Destination -> (entry, full destination, manifest destination) of each + # platform file, for the core claims a target build would fall back on. + platform_entries: dict[str, tuple[dict, str, str]] = field(default_factory=dict) + # Full destination -> the platform systems declaring it. A file's + # `systems` also names the systems whose cores read it there. A pack built + # for a target keeps the file only while a declaring system stays. + declared_by: dict[str, set[str]] = field(default_factory=dict) + manifest_files: list[dict] = field(default_factory=list) + omitted_by_destination: dict[str, dict] = field(default_factory=dict) + total_size: int = 0 + # Sizes of the files the pack carries and the installer cannot fetch: the + # collection does not index them, a data directory cache answered. + pack_only_sizes: list[int] = field(default_factory=list) + # Platform entries resolved into a data directory cache: destination -> + # (cache file, size). Settled once the trees are walked. + cache_held: dict[str, tuple[str, int]] = field(default_factory=dict) + rename_notes: set[str] = field(default_factory=set) + slot_choices: dict = field(default_factory=dict) + slot_overrides: dict[str, str] = field(default_factory=dict) + undeclared: list[dict] | None = None + region_drops: set[str] = field(default_factory=set) + selection: SelectionIndex | None = None + builder_held: set[str] = field(default_factory=set) + declarations: dict[str, dict[str, list[dict]]] = field(default_factory=dict) + data_members: list[tuple[str, str]] = field(default_factory=list) + data_directories: list[dict] = field(default_factory=list) + + def __post_init__(self) -> None: + self.placed = _Placed(self.case_insensitive) + + @property + def base_dest(self) -> str: + return self.config.get("base_destination", "") + + @property + def case_insensitive(self) -> bool: + return self.config.get("case_insensitive_fs", False) + + @property + def verification_mode(self) -> str: + return self.config.get("verification_mode", "existence") + + @property + def fields(self) -> SelectionIndex: + assert self.selection is not None + return self.selection + + def manifest_destination(self, full_destination: str) -> str: + return _manifest_dest_of(full_destination, self.base_dest) + + def record_omission( + self, + full_destination: str, + file_entry: dict, + system_id: str, + reason: str, + cores: list[str] | None, + ) -> None: + # A core extra (cores given) is keyed as the region pass keys it. + bare = ( + sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) + if cores is None else extra_region_key(file_entry, declared_root(self.config)) + ) + self.omitted_by_destination[full_destination] = { + **self._omission_dest(full_destination, file_entry), + "name": str(file_entry.get("name") or ""), + "system": system_id, + "required": bool(file_entry.get("required", True)), + "reason": reason, + "cores": cores, + # An omission keeps its region groups, as the builder groups it: + # a requested file the collection lacks answers the request + # without displacing a held fallback (resolve_region_drops, + # held). One the builder holds and the installer cannot fetch + # does displace it in the pack, so it says so, and the installer + # drops the same fallback. + **self.fields.fields(bare, str(file_entry.get("name") or "")), + **({"held": True} if bare in self.builder_held else {}), + **( + {"category": GAME_DATA} + if (bare in self.game_destinations if cores is None else is_game_data(file_entry)) + else {} + ), + } + + def _omission_dest(self, full_destination: str, file_entry: dict) -> dict: + # Read in the emulator's own folder, outside the BIOS tree: dest is + # the path the emulator reads, relative to that folder. + if file_entry.get("unplaced"): + return {"dest": sanitize_pack_path(file_entry.get("path") or ""), + "root": "emulator"} + if file_entry.get("root") in OUTER_ROOTS: + return {"dest": sanitize_pack_path( + file_entry.get("destination") or file_entry.get("path") or "" + ), "root": file_entry["root"]} + if file_entry.get("root") == "save": + return {"dest": save_manifest_dest(file_entry), **save_entry_fields(file_entry)} + return {"dest": self.manifest_destination(full_destination)} + + def kept_declarations(self) -> Iterator[tuple[str, dict, str, str]]: + """(system, entry, destination, full destination) of each platform + declaration this manifest keeps, in the builder's order.""" + opts = self.opts + for sys_id, system in sorted(self.pack_systems.items()): + for file_entry in system.get("files", []): + if opts.required_only and file_entry.get("required") is False: + continue + dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) + if not dest: + continue + if self.region_drops and dest in self.region_drops: + continue + full_dest = f"{self.base_dest}/{dest}" if self.base_dest else dest + yield sys_id, file_entry, dest, full_dest + + def declaration_order(self, full_dest: str) -> list[tuple[list[str], dict, str]]: + """The declarations answering a destination as its systems drop. + + A pack built for a target loses the systems no available core + reads, and the next declaration takes the destination by the + same rule: RetroArch's bare nintendo-ds dsi_bios9.bin once the + pinned nintendo-dsi one is gone. + """ + remaining = dict(self.declarations.get(full_dest, {})) + order: list[tuple[list[str], dict, str]] = [] + while remaining: + winner = _preferred_entries( + {sid: {"files": fes} for sid, fes in remaining.items()}, + self.db, self.bios_dir, self.base_dest, self.opts.required_only, + self.zip_contents, self.opts.offline, + ).get(full_dest) + first_sys, first = next( + (sid, fe) for sid, fes in sorted(remaining.items()) for fe in fes + if winner is None or id(fe) == winner + ) + systems = sorted( + sid for sid, fes in remaining.items() + if any(fe is first for fe in fes) + ) + order.append((systems, first, first_sys)) + for sid in systems: + del remaining[sid] + return order + + def list_baseline(self, settle: _Settle) -> None: + """Phase 1: the platform's own files.""" + # The same destination can be declared by more than one system, bare + # in one and hash-constrained in another. The builder lets the + # constrained sibling claim it. Without the same rule here the + # manifest named whatever answered to the name, so the pack and the + # installer disagreed about which file a destination means. + # Decided among the declarations this manifest keeps, as the pack + # does. A manifest carries no data directories. + preferred_entries = _preferred_entries( + self.pack_systems, self.db, self.bios_dir, self.base_dest, + self.opts.required_only, self.zip_contents, self.opts.offline, + ) + for sys_id, file_entry, _dest, full_dest in self.kept_declarations(): + self.declarations.setdefault(full_dest, {}).setdefault(sys_id, []).append( + file_entry + ) + for sys_id, file_entry, dest, full_dest in self.kept_declarations(): + self.declared_by.setdefault(full_dest, set()).add(sys_id) + preferred = preferred_entries.get(full_dest) + if preferred is not None and id(file_entry) != preferred: + continue + if self.placed.holds(full_dest) or self.placed.conflicts(full_dest): + continue + if file_entry.get("storage", "embedded") == "user_provided": + self._list_instructions(file_entry, sys_id, full_dest) + continue + local_path, status = settle( + file_entry, sys_id, dest, self.slot_overrides.get(full_dest) + ) + if local_path is None: + self.record_omission(full_dest, file_entry, sys_id, status, None) + continue + self._list_declared(file_entry, sys_id, dest, full_dest, local_path, settle) + + def _list_instructions(self, file_entry: dict, sys_id: str, full_dest: str) -> None: + self.record_omission( + full_dest, + file_entry, + sys_id, + "user_provided", + None, + ) + # The pack writes the instructions in the slot's place + # and holds it: one more member than the files listed. + instructions = file_entry.get( + "instructions", "Please provide this file manually." + ) + self.pack_only_sizes.append(len( + f"File needed: {file_entry['name']}\n\n{instructions}\n".encode() + )) + self.placed.take(full_dest) + + def _list_declared( + self, + file_entry: dict, + sys_id: str, + dest: str, + full_dest: str, + local_path: str, + settle: _Settle, + ) -> None: + entry, file_size = _manifest_entry( + local_path, dest, None, self.db, self.repo_root, + self.fields.fields(dest, file_entry["name"]), + ) + if entry is not None and dest in self.game_destinations: + entry["category"] = GAME_DATA + if entry is not None and self.opts.target_cores is None: + order = self.declaration_order(full_dest) + if full_dest in self.slot_choices or len(order) > 1: + _record_slot_choices( + entry, self.slot_choices.get(full_dest, []), order, + settle, dest, self.db, self.repo_root, + ) + if entry is None: + self.record_omission(full_dest, file_entry, sys_id, "not_found", None) + if file_size and full_dest not in self.placed.destinations: + if _in_data_cache(local_path, self.data_registry): + self.cache_held[full_dest] = (local_path, file_size) + else: + self.pack_only_sizes.append(file_size) + self.placed.take(full_dest) + return + + self.manifest_files.append(entry) + self.platform_entries[full_dest] = (entry, full_dest, dest) + self.omitted_by_destination.pop(full_dest, None) + self.total_size += file_size + self.placed.take(full_dest) + + def claim_context(self) -> _ClaimContext: + return _ClaimContext( + self.db, self.bios_dir, self.zip_contents, self.opts.offline, + self.opts.required_only, self.manifest_validation, self.manifest_owners, + self.repo_root, self.data_registry, + ) + + def list_core_files(self) -> None: + """Phase 2: core complement (emulator extras).""" + opts = self.opts + unplaceable: list[dict] = [] + baseline_claims: dict[str, dict] = {} + absent: list[dict] = [] + if opts.source != "platform": + core_files = _collect_emulator_extras( + self.config, + opts.emulators_dir, + self.db, + self.placed.destinations, + self.base_dest, + self.emu_profiles, + target_cores=opts.target_cores, + include_all=(opts.source == "truth"), + unplaceable=unplaceable, + baseline_claims=baseline_claims, + absent=absent, + undeclared=self.undeclared, + ) + else: + core_files = [] + _record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles) + _record_absent( + absent, self.config, self.base_dest, self.region_drops, opts.required_only, + self.placed.destinations, self.omitted_by_destination, self.record_omission, + ) + self.total_size += _manifest_core_entries( + core_files, self.config, self.db, self.bios_dir, self.base_dest, self.repo_root, + self.zip_contents, opts.offline, + region_drops=self.region_drops, case_insensitive=self.case_insensitive, + seen_destinations=self.placed.destinations, seen_lower=self.placed.lower, + seen_parents=self.placed.parents, manifest_files=self.manifest_files, + omitted_by_destination=self.omitted_by_destination, + record_omission=self.record_omission, pack_only_sizes=self.pack_only_sizes, + selection=self.fields, required_only=opts.required_only, + validation_index=self.manifest_validation, owners=self.manifest_owners, + data_registry=self.data_registry, profiles=self.emu_profiles, + ) + self._settle_claims(baseline_claims) + + def _settle_claims(self, baseline_claims: dict[str, dict]) -> None: + ctx = self.claim_context() + for key, (entry, full_dest, dest) in self.platform_entries.items(): + declared = self.declared_by.get(full_dest, set()) + if declared and declared != set(entry.get("systems") or []): + entry["declared_in"] = sorted(declared) + claims = baseline_claims.get(key, {}).get("other_claims") + if claims and any(not is_game_data(claim) for claim in claims): + # A core reads this path as firmware: a pack without game data + # still fills it. + entry.pop("category", None) + if claims: + _attach_claims(entry, claims, ctx, dest, dest) + # A platform omission narrows like a platform file: by the systems + # declaring it, which can be fewer than the ones whose cores read it. + for full_dest, omission in self.omitted_by_destination.items(): + declared = self.declared_by.get(full_dest, set()) + if ( + omission.get("cores") is None + and declared + and declared != set(omission.get("systems") or []) + ): + omission["declared_in"] = sorted(declared) + + def list_data_directories(self) -> list[int]: + """Phase 3: data directories, and the sizes the pack alone holds. + + They are not files of the collection: the installer fetches each + from its source archive and keeps the members whose hash the list + below records, the same tree the pack carries. + """ + opts = self.opts + required_only = opts.required_only + data_refs: dict[str, tuple[str, tuple[str, ...], str, bool]] = {} + reclaim = {full: path for full, (path, _size) in self.cache_held.items()} + core_trees = ([] if opts.source == "platform" + else core_data_trees(self.config, self.emu_profiles, self.platform_name, + self.data_registry, opts.target_cores)) + self.data_members = list(_data_directory_members( + self.pack_systems, self.data_registry, self.platform_name, self.base_dest, + self.case_insensitive, self.placed.destinations, self.placed.lower, + self.placed.parents, refs_out=data_refs, required_only=required_only, + core_trees=core_trees, + reclaim=reclaim, + )) + # A platform entry found in a tree the pack carries is that tree's member: + # the installer rebuilds it from the tree's archive. One found in a tree + # the pack does not carry stays omitted, held by the pack alone. + for full_dest, (_path, size) in self.cache_held.items(): + if full_dest in reclaim: + self.pack_only_sizes.append(size) + else: + self.omitted_by_destination.pop(full_dest, None) + self.data_directories = _manifest_data_directories( + self.data_members, data_refs, self.data_registry or {}, self.base_dest, + tree_readers(self.pack_systems, core_trees), self.pack_systems, + ) + return self.pack_only_sizes + [os.path.getsize(src) for src, _dest in self.data_members] + + def result(self, data_sizes: list[int]) -> dict: + opts, config, pack_systems = self.opts, self.config, self.pack_systems + manifest_files, platform_name = self.manifest_files, self.platform_name + omitted = self.omitted_by_destination + # The pack is unzipped into the BIOS folder: an entry the installer puts + # in the roms, emulators or configs folder is in its list, not in the ZIP. + outer = [e for e in manifest_files if e.get("root") in OUTER_ROOTS] + core_names, system_cores = _manifest_core_index( + config, self.emu_profiles, manifest_files, list(omitted.values()) + ) + result: dict = { + "manifest_version": 2, + "source": opts.source, + "regions": list(opts.regions or []), + # A target-filtered manifest is only distinguishable from the full one + # by its filename, so it records the filter the way regions does. + # Absent on an unfiltered manifest rather than empty, to leave the + # twelve default files byte-identical. + **({"target": opts.target_name} if opts.target_name else {}), + # Every game data file below says so: the installer's --no-game-data + # relies on it, and refuses a list that does not record categories. + "categorized": True, + # The entries a slot decides carry `slot`, which --one-per-slot + # reads: without this mark the installer refuses it. + "slot_fields": True, + **({"no_game_data": True} if opts.no_game_data else {}), + "platform": platform_name, + "display_name": config.get("platform", platform_name), + "version": platform_list_version(config, platform_name), + "generated": _build_timestamp(self.db), + "base_destination": self.base_dest, + "detect": self.install_section.get("detect", []), + "standalone_copies": _standalone_copies( + self.install_section.get("standalone_copies", []), self.manifest_profiles, + manifest_files, + ), + "total_files": len(manifest_files), + "total_size": self.total_size, + "pack_files": ( + len(manifest_files) - len(outer) + len(data_sizes) + len(PACK_DOCUMENTS) + + len(self.rename_notes) + + len(pack_markers(platform_name, opts.target_name, self.platforms_dir)) + ), + "pack_size": self.total_size - sum(int(e.get("size") or 0) for e in outer) + + sum(data_sizes), + "total_omitted": len(omitted), + "omitted_files": sorted( + omitted.values(), key=lambda entry: entry["dest"] + ), + "core_names": core_names, + **({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores( + config, self.emu_profiles, core_names, self.platforms_dir, + )) else {}), + **({"offered_boards": offered} if (offered := _offered_boards( + config, self.emu_profiles, core_names, + [*manifest_files, *omitted.values()], + )) else {}), + "system_cores": system_cores, + # The names the platform itself gives its systems (Batocera's psx), + # which --system accepts beside the ids. + "system_names": platform_system_names(config, list(pack_systems)), + "system_titles": system_titles(manifest_files, omitted.values()), + "files": manifest_files, + } + if self.data_directories: + result["data_directories"] = self.data_directories + self._outer_directories(result) + return result + + def _outer_directories(self, result: dict) -> None: + for root in OUTER_ROOTS: + layout = outer_layout(self.config, root) or {} + if layout and any(entry.get("root") == root + for entry in [*self.manifest_files, *result["omitted_files"]]): + # Where the installer finds the folder: relative to the folder + # holding the BIOS folder, which the platform names bios_folder. + result[f"{root}_directory"] = { + key: layout[key] for key in MANIFEST_OUTER_FIELDS if key in layout + } + saved = [entry for entry in self.manifest_files if entry.get("root") == "save"] + if saved: + save = save_layout(self.config) + result["save_directory"] = {"folder": save.folder, "by_core": save.by_core} + if save.by_system: + # The launcher writes the directory at each launch, one folder + # per system: each dest starts with that folder. + result["save_directory"]["by_system"] = True + + +def _start_manifest( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + registry_path: str, + opts: _ManifestSettings, +) -> tuple[_ManifestBuild, dict]: + """The manifest's configuration and scope, and the profiles before the + game data cut.""" + config = load_platform_config(platform_name, platforms_dir) + if opts.fold_case is not None: + config = {**config, "case_insensitive_fs": opts.fold_case} + if opts.target_name: + config = {**config, TARGET_KEY: opts.target_name} + zip_contents = {} if opts.zip_contents is None else opts.zip_contents + emu_profiles = opts.emu_profiles + if emu_profiles is None: + emu_profiles = load_emulator_profiles(opts.emulators_dir) + data_registry = opts.data_registry + if data_registry is None: + data_registry = load_data_dir_registry(platforms_dir) + full_profiles = emu_profiles + game_entries: set[int] = set() + if opts.no_game_data: + cut = without_game_data(config, emu_profiles, data_registry, opts.target_cores) + config, emu_profiles = cut.config, cut.profiles + else: + game_entries = platform_game_data(config, emu_profiles, data_registry) + + # Load registry for install metadata + registry: dict = {} + if os.path.exists(registry_path): + with open(registry_path) as f: + registry = yaml_load(f) or {} + plat_registry = registry.get("platforms", {}).get(platform_name, {}) + + plat_cores = _platform_cores(config, emu_profiles) if opts.target_cores else None + pack_systems = filter_systems_by_target( + config.get("systems", {}), + emu_profiles, + opts.target_cores, + platform_cores=plat_cores, + ) + build = _ManifestBuild( + platform_name, platforms_dir, db, bios_dir, opts, config, emu_profiles, + zip_contents, data_registry, game_entries, plat_registry.get("install", {}), + str(REPO_ROOT), pack_systems, + ) + build.manifest_profiles = { + name: emu_profiles[name] + for name in _platform_cores(config, emu_profiles) + } + build.manifest_validation = _build_validation_index(build.manifest_profiles) + build.manifest_owners = destination_owners(build.manifest_profiles) + _settle_manifest_scope(build) + return build, full_profiles + + +def _settle_manifest_scope(build: _ManifestBuild) -> None: + """Game data destinations, slot choices and the region selection.""" + opts, config, emu_profiles = build.opts, build.config, build.emu_profiles + # A destination is game data when every declaration of it is: a firmware + # declaration of the same path keeps it in a pack built without game data. + declared_kinds: dict[str, set[bool]] = {} + for system in build.pack_systems.values(): + for fe in system.get("files", []): + bare = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) + if bare: + declared_kinds.setdefault(bare, set()).add(id(fe) in build.game_entries) + build.game_destinations = {d for d, kinds in declared_kinds.items() if kinds == {True}} + + # The full manifest records every core's answer at a contested slot, so a + # target narrowed from it gets what that target's own pack serves. + whole = opts.target_cores is None and opts.source != "platform" and bool(emu_profiles) + # The truth list read inside this run takes the choices already made. + build.slot_choices = ( + opts.known_slot_choices if opts.known_slot_choices is not None and whole + else slots.slot_choices(config, emu_profiles, build.db, build.zip_contents, + build.data_registry) + if whole else {} + ) + # Derived from the same choices: computed twice, it was 8% of a run. + build.slot_overrides = slots.pack_overrides( + config, emu_profiles, build.db, build.zip_contents, build.data_registry, + target_cores=opts.target_cores, source=opts.source, + choices=build.slot_choices if whole else None, + ) + + # Read by the region grouping and by phase 2 with the same arguments. + build.undeclared = ( + undeclared_report( + config, opts.emulators_dir, build.db, emu_profiles, opts.target_cores, + include_all=(opts.source == "truth"), + ) + if opts.source != "platform" + else None + ) + build.region_drops, build.selection, build.builder_held = _manifest_selection( + config, build.pack_systems, opts.emulators_dir, build.db, build.base_dest, + emu_profiles, opts.target_cores, opts.source, + required_only=opts.required_only, regions=opts.regions, + undeclared=build.undeclared, zip_contents=build.zip_contents, + data_registry=build.data_registry, slot_overrides=build.slot_overrides, + one_per_slot=opts.one_per_slot, + ) + + +def generate_manifest( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + registry_path: str, + **options: Unpack[ManifestOptions], +) -> dict: + """Generate a JSON manifest for a platform (same resolution as generate_pack). + + Returns a dict ready for JSON serialization with file inventory, + install hints, and download metadata. ``fold_case`` overrides the + platform's ``case_insensitive_fs``, for the case variants below. + + A file that is a game's data, not firmware, carries ``"category": + "game_data"``, so the installer can leave it out as the builder does + under ``no_game_data``. Firmware carries no category. + One build: generate_install_list adds what --source truth and + --standalone read. `build_out` receives the slot choices and the + profiles this build read, which that second build takes over. + """ + _reject_unknown("generate_manifest", options, ManifestOptions.__optional_keys__) + opts = _ManifestSettings(**options) + build, full_profiles = _start_manifest( + platform_name, platforms_dir, db, bios_dir, registry_path, opts + ) + config, verification_mode = build.config, build.verification_mode + + def settle( + file_entry: dict, sys_id: str, dest: str, override: str | None + ) -> tuple[str | None, str]: + """The file served once the slot is settled, or None and why not.""" + local_path, status = resolve_declaration( + file_entry, + db, + bios_dir, + build.zip_contents, + build.data_registry, + override, + offline=opts.offline, + ) + if status == "not_found" and not reads_file_contents(verification_mode): + found = agnostic_substitute(file_entry, sys_id, db, build.manifest_profiles) + if found: + local_path, status = found[0], "agnostic_fallback" + if os.path.basename(local_path) != file_entry.get("name", ""): + # The pack explains the rename in a note of its own. + build.rename_notes.add(file_entry.get("name", "")) + # The builder's verdict: a hash platform omits what its frontend + # would reject, a zipped_file archive included when the member is + # missing whatever the outer resolution said. An existence + # platform never reads the bytes. + status, refusal = baseline_verdict( + file_entry, local_path, status, verification_mode, + config.get("hash_rule", ""), + ) + if refusal or status in ("not_found", "external"): + return None, "hash_mismatch" if refusal else status + # The variant the pack ships when an emulator rejects the + # resolved file: the installer must place the same bytes. + local_path, _disagreement = validated_choice( + file_entry, local_path, db, build.manifest_validation, bios_dir, + digest_algorithm(verification_mode), dest, build.manifest_owners, + ) + return local_path, status + + if opts.source != "truth": + build.list_baseline(settle) + build.list_core_files() + result = build.result(build.list_data_directories()) + detect = build.install_section.get("detect", []) + if build.case_insensitive and opts.fold_case is None and any( + d.get("os") not in CASE_FOLDING_OS for d in detect + ): + # RetroArch also runs where case is kept: there Mesen-CE opens + # bios.col and np2kai np2kai/2608_bd.wav, which the folded list + # serves only as BIOS.col and 2608_BD.WAV. The installer adds these + # where the directory keeps case, while the pack, extracted on Windows + # or macOS too, stays folded. + kept = generate_manifest( + platform_name, platforms_dir, db, bios_dir, registry_path, + emulators_dir=opts.emulators_dir, zip_contents=build.zip_contents, + emu_profiles=full_profiles, target_cores=opts.target_cores, source=opts.source, + regions=opts.regions, target_name=opts.target_name, offline=opts.offline, + required_only=opts.required_only, data_registry=build.data_registry, + fold_case=False, no_game_data=opts.no_game_data, + ) + folded = {entry["dest"] for entry in build.manifest_files} + folded_lower = {dest.lower() for dest in folded} + variants = [ + entry for entry in kept["files"] + if entry["dest"] not in folded and entry["dest"].lower() in folded_lower + ] + if variants: + result["case_variants"] = variants + if opts.build_out is not None: + opts.build_out.update(slot_choices=build.slot_choices, profiles=build.manifest_profiles) + return result + + +def generate_install_list( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + registry_path: str, + standalone_out: dict | None = None, + **options: Unpack[InstallListOptions], +) -> dict: + """The list install.py reads: the full manifest, the files and omissions + the --source truth build holds apart from it, and the emulators with a + standalone build. `standalone_out` receives, per such emulator, what + `--emulator X --standalone` packs, written apart from the list + (install/standalone/.json) and fetched only by a run given + --standalone. + + A manifest narrowed by a target, a case fold or --one-per-slot is no + list install.py reads by default and gets neither. + """ + settings = _ManifestSettings(**options) + built: dict = {} + result = generate_manifest(platform_name, platforms_dir, db, bios_dir, registry_path, + build_out=built, **options) + if (settings.source != "full" or settings.target_cores is not None + or settings.fold_case is not None or settings.one_per_slot): + return result + truth_options: InstallListOptions = {**options, "source": "truth"} + with contextlib.redirect_stdout(io.StringIO()): + truth = generate_manifest( + platform_name, platforms_dir, db, bios_dir, registry_path, + **truth_options, known_slot_choices=built["slot_choices"], + ) + _mark_truth(result, truth) + layouts = _standalone_layouts( + built["profiles"], settings.emulators_dir, db, bios_dir, + settings.zip_contents or {}, settings.offline, platforms_dir, result, + ) + if layouts: + result["standalone_builds"] = sorted(layouts) + if standalone_out is not None: + standalone_out.update(layouts) + return result + + +def _truth_key(entry: dict) -> tuple: + """What tells one entry from another, as the installer's _entry_key.""" + root = entry.get("root") + cores = tuple(entry.get("cores") or []) if root == "emulator" else () + return (str(entry.get("dest")), root, cores) + + +def _mark_truth(result: dict, truth: dict) -> None: + """What `--source truth` installs, carried in the full list. + + The truth list holds what the emulator profiles prove is read. A file of + the full list it does not hold, by destination and content, is marked + `"truth": false`, and what only the truth list holds is `truth_files`. + Omissions compare by destination. The installer then rebuilds the + truth list from the full one, and a list without `truth_files` is one + published before, on which `--source truth` is refused. + """ + held = {(_truth_key(entry), entry.get("sha1")) for entry in truth["files"]} + full = {(_truth_key(entry), entry.get("sha1")) for entry in result["files"]} + for entry in result["files"]: + if (_truth_key(entry), entry.get("sha1")) not in held: + entry["truth"] = False + result["truth_files"] = [ + entry for entry in truth["files"] + if (_truth_key(entry), entry.get("sha1")) not in full + ] + absent = {_truth_key(entry) for entry in truth["omitted_files"]} + listed = {_truth_key(entry) for entry in result["omitted_files"]} + for entry in result["omitted_files"]: + if _truth_key(entry) not in absent: + entry["truth"] = False + result["truth_omitted"] = [ + entry for entry in truth["omitted_files"] if _truth_key(entry) not in listed + ] diff --git a/scripts/packs/manifestcores.py b/scripts/packs/manifestcores.py new file mode 100644 index 000000000..d705ad5aa --- /dev/null +++ b/scripts/packs/manifestcores.py @@ -0,0 +1,464 @@ +"""The manifest's core entries and the scope a manifest selects.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict + +from core.paths import sanitize_pack_path +from model.alternatives import core_file_spares +from model.declarations import OUTER_ROOTS, ROMS_ROOT, declared_root +from model.profiles import upstream_profile_index +from model.targets import list_available_targets, load_target_config +from packs.archive import _reject_unknown +from packs.extras import ( + ExtraResolver, + _detect_extras_prefix, + _extra_system_ids, + extra_full_destination, + extra_region_key, + platform_region_groups, + save_entry_fields, + save_manifest_dest, +) +from packs.manifestentry import ( + _ClaimContext, + _attach_claims, + _claim_cores, + _claim_platform_omission, + _manifest_dest_of, + _manifest_entry, +) +from packs.manifestselect import SelectionIndex +from packs.paths import _register_path, placement_block +from packs.platformpack import _slot_drops +from resolve import regions as resolve_regions, slot as slot_mod +from resolve.contentlayout import TARGET_KEY, _core_key, content_folder_boards +from resolve.cores import ( + downloadable_on, + downloaded_only_profiles, + resolve_platform_cores as _platform_cores, + system_core_reach, +) +from resolve.gamedata import GAME_DATA, is_game_data + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +class _CoreEntryState(TypedDict): + """What _manifest_core_entries reads and fills of the manifest being listed.""" + + region_drops: set + case_insensitive: bool + seen_destinations: set + seen_lower: set + seen_parents: set + manifest_files: list + omitted_by_destination: dict + record_omission: Callable[..., None] + pack_only_sizes: list[int] + selection: SelectionIndex + + +class _CoreEntryParts(_CoreEntryState, total=False): + """_CoreEntryState and the optional keywords of _manifest_core_entries.""" + + required_only: bool + validation_index: dict | None + owners: dict | None + data_registry: dict | None + profiles: dict | None + + +@dataclass +class _CoreEntryLister: + """Lists a platform's core extras into the manifest, one at a time.""" + + config: dict + base_dest: str + ctx: _ClaimContext + state: _CoreEntryParts + resolver: ExtraResolver + total_size: int = 0 + extras_pfx: str = field(init=False) + + def __post_init__(self) -> None: + self.extras_pfx = _detect_extras_prefix(self.config, self.base_dest) + + def region_key(self, fe: dict) -> str: + return extra_region_key(fe, declared_root(self.config)) + + def region_dropped(self, fe: dict) -> bool: + drops = self.state["region_drops"] + return bool(drops) and self.region_key(fe) in drops + + def list_extra(self, fe: dict) -> None: + state = self.state + dest = sanitize_pack_path(fe.get("destination", fe["name"])) + if not dest: + return + region_key = self.region_key(fe) + if state["region_drops"] and region_key in state["region_drops"]: + return + full_dest = extra_full_destination(fe, self.extras_pfx) + if not full_dest: + return + + if ( + state["case_insensitive"] + and full_dest not in state["seen_destinations"] + and full_dest.lower() in state["seen_lower"] + ): + self._join_spelling(fe, full_dest, dest) + return + + if placement_block( + full_dest, state["seen_destinations"], state["seen_lower"], state["seen_parents"], + state["case_insensitive"], + ): + return + + # The builder's own lookup (ExtraResolver): the data directories, the + # copy the emulator accepts, and the size its code checks. Without + # the data directories blueMSX's MSX2P.rom named a different dump + # than the one its pack carried. + local_path, status, _disagreement = self.resolver.resolve(fe, dest) + if not local_path: + self._omit(fe, full_dest, status) + return + self._list_held(fe, dest, full_dest, region_key, local_path) + + def _join_spelling(self, fe: dict, full_dest: str, dest: str) -> None: + # One file under two spellings: BlastEm opens 32X_M_BIOS.bin and + # PicoDrive 32X_M_BIOS.BIN. The second core's claim joins the + # entry kept, or a pack built without the first core loses the + # file the installer would still have to place. Collisions are + # rare, so the entry is looked up only when one happens. + save_root = fe.get("root") == "save" + folded = ( + save_manifest_dest(fe) if save_root + else _manifest_dest_of(full_dest, self.base_dest) + ).lower() + held = next( + (e for e in self.state["manifest_files"] + if e["dest"].lower() == folded + and (e.get("root") == "save") == save_root), + None, + ) + if held is not None and held.get("cores") is not None: + _attach_claims(held, [fe], self.ctx, dest, held["dest"]) + + def _omit(self, fe: dict, full_dest: str, reason: str) -> None: + source_emu = fe.get("source_profile") or fe.get("source_emulator", "") + if not _claim_platform_omission( + self.state["omitted_by_destination"].get(full_dest), source_emu + ): + systems = _extra_system_ids(fe) + self.state["record_omission"]( + full_dest, fe, systems[0] if systems else "", reason, _claim_cores(fe), + ) + + def _list_held( + self, fe: dict, dest: str, full_dest: str, region_key: str, local_path: str, + ) -> None: + state = self.state + source_emu = fe.get("source_profile") or fe.get("source_emulator", "") + save_root = fe.get("root") == "save" + + # Manifest dests are relative to base_destination. Keep the inferred + # extras prefix when it is an internal layout dir (RetroDECK bios/). + # A file read below the save directory is written relative to the + # directory the core is handed, and says so (save_entry_fields). + outer_root = fe.get("root") if fe.get("root") in OUTER_ROOTS else None + if save_root: + manifest_dest = save_manifest_dest(fe) + elif outer_root: + # Relative to the roms or emulators folder the entry names. + manifest_dest = dest + else: + manifest_dest = _manifest_dest_of(full_dest, self.base_dest) + + entry, file_size = _manifest_entry( + local_path, manifest_dest, [source_emu] if source_emu else [], + self.ctx.db, self.ctx.repo_root, + state["selection"].fields(region_key, fe.get("name", "")), + ) + if entry is not None and save_root: + entry.update(save_entry_fields(fe)) + elif entry is not None and outer_root: + entry["root"] = outer_root + if entry is None: + self._omit(fe, full_dest, "not_found") + if file_size: + state["pack_only_sizes"].append(file_size) + return + + if is_game_data(fe) and all( + is_game_data(claim) for claim in fe.get("other_claims", []) + ): + entry["category"] = GAME_DATA + _attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest) + + state["manifest_files"].append(entry) + displaced = state["omitted_by_destination"].pop(full_dest, None) + if displaced and displaced.get("cores"): + # A core that wants this slot and has nothing held: a pack built + # without the cores served here leaves the slot to it, missing, + # and the installer narrowing to those cores has to say so too. + entry.setdefault("absent_claims", []).append( + {k: v for k, v in displaced.items() if k not in ("dest", "held")} + ) + self.total_size += file_size + state["seen_destinations"].add(full_dest) + _register_path(full_dest, state["seen_destinations"], state["seen_parents"]) + if state["case_insensitive"]: + state["seen_lower"].add(full_dest.lower()) + + +def _manifest_core_entries( + core_files: list, + config: dict, + db: dict, + bios_dir: str, + base_dest: str, + repo_root: str, + zip_contents: dict | None, + offline: bool | None, + **state: Unpack[_CoreEntryParts], +) -> int: + """Add the files a platform's cores need but its list does not name. + + The installer fetches by hash, so an entry records the copy this + repository holds rather than the value the profile declares: an + upstream hash carried by no local file leaves the entry with no URL. + Returns the bytes added. + """ + _reject_unknown( + "_manifest_core_entries", state, + _CoreEntryParts.__required_keys__ | _CoreEntryParts.__optional_keys__, + ) + required_only = state.get("required_only", False) + ctx = _ClaimContext( + db, bios_dir, zip_contents, offline, required_only, + state.get("validation_index"), state.get("owners"), repo_root, + state.get("data_registry"), + ) + lister = _CoreEntryLister( + config, base_dest, ctx, state, + ExtraResolver( + db, bios_dir, zip_contents, ctx.data_registry, ctx.validation_index or {}, + ctx.owners, offline, profiles=state.get("profiles"), + ), + ) + spares = core_file_spares(core_files, lister.region_dropped) if required_only else set() + for fe in core_files: + if required_only and (fe.get("required") is False or id(fe) in spares): + continue + lister.list_extra(fe) + return lister.total_size + + +class _SelectionOptions(TypedDict, total=False): + """The keyword options of _manifest_selection.""" + + required_only: bool + regions: list[str] | None + undeclared: list[dict] | None + zip_contents: dict | None + data_registry: dict | None + slot_overrides: dict[str, str] | None + one_per_slot: bool + + +def _manifest_selection( + config: dict, + pack_systems: dict, + emulators_dir: str, + db: dict, + base_dest: str, + emu_profiles: dict, + target_cores: set[str] | None, + source: str, + **options: Unpack[_SelectionOptions], +) -> tuple[set[str], SelectionIndex, set[str]]: + """Destinations a region list and --one-per-slot remove, the groups the + installer replays, and the destinations the builder holds. + + Grouped as the pack groups them, so a region or a slot the installer + decides on the full manifest withdraws what `--region` and + `--one-per-slot` withdraw from the pack. + """ + _reject_unknown("_manifest_selection", options, _SelectionOptions.__optional_keys__) + required_only = options.get("required_only", False) + regions = options.get("regions") + one_per_slot = options.get("one_per_slot", False) + extras: list[dict] = [] + held: set[str] = set() + region_groups, _extra_dests = platform_region_groups( + config, + pack_systems, + emulators_dir, + db, + base_dest, + emu_profiles, + target_cores=target_cores, + include_extras=(source != "platform"), + include_all=(source == "truth"), + required_only=required_only, + extras_out=extras, + held_out=held, + undeclared=options.get("undeclared"), + zip_contents=options.get("zip_contents"), + data_registry=options.get("data_registry"), + slot_overrides=options.get("slot_overrides"), + ) + region_index = resolve_regions.platform_region_index( + config, emu_profiles, target_cores + ) + drops = ( + resolve_regions.resolve_region_drops(region_groups, region_index, regions, held) + if regions + else set() + ) + if one_per_slot: + drops = drops | _slot_drops( + config, emu_profiles, target_cores, region_groups, drops, held + )[0] + return drops, SelectionIndex.build( + region_groups, region_index, pack_systems, extras, required_only, + extras_prefix=declared_root(config), + slot_claims=slot_mod.platform_slot_claims(config, emu_profiles, target_cores), + ), held + + +def _offered_boards( + config: dict, + profiles: dict[str, dict], + core_names: dict[str, list[str]], + entries: list[dict], +) -> dict[str, list[dict]]: + """The roms folders each profile is offered for on some boards only, + each with those boards, aliases included, where the manifest places a + file of that profile. + + ROCKNIX writes uae4arm for roms/amiga under the devices it builds it for + (emulators/package.mk:188), and a board's core list names uae4arm when + another folder offers it there. The pack builder reads the board from + the config (TARGET_KEY) and `install.py --target` reads its answer here. + A manifest built for one board needs none. + """ + if config.get(TARGET_KEY): + return {} + pairs = content_folder_boards(config) + if all(on is None for on in pairs.values()): + return {} + from resolve.launchers import _roms_place + + by_key: dict[str, set[str]] = {} + for name, claimants in upstream_profile_index(profiles).items(): + by_key.setdefault(_core_key(name), set()).update(claimants) + free = { + (profile, folder) for (core, folder), on in pairs.items() if on is None + for profile in by_key.get(core, ()) + } + found: dict[tuple[str, str, str], set[str]] = {} + for (core, folder), on in pairs.items(): + where = _roms_place(config, folder) if on is not None else None + if where is None: + continue + for profile in by_key.get(core, ()): + if profile in core_names and (profile, folder) not in free: + found.setdefault((profile, where[0], where[1]), set()).update(on) + # An entry below the roms root names it, one in the install tree none. + trees = {ROMS_ROOT: ROMS_ROOT, None: "install"} + placed = { + (profile, trees[entry.get("root")], str(entry.get("dest", "")).rpartition("/")[0]) + for entry in entries if entry.get("root") in trees + for copy in [entry, *entry.get("alternatives", [])] + for profile in copy.get("cores") or [] + } + result: dict[str, list[dict]] = {} + for (profile, tree, folder), boards in sorted(found.items()): + if not any( + p == profile and t == tree and (d == folder or d.startswith(f"{folder}/")) + for p, t, d in placed + ): + continue + result.setdefault(profile, []).append( + {"root": tree, "folder": folder, "boards": sorted(boards)} + ) + return result + + +def _downloaded_cores( + config: dict, + profiles: dict[str, dict], + core_names: dict[str, list[str]], + platforms_dir: str, +) -> dict[str, list[str]]: + """The cores only the platform's RetroArch downloader brings, each with + the boards, aliases included, whose downloader offers it. + + A target list names the board's standalone amiberry and the buildbot's + amiberry core alike, so the installer cannot tell from the name whether + the board reaches the core. `resolve_platform_cores` decides it, and + `install.py --target` reads its answer here. + """ + reached = { + profile: names + for profile, names in downloaded_only_profiles(config, profiles).items() + if profile in core_names + } + if not reached: + return {} + platform = str(config.get("_key") or "") + boards: dict[str, list[str]] = {profile: [] for profile in reached} + for target in list_available_targets(platform, platforms_dir): + cores = load_target_config(platform, target["name"], platforms_dir) + if cores is None: + continue + for profile, names in reached.items(): + if downloadable_on(cores, names): + boards[profile] += [target["name"], *target.get("aliases", [])] + return {profile: sorted(names) for profile, names in sorted(boards.items())} + + +def _manifest_core_index( + config: dict, + profiles: dict[str, dict], + files: list[dict], + omitted: list[dict], +) -> tuple[dict[str, list[str]], dict[str, list[str]]]: + """What the installer needs to narrow by a list of core names. + + A target list, or the cores found installed, names cores the way the + buildbot does, and a file names the profile that reads it: `core_names` + gives each profile the other names it goes by, and names every core the + platform runs, one that reads no file included: a core found installed + that the list does not name is one it has no profile for. `system_cores` + gives each platform system the cores whose presence keeps it, as + `filter_systems_by_target` decides. A system absent from it is kept + whatever is available. + """ + runs = _platform_cores(config, profiles) + reach = system_core_reach(config.get("systems", {}), profiles, runs) + system_cores = { + sys_id: sorted(cores) for sys_id, cores in sorted(reach.items()) + if cores is not None + } + named = { + c for entry in [*files, *omitted] + for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])] + for c in copy.get("cores") or [] + } + named |= {c for cores in system_cores.values() for c in cores} + named |= set(runs) + aliases: dict[str, set[str]] = {profile: set() for profile in named & set(runs)} + for name, claimants in upstream_profile_index(profiles, include_aliases=True).items(): + for profile in claimants & named: + if name != profile: + aliases.setdefault(profile, set()).add(name) + core_names = {profile: sorted(names) for profile, names in sorted(aliases.items())} + return core_names, system_cores diff --git a/scripts/packs/manifestentry.py b/scripts/packs/manifestentry.py new file mode 100644 index 000000000..85fe21020 --- /dev/null +++ b/scripts/packs/manifestentry.py @@ -0,0 +1,477 @@ +"""One file's manifest entry: where it is fetched, its hashes, the claims on it.""" + +from __future__ import annotations + +import functools +import os +from collections.abc import Callable +from dataclasses import dataclass + +from core.hashing import compute_hashes +from core.paths import sanitize_pack_path +from model.declarations import OUTER_ROOTS, declared_root +from model.largefiles import asset_name, load_registered_paths, published_asset_name +from packs.extras import ( + _detect_extras_prefix, + _extra_system_ids, + extra_full_destination, + extra_region_key, + save_manifest_dest, +) +from resolve.packfiles import resolve_file +from resolve.validation import validated_choice + + +@functools.cache +def _registered(repo_root: str) -> frozenset[str]: + """The paths a repository's .gitignore registers as release assets, read + by the parser the fetcher and the release check use, once per root.""" + return frozenset(load_registered_paths(os.path.join(repo_root, ".gitignore"))) + + +def _is_release_asset(local_path: str, repo_root: str) -> bool: + """Whether the installer fetches this file from the large-files release. + + The repository serves every committed file from its raw URL. Only the + files kept out of git live as release assets, and .gitignore is the + ledger of those. Size is not the criterion: a committed file over 50 MB + is still served by the repository, and announcing it as a release asset + sends the installer to an asset nobody uploaded. + """ + return _repo_relative(local_path, repo_root) in _registered(repo_root) + + +def _repo_relative(local_path: str, repo_root: str) -> str: + try: + return os.path.relpath(local_path, repo_root) + except ValueError: + return "" + + +def _release_asset_name(local_path: str, repo_root: str) -> str: + """The large-files asset install.py downloads for a gitignored file. + + The name GitHub serves, not the one uploaded: a space in the path came + back as a 404 for an installer asking for it verbatim. + """ + return published_asset_name( + asset_name(_repo_relative(local_path, repo_root), sorted(_registered(repo_root))) + ) + + +def _get_repo_path(sha1: str, db: dict) -> str: + """Get the repo path for a file by SHA1 lookup.""" + entry = db.get("files", {}).get(sha1, {}) + return entry.get("path", "") + + +# The database the index was built from, held so its identity stays its own. +_DB_SHA1_BY_PATH: list[tuple[dict, dict[str, str]]] = [] + + +def _db_sha1_by_path(db: dict) -> dict[str, str]: + """Path -> sha1 of the database, built once per database.""" + if _DB_SHA1_BY_PATH and _DB_SHA1_BY_PATH[0][0] is db: + return _DB_SHA1_BY_PATH[0][1] + index = { + os.path.normpath(entry["path"]): sha1 + for sha1, entry in db.get("files", {}).items() + if entry.get("path") + } + _DB_SHA1_BY_PATH[:] = [(db, index)] + return index + + +# The hashes a manifest entry records, and each file's once verified. +_MANIFEST_HASHES = frozenset({"sha1", "sha256"}) +_STABLE_HASHES: dict[tuple, dict] = {} + + +def _stable_hashes(local_path: str, db: dict) -> dict: + """The file's hashes, held against the scan that built the database. + + A manifest entry is what every installer downloads and checks against. + Under load this host has hashed a 252 MB DSi NAND to a sha1 no file + holds, twice and the same way, so recomputing alone proves nothing: the + database scanned the same path, and a manifest that disagrees with it is + refused rather than published. + """ + stat = os.stat(local_path) + expected = _db_sha1_by_path(db).get(os.path.normpath(local_path)) + # Keyed by what was checked, the sha1 this database expects there, never + # by id(db): a database freed and replaced at the same address answered + # with hashes verified against the first one. + key = (os.path.normpath(local_path), stat.st_size, stat.st_mtime_ns, expected) + known = _STABLE_HASHES.get(key) + if known is not None: + # Verified against the scan once: twelve manifests name a file up + # to a dozen times, and rehashing it each time spent 163 s of 218. + return known + hashes = compute_hashes(local_path, _MANIFEST_HASHES) + for _attempt in range(2): + if expected is None or hashes["sha1"] == expected: + _STABLE_HASHES[key] = hashes + return hashes + # Read from disk again: the cached digest is the one in doubt, and a + # retry through the cache answered with it without a second read. + hashes = compute_hashes(local_path, _MANIFEST_HASHES, cache=False) + raise RuntimeError( + f"{local_path}: sha1 {hashes['sha1']} contradicts the database scan " + f"({expected}). Rehash the file or regenerate database.json" + ) + + +def _manifest_entry( + local_path: str | None, + dest: str, + cores: list[str] | None, + db: dict, + repo_root: str, + selection_fields: dict, +) -> tuple[dict | None, int]: + """The download record of a resolved file, and the size it occupies. + + The installer fetches by hash, so the entry records the copy this + repository holds: an upstream hash carried by no local file resolves to + no URL. An entry needs somewhere to be fetched from, and a file the + database does not index (a data directory, a copy added since the last + scan, a hash computed wrong) has neither a repo path nor a release + asset. None then, so the caller records an omission instead of a dead + entry that makes the installer refuse the whole manifest. + `selection_fields` carries what the installer narrows on. + """ + sha1 = "" + sha256 = "" + file_size = 0 + if local_path and os.path.exists(local_path): + file_size = os.path.getsize(local_path) + hashes = _stable_hashes(local_path, db) + sha1 = hashes["sha1"] + sha256 = hashes["sha256"] + repo_path = _get_repo_path(sha1, db) if sha1 else "" + is_release_asset = _is_release_asset(local_path or "", repo_root) + if not repo_path and not is_release_asset: + return None, file_size + entry: dict = { + "dest": dest, + "sha1": sha1, + "sha256": sha256, + "size": file_size, + "repo_path": repo_path, + "cores": cores, + **selection_fields, + } + if local_path and is_release_asset: + entry["storage"] = "release" + entry["release_asset"] = _release_asset_name(local_path, repo_root) + # The installer writes what it downloads with the umask's mode, but a program + # (RetroDECK's pico8, vox) has to stay runnable. The git mode cannot say: + # hundreds of MAME archives carry an execute bit nothing reads. + if local_path and _is_program(local_path): + entry["executable"] = True + return entry, file_size + + +_PROGRAM_MAGIC = ( + b"\x7fELF", + b"#!", + b"\xcf\xfa\xed\xfe", + b"\xce\xfa\xed\xfe", + b"\xca\xfe\xba\xbe", +) + + +def _is_program(path: str) -> bool: + """An ELF or Mach-O binary, or a script with an interpreter line.""" + with open(path, "rb") as handle: + head = handle.read(4) + return any(head.startswith(magic) for magic in _PROGRAM_MAGIC) + + +@dataclass(frozen=True) +class _ClaimContext: + """How a manifest resolves and judges the copy a core claim names.""" + + db: dict + bios_dir: str + zip_contents: dict | None + offline: bool | None + required_only: bool + validation_index: dict | None + owners: dict | None + repo_root: str + data_registry: dict | None = None + + +def _attach_claims( + entry: dict, + claims: list[dict], + ctx: _ClaimContext, + dest: str, + manifest_dest: str, +) -> None: + """Every other core that reads this destination, in the order the builder + meets them: a pack built without the earlier cores, or without the + platform system that declares the file, carries the first remaining + one's copy. + + A claim joins the copy just before it when the bytes agree and starts an + alternative otherwise. It never joins an earlier copy, which would let it + win over a core the builder tries first. Only a core's first claim can + win: its later ones are reached only when that one is. A platform entry + names no core, so its first claim always starts an alternative. + """ + claimed = set(entry["cores"] or []) + for claim in claims: + claim_emu = claim.get("source_profile") or claim.get("source_emulator", "") + if not claim_emu or claim_emu in claimed: + continue + claimed.add(claim_emu) + if ctx.required_only and claim.get("required") is False: + continue + claim_path, claim_status = resolve_file( + claim, ctx.db, ctx.bios_dir, ctx.zip_contents, + dest_hint=claim.get("destination", ""), + data_dir_registry=ctx.data_registry, offline=ctx.offline, + ) + if claim_status in ("not_found", "external", "user_provided") or not claim_path: + # Nothing held for this core: narrowed to it without the cores + # served above, the slot is a file left out (installer replays it). + entry.setdefault("absent_claims", []).append( + _absent_claim(claim, claim_emu, claim_status) + ) + continue + claim_path, _ = validated_choice( + claim, claim_path, ctx.db, ctx.validation_index or {}, ctx.bios_dir, None, + claim.get("layout_path") or dest, ctx.owners, + ) + copy, _size = _manifest_entry( + claim_path, manifest_dest, [claim_emu], ctx.db, ctx.repo_root, {} + ) + if copy is None: + continue + alternatives = entry.setdefault("alternatives", []) + last = alternatives[-1] if alternatives else entry + if last["cores"] is not None and copy["sha1"] == last["sha1"]: + if claim_emu not in last["cores"]: + last["cores"].append(claim_emu) + continue + del copy["dest"] + alternatives.append(copy) + if not entry.get("alternatives"): + entry.pop("alternatives", None) + + +def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict: + """The omission a claim with nothing held stands for.""" + systems = _extra_system_ids(claim) + return { + "name": str(claim.get("name") or ""), + "system": systems[0] if systems else "", + "required": bool(claim.get("required", True)), + "reason": ( + claim_status + if claim_status in ("not_found", "external", "user_provided") + else "not_found" + ), + "cores": [claim_emu], + } + + +def _record_slot_choices( + entry: dict, + choices: list[tuple[str, str | None]], + declarations: list[tuple[list[str], dict, str]], + settle: Callable[[dict, str, str, str | None], tuple[str | None, str]], + dest: str, + db: dict, + repo_root: str, +) -> None: + """Record what a pack built for fewer cores serves at a platform destination. + + `slot_choices` lists, in the order slots decides, the cores whose claim + settles the slot and the copy it serves, a choice without a copy leaving + the platform's answer. `declared_choices` is the platform's answer by the + declaring systems that remain, in the order the builder takes them. + Nothing is recorded where every narrowing gets the entry's own copy. + """ + + def download(file_entry: dict, sys_id: str, override: str | None) -> dict | None: + local_path, _status = settle(file_entry, sys_id, dest, override) + if local_path is None: + return None + copy, _size = _manifest_entry(local_path, dest, None, db, repo_root, {}) + if copy is None: + return None + return {k: v for k, v in copy.items() if k not in ("dest", "cores")} + + declared: list[dict] = [] + for systems, file_entry, sys_id in declarations: + copy = download(file_entry, sys_id, None) + if copy is None: + # An omission is not a copy the installer can switch to. + return + if declared and declared[-1]["sha1"] == copy["sha1"]: + declared[-1]["systems"].extend(systems) + else: + declared.append({**copy, "systems": list(systems)}) + _systems, first, first_sys = declarations[0] + recorded: list[dict] = [] + seen: set[str] = set() + for emulator, path in choices: + if emulator in seen: + continue + seen.add(emulator) + copy = {} if path is None else download(first, first_sys, path) + if copy is None: + return + if recorded and recorded[-1].get("sha1") == copy.get("sha1"): + recorded[-1]["cores"].append(emulator) + else: + recorded.append({**copy, "cores": [emulator]}) + while recorded and "sha1" not in recorded[-1]: + recorded.pop() + if not recorded and len(declared) == 1: + return + if recorded: + entry["slot_choices"] = recorded + entry["declared_choices"] = declared + + +def _manifest_dest_of(full_dest: str, base_dest: str) -> str: + """A pack destination as the manifest writes it, below base_destination.""" + if base_dest and full_dest.startswith(f"{base_dest}/"): + return full_dest[len(base_dest) + 1:] + return full_dest + + +def _claim_platform_omission(held: dict | None, emulator: str) -> bool: + """Record a core's claim on a destination the platform already omits. + + The platform's own omission stands while one of its declaring systems + does. A pack built without them falls to the first core claiming the + path, as for a file present. Overwriting the record lost the platform's + claim: a target without that core dropped an omission its pack reports. + """ + if held is None or held.get("cores") is not None: + return False + if emulator: + claims = held.setdefault("alternatives", []) + if {"cores": [emulator]} not in claims: + claims.append({"cores": [emulator]}) + return True + + +def _claim_cores(fe: dict) -> list[str]: + """The cores an extra and the claims folded onto it name: an omission + names every core reading the file, as a list built for one of them + would.""" + names = { + claim.get("source_profile") or claim.get("source_emulator", "") + for claim in (fe, *fe.get("other_claims", [])) + } + return sorted(name for name in names if name) + + +def _record_absent( + absent: list[dict], + config: dict, + base_dest: str, + region_drops: set, + required_only: bool, + seen_destinations: set, + omitted_by_destination: dict, + record_omission: Callable[..., None], +) -> None: + """A file a core needs that the collection does not hold is an omission. + + Left out of both lists, DevilutionX's diabdat.mpq and dhewm3's + pak000-004 reached no safety notice: the installer said everything + was verified and the game refused to start. + """ + extras_pfx = _detect_extras_prefix(config, base_dest) + for fe in absent: + if required_only and fe.get("required") is False: + continue + dest = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) + if not dest or ( + region_drops and extra_region_key(fe, declared_root(config)) in region_drops + ): + continue + full_dest = extra_full_destination(fe, extras_pfx) + if not full_dest or full_dest in seen_destinations: + continue + source_emu = fe.get("source_profile") or fe.get("source_emulator", "") + held = omitted_by_destination.get(full_dest) + if held is not None: + # Another core reads the same missing file there (Raze and + # EDuke32 both open NAPALM.GRP): one omission names them all. + claimed = held.get("cores") + if (held.get("reason") == "not_found" and claimed and source_emu + and source_emu not in claimed): + held["cores"] = sorted([*claimed, source_emu]) + continue + systems = _extra_system_ids(fe) + record_omission( + full_dest, fe, systems[0] if systems else "", "not_found", + [source_emu] if source_emu else [], + ) + + +# What a manifest's roms_directory and emulators_directory carry: the BIOS +# folder's name, for the roms root its place relative to the BIOS folder +# (romfolders roms_root.from_bios), and for emulator folders the places the +# launcher searches, the one a missing folder is created at, and the config +# file whose key moves a folder. +MANIFEST_OUTER_FIELDS = ("bios_folder", "from_bios", "searched", "default", "config") + + +def _record_unplaceable( + unplaceable: list[dict], + record_omission: Callable[..., None], + config: dict, + profiles: dict[str, dict], +) -> None: + """Held by the collection, nowhere to put it on this platform. + + Said in the manifest, where RomM's DOSBox Pure ROMs were simply absent. + One place read by several cores is one omission naming them all. + """ + # The emulator's own folder is the one the platform installs the name + # it lists into: RetroPie puts amiberry 5.7.2 and 6.3.3, one per board, + # both in $md_inst of its amiberry package. + platform_names = { + str(c) for key in ("cores", "standalone_cores") + if isinstance(config.get(key), list) for c in config[key] + } + + def folder(profile: str) -> str: + names = {profile, *map(str, (profiles.get(profile) or {}).get("cores") or [])} + return min(names & platform_names, default=profile) + + grouped: dict[str, tuple[dict, list[str]]] = {} + for u in unplaceable: + where = u.get("path") or u.get("name", "") + # The profile key, the name a target's core list and the + # installer's narrowing match: the display name matched none. + core = u.get("profile") or u.get("emulator", "") + if u.get("unplaced"): + key = f"emulator:{folder(core)}:{where}" + elif u.get("root") in OUTER_ROOTS: + key = f"{u['root']}:{where}" + elif u.get("root") == "save": + key = f"save:{save_manifest_dest(u)}" + else: + key = where + held, cores = grouped.setdefault(key, (u, [])) + if core and core not in cores: + cores.append(core) + if u.get("required", True) and not held.get("required", True): + grouped[key] = ({**held, "required": True}, cores) + for key, (u, cores) in grouped.items(): + record_omission( + # Keyed apart from the BIOS tree's paths, which a file read below + # the save directory or in the emulator's folder can repeat. + key, u, u.get("system") or "", + u.get("unplaceable", "no_platform_slug"), sorted(cores), + ) diff --git a/scripts/manifestselect.py b/scripts/packs/manifestselect.py similarity index 99% rename from scripts/manifestselect.py rename to scripts/packs/manifestselect.py index 31bef99af..c7f7091a0 100644 --- a/scripts/manifestselect.py +++ b/scripts/packs/manifestselect.py @@ -21,7 +21,7 @@ from resolve import regions as resolve_regions from resolve import slot as slot_mod from model.systems import _norm_system_id from core.paths import sanitize_pack_path -from packextras import ( +from packs.extras import ( _kept, _serving_system_ids, extra_region_groups, diff --git a/scripts/packs/md5pack.py b/scripts/packs/md5pack.py new file mode 100644 index 000000000..85e81dffc --- /dev/null +++ b/scripts/packs/md5pack.py @@ -0,0 +1,243 @@ +"""A pack built from a list of hashes.""" + +from __future__ import annotations + +import hashlib +import os +import sys +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict + +from model.platforms import load_platform_config +from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles +from packs.archive import _add_pack_member, _reject_unknown, _writing_pack +from packs.naming import _name_part, _narrowings +from packs.paths import _resolve_destination +from resolve.packfiles import resolve_file, sha1_for_hash + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def _entry_for_file(candidates: list[dict], held: dict) -> dict: + """The declaration a held file answers when several share its name. + + BBKEmu declares 8.BIN once per model. The last one won, and the A4980 + dump went to the A4988 folder. The declared hash decides, then the + destination the collection's own path ends with, then the last one. + """ + def declared(fe: dict, key: str) -> set[str]: + value = fe.get(key) + values = value if isinstance(value, list) else str(value or "").split(",") + return {str(v).strip().lower() for v in values if str(v).strip()} + + for fe in candidates: + if any( + str(held.get(key, "")).lower() in declared(fe, key) + for key in ("sha1", "md5", "sha256", "crc32") + if held.get(key) + ): + return fe + held_paths = [str(held.get("path", ""))] + [str(p) for p in held.get("paths") or []] + for fe in candidates: + tail = str(fe.get("path") or fe.get("destination") or "").lower() + if tail and any(path.lower().endswith("/" + tail) for path in held_paths): + return fe + return candidates[-1] + + +class Md5PackOptions(TypedDict, total=False): + """The keyword options of generate_md5_pack: the layout to follow.""" + + platform_name: str | None + platforms_dir: str | None + emulator_name: str | None + emulators_dir: str | None + standalone: bool + + +@dataclass(frozen=True) +class _Md5Settings: + """Md5PackOptions with their defaults.""" + + platform_name: str | None = None + platforms_dir: str | None = None + emulator_name: str | None = None + emulators_dir: str | None = None + standalone: bool = False + + +@dataclass(frozen=True) +class _Md5Layout: + """Where a hash-selected pack puts each file: the declarations by + lowercased name, the platform's base destination, and the pack's name.""" + + index: dict[str, list[dict]] + base_dest: str + context_name: str + + +def _md5_layout(opts: _Md5Settings) -> _Md5Layout | None: + """The platform or emulator layout a hash list is packed in, or None + when the emulator named is refused.""" + platform_name = opts.platform_name + platforms_dir = opts.platforms_dir + emulator_name = opts.emulator_name + emulators_dir = opts.emulators_dir + plat_file_index: dict[str, list[dict]] = {} + base_dest = "" + plat_display = "Custom" + if platform_name and platforms_dir: + config = load_platform_config(platform_name, platforms_dir) + base_dest = config.get("base_destination", "") + plat_display = config.get("platform", platform_name) + for system in config.get("systems", {}).values(): + for fe in system.get("files", []): + plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe) + + emu_display = "" + if emulator_name and emulators_dir: + profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) + # The same gate as --emulator, unknown names included: a typo or a + # buildbot name gave a generic pack in the layout of no emulator. A + # core with no standalone build has no standalone layout either. + try: + (_name, profile), = select_emulator_profiles( + [emulator_name], profiles, opts.standalone + ) + except ProfileSelectionError as exc: + print(f"Error: {exc}", file=sys.stderr) + return None + emu_display = profile.get("emulator", emulator_name) + for fe in profile.get("files", []): + plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe) + for alias in fe.get("aliases", []): + plat_file_index.setdefault(alias.lower(), []).append(fe) + + context_name = plat_display if platform_name else (emu_display or "Custom") + return _Md5Layout(plat_file_index, base_dest, context_name) + + +def _md5_pack_name( + context_name: str, hashes: list[tuple[str, str]], opts: _Md5Settings, +) -> str: + """The file name of a hash-selected pack.""" + # The selection mode is part of the name, as for --system: BizHawk is + # both a platform and a profile display name, and the two layouts + # (Firmware/ under the platform, the profile's paths under the core) + # wrote one file, the second run replacing the first without a word. + mode_part = ( + "_Emulator" if opts.emulator_name and not opts.platform_name else "" + ) + # --standalone changes the destination layout, so a run with it must not + # take the name of a run without it. + custom_tags = "".join( + tag + for tag, _label in _narrowings( + "full", None, None, False, False, standalone=opts.standalone + ) + ) + # The hash list is what chooses the content: two lists under one name + # overwrote each other in the same output directory. + selection = hashlib.sha1( + "\n".join(sorted(f"{kind}:{value.lower()}" for kind, value in hashes)).encode() + ).hexdigest()[:8] + return ( + f"{_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}" + "_BIOS_Pack.zip" + ) + + +def _md5_destination(entry: dict, layout: _Md5Layout, opts: _Md5Settings) -> str: + """Where a held file goes in a hash-selected pack.""" + name = entry.get("name", "") + aliases = entry.get("aliases") or [] + paths = entry.get("paths") or [] + + dest = name + matched_fe = None + for lookup_name in [name] + aliases: + if lookup_name.lower() in layout.index: + matched_fe = _entry_for_file(layout.index[lookup_name.lower()], entry) + break + + if matched_fe: + if opts.emulator_name: + # Laid out as the emulator pack lays it out: its path and + # its standalone_path, which --standalone has to reach. + dest = _resolve_destination(matched_fe, opts.standalone) + else: + dest = matched_fe.get("destination", matched_fe.get("name", name)) + elif paths: + dest = paths[0] + + if layout.base_dest and not dest.startswith(layout.base_dest): + return f"{layout.base_dest}/{dest}" + return dest + + +def generate_md5_pack( + hashes: list[tuple[str, str]], + db: dict, + bios_dir: str, + output_dir: str, + zip_contents: dict | None = None, + **options: Unpack[Md5PackOptions], +) -> str | None: + """Build a pack from an explicit list of hashes with layout context.""" + files_db = db.get("files", {}) + if zip_contents is None: + zip_contents = {} + _reject_unknown("generate_md5_pack", options, Md5PackOptions.__optional_keys__) + opts = _Md5Settings(**options) + layout = _md5_layout(opts) + if layout is None: + return None + zip_path = os.path.join(output_dir, _md5_pack_name(layout.context_name, hashes, opts)) + os.makedirs(output_dir, exist_ok=True) + + packed: list[tuple[str, str]] = [] + not_in_repo: list[tuple[str, str]] = [] + not_in_db: list[str] = [] + seen: set[str] = set() + + with _writing_pack(zip_path) as zf: + for hash_type, hash_val in hashes: + sha1 = sha1_for_hash(hash_type, hash_val, db) + if not sha1: + not_in_db.append(hash_val) + continue + + entry = files_db[sha1] + name = entry.get("name", "") + full_dest = _md5_destination(entry, layout, opts) + if full_dest in seen: + continue + seen.add(full_dest) + + fe_for_resolve = {"name": name, "sha1": sha1, "md5": entry.get("md5", "")} + local_path, status = resolve_file( + fe_for_resolve, db, bios_dir, zip_contents + ) + + if status == "not_found" or not local_path: + not_in_repo.append((name, hash_val)) + continue + + _add_pack_member(zf, local_path, full_dest) + packed.append((name, hash_val)) + + total = len(hashes) + print(f"\nPacked {len(packed)}/{total} requested files") + for name, h in packed: + print(f" PACKED: {name} ({h[:16]}...)") + for name, h in not_in_repo: + print(f" NOT IN REPO: {name} ({h[:16]}...)") + for h in not_in_db: + print(f" NOT IN DB: {h}") + + if not packed: + if os.path.exists(zip_path): + os.unlink(zip_path) + return None + return zip_path diff --git a/scripts/packs/naming.py b/scripts/packs/naming.py new file mode 100644 index 000000000..3a1e1915a --- /dev/null +++ b/scripts/packs/naming.py @@ -0,0 +1,346 @@ +"""The names of pack archives and manifests, built from every narrowing.""" + +from __future__ import annotations + +import hashlib +import os +import re + +from model import region +from model.platforms import load_platform_config +from model.registry import list_release_pack_platforms +from model.systems import MANUFACTURER_PREFIXES +from model.targets import build_target_cores_cache, canonical_target_name, platform_files_target +from packs import parts as packs_parts +from resolve.grouping import group_identical_platforms + + +def _narrowings( + source: str, + regions: list[str] | None, + target_name: str | None, + one_per_slot: bool, + required_only: bool, + standalone: bool = False, + no_game_data: bool = False, +) -> list[tuple[str, str]]: + """Every dimension that narrows a pack, as (filename tag, plain label). + + The pack name and the pack README are both built from this list, so a new + way of narrowing a pack cannot reach users nameless or unannounced. Order + is the filename order and must not change: it is what existing archives + are called. + """ + applied: list[tuple[str, str]] = [] + if source == "platform": + applied.append(("_Platform", "only what the platform declares")) + elif source == "truth": + applied.append(("_Truth", "only what emulator profiles require")) + if regions: + pretty = ", ".join( + " ".join(w.title() for w in slug.split("-")) for slug in regions + ) + applied.append( + (f"_{region.region_tag(regions)}", f"region priority {pretty}") + ) + if target_name: + applied.append( + (f"_{_target_tag(target_name)}", f"cores available on {target_name}") + ) + if one_per_slot: + applied.append(("_OnePerSlot", "one BIOS per system and region")) + if standalone: + applied.append(("_Standalone", "standalone mode files only")) + if required_only: + applied.append(("_Required", "required files only")) + if no_game_data: + applied.append(("_NoGameData", "firmware only, game data left out")) + return applied + + +def _target_tag(target_name: str) -> str: + """Filename tag for a hardware target. + + Without it a targeted pack takes the same name as the full one and + overwrites it. + """ + return "".join( + part.title() for part in re.split(r"[-_\s]+", target_name.strip()) if part + ) + + +def _platform_target( + platform_name: str, target: str | None, platforms_dir: str +) -> str | None: + """The target as this platform files it, the name its artifacts carry. + + Named once for the whole run, a target two platforms file differently + (rpi4: Batocera's bcm2711, Recalbox's rpi4_64) kept the typed name under + --all and took the platform's own under --platform, so --verify-packs + looked for a pack the --all build had named otherwise. A platform that + does not file the target is packed whole under --all, and its name + claims no narrowing: BizHawk_..._Switch_BIOS_Pack.zip was the full pack. + """ + if not target or not platform_files_target(platform_name, target, platforms_dir): + return None + return canonical_target_name([platform_name], target, platforms_dir) + + +def _system_tag(system_filter: list[str] | None) -> str: + """Filename tag for a pack limited to some systems, empty for all.""" + if not system_filter: + return "" + display_parts = [] + for sid in system_filter: + s = sid.lower().replace("_", "-") + for prefix in MANUFACTURER_PREFIXES: + if s.startswith(prefix): + s = s[len(prefix) :] + break + display_parts.append("_".join(p.title() for p in s.split("-") if p)) + return "_" + _bounded_join(display_parts, system_filter) + + +# A system list long enough to push a pack name past this falls back to the +# first system, a count and a digest of the list. +MAX_SYSTEM_TAG_BYTES = 120 + + +def _bounded_join(parts: list[str], keys: list[str]) -> str: + """Parts joined while they fit, else the first, a count and a digest. + + Thirty systems joined made a 261-byte file name and the ZIP could not + be opened. The digest keeps two different selections apart. The joiner + is one no part holds: with "_", sega-dreamcast + arcade and + sega-dreamcast-arcade both named Dreamcast_Arcade, and the second build + replaced the first. + """ + joined = "+".join(parts) + if len(joined.encode("utf-8")) <= MAX_SYSTEM_TAG_BYTES: + return joined + digest = hashlib.sha1("\n".join(sorted(keys)).encode("utf-8")).hexdigest()[:8] + return f"{parts[0]}_and_{len(parts) - 1}_more_{digest}" + + +_UNSAFE_IN_NAME = re.compile(r'[/\\:*?"<>|]') + + +def _name_part(text: str, space: str = "") -> str: + """A display name made safe to stand in a file name. + + 'FinalBurn Neo (CPS-1/CPS-2)' named a directory that did not exist, and a + Windows user cannot write ':' or '?' either. + """ + return _UNSAFE_IN_NAME.sub("-", text.replace(" ", space)) + + +def _platform_pack_stem( + group_platforms: list[str], representative: str, platforms_dir: str +) -> str: + """Platform part of a pack name, version included. + + A group of identical platforms shares one pack named after all of them, + and the builder and --verify-packs both read the name from here. + """ + rep_cfg = load_platform_config(representative, platforms_dir) + version = rep_cfg.get("version", rep_cfg.get("dat_version", "")) + version_tag = f"_{_name_part(str(version))}" if version else "" + return platform_pack_prefix(group_platforms, representative, platforms_dir) + version_tag + + +def platform_pack_prefix( + group_platforms: list[str], representative: str, platforms_dir: str +) -> str: + """Platform part of a pack name without the version. + + The site reads a pack's version back by removing this prefix: a version + may hold an underscore (AmberELEC prerelease-20261019_1835). + """ + if len(group_platforms) <= 1: + rep_cfg = load_platform_config(representative, platforms_dir) + return _name_part(rep_cfg.get("platform", representative), "_") + names = [ + load_platform_config(p, platforms_dir).get("platform", p) + for p in group_platforms + ] + return "_".join(_name_part(n) for n in names) + + +def _platform_pack_name( + platform_name: str, + platforms_dir: str, + narrowings: list[tuple[str, str]], + system_filter: list[str] | None, + pack_name: str | None = None, +) -> str: + """File name of a platform pack: stem, narrowing tags, system tag. + + A caller naming the pack itself (a --split part) is taken at its word. + """ + if pack_name: + return pack_name + stem = _platform_pack_stem([platform_name], platform_name, platforms_dir) + tags = "".join(tag for tag, _label in narrowings) + return f"{stem}{tags}_BIOS_Pack{_system_tag(system_filter)}.zip" + + +# A file name holds 255 bytes on every filesystem a pack is written to, +# and the margin leaves room for the split part suffix and a scratch prefix. +MAX_PACK_NAME_BYTES = 200 + + +def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) -> str: + """The emulator pack's file name, its emulators joined while they fit. + + Past the limit the name keeps the first emulator, says how many more the + pack holds, and carries a digest of the selection so two different + selections never share a file. + """ + joined = "_".join(display_names) + suffix + if len(joined.encode("utf-8")) <= MAX_PACK_NAME_BYTES: + return joined + digest = hashlib.sha1("\n".join(sorted(keys)).encode("utf-8")).hexdigest()[:8] + return f"{display_names[0]}_and_{len(display_names) - 1}_more_{digest}{suffix}" + + +def _expected_pack_names( + platforms: list[str], + platforms_dir: str, + regions: list[str] | None, + target_name: str | None, + variants: tuple[tuple[str, bool], ...] = (("full", False),), + no_game_data: bool = False, +) -> dict[str, set[str]]: + """Exact pack file names --verify-packs may check, per platform. + + Rebuilt from the name builder, never matched by substring: a substring + picks the full pack when a regional or targeted one was asked for, or a + narrowed pack when the full one was. A platform answers to its own name + and to the name of the group it shares a pack with. ``variants`` lists + the (source, required_only) combinations the run built. + """ + def narrow_tags(platform_name: str) -> list[str]: + named = _platform_target(platform_name, target_name, platforms_dir) + return [ + "".join( + tag + for tag, _label in _narrowings( + source, regions, named, False, required, no_game_data=no_game_data + ) + ) + for source, required in variants + ] + + names: dict[str, set[str]] = { + p: { + f"{_platform_pack_stem([p], p, platforms_dir)}{tags}_BIOS_Pack.zip" + for tags in narrow_tags(p) + } + for p in platforms + } + # Groups depend on which platforms a run built: the release packs of + # --all. + pool = list_release_pack_platforms(platforms_dir) + cache = None + if target_name: + try: + cache, pool = build_target_cores_cache( + pool, target_name, platforms_dir, is_all=True + ) + except ValueError: + # No platform has the target: no pack was built under it. + return names + for group, representative in group_identical_platforms( + pool, platforms_dir, cache + ): + if len(group) < 2: + continue + stem = _platform_pack_stem(group, representative, platforms_dir) + for tags in narrow_tags(representative): + for p in group: + if p in names: + names[p].add(f"{stem}{tags}_BIOS_Pack.zip") + return names + + +def _content_narrowing_tags() -> tuple[str, ...]: + """Tags naming a pack that holds fewer files than the platform declares. + + Read from the name builder rather than retyped, so the two cannot drift. + Region and target are absent on purpose: both are handed to the check + itself, which narrows its expectation instead of skipping it. + """ + # (source, one_per_slot, required_only), one dimension at a time. + dimensions = ( + ("platform", False, False), + ("truth", False, False), + ("full", True, False), + ("full", False, True), + ) + tags: list[str] = [] + for source, one_per_slot, required_only in dimensions: + tags.extend( + tag + for tag, _label in _narrowings(source, None, None, one_per_slot, required_only) + ) + return tuple(tags) + + +_CONTENT_NARROWING_TAGS = _content_narrowing_tags() + + +def _narrows_contents(pack_name: str) -> bool: + """True when a pack holds fewer files than the platform declares. + + A source-restricted or required-only build is narrower by design, so the + full platform expectation does not apply to it and conformance is skipped. + Region is not listed: the region filter is passed to the check itself, and + a hardware target is passed the same way. + """ + return any(f"{tag}_" in pack_name for tag in _CONTENT_NARROWING_TAGS) + + +def _pack_variant(pack_name: str) -> tuple[str, bool] | None: + """The (source, required_only) a pack was built as, read from its name. + + None for a one-per-slot pack, whose slot choice the check does not + replay. The tags come from the name builder, as for _narrows_contents. + """ + def tagged(**dimension: object) -> bool: + tags = [ + tag for tag, _label in _narrowings( + str(dimension.get("source", "full")), None, None, + bool(dimension.get("one_per_slot", False)), + bool(dimension.get("required_only", False)), + ) + ] + return all(f"{tag}_" in pack_name for tag in tags) + + if tagged(one_per_slot=True): + return None + source = next( + (s for s in ("platform", "truth") if tagged(source=s)), "full" + ) + return source, tagged(required_only=True) + + +def _pack_archives(output_dir: str) -> list[str]: + """The ZIPs of a directory that are packs. + + A part of a split pack holds a share of a platform by design and was + checked against the whole when it was cut: judged as a pack it would + fail conformance, and injecting a manifest would change published bytes. + Every name the builder gives holds `_BIOS_Pack`, then the system tag of + a --system platform pack (`_BIOS_Pack_Playstation.zip`): build_port.py + wrote its launcher archives (RetroBIOS.zip) to the same dist/, and + taking every ZIP rewrote them with a manifest after build_port had + printed their hashes. + """ + return sorted( + name + for name in os.listdir(output_dir) + if _PACK_NAME.search(name) and not packs_parts.is_part(name) + ) + + +_PACK_NAME = re.compile(r"_BIOS_Pack(?:_[^/]+)?\.zip$") diff --git a/scripts/packs/parts.py b/scripts/packs/parts.py new file mode 100644 index 000000000..3a903acf5 --- /dev/null +++ b/scripts/packs/parts.py @@ -0,0 +1,297 @@ +"""A pack too large for one release asset, written as several ZIPs of whole files.""" + +from __future__ import annotations + +import io +import re +import struct +import zipfile +import zlib +from pathlib import Path + + +# "Each file included in a release must be under 2 GiB." +ASSET_LIMIT = 2 * 1024**3 + +PACK_SUFFIX = "_BIOS_Pack.zip" +_PART_NAME = re.compile(r"^(?P.+_BIOS_Pack)\.part(?P\d+)of(?P\d+)\.zip$") +_MARKER_NAME = re.compile(r"^(?P.+_BIOS_Pack)\.part(?P\d+)of(?P\d+)\.txt$") +# Sizes are written at a fixed width, so a marker's length, and with it the +# size of its own part, does not depend on the sizes it records. +_SIZE_WIDTH = 13 + +_LOCAL = struct.Struct("<4s2B4HL2L2H") +_CENTRAL = struct.Struct("<4s4B4HL2L5H2L") +_END = struct.Struct("<4s4H2LH") +_LOCAL_SIG = b"PK\x03\x04" +_CENTRAL_SIG = b"PK\x01\x02" +_END_SIG = b"PK\x05\x06" +_DATA_DESCRIPTOR = 0x08 +_UTF8_NAME = 0x800 +_CHUNK = 1024 * 1024 +_MAX_ENTRIES = 0xFFFF +_MAX_FIELD = 0xFFFFFFFF + + +def is_part(name: str) -> bool: + """Whether a file name is one part of a split pack.""" + return _PART_NAME.match(name) is not None + + +def pack_of(name: str) -> str: + """The pack a published file belongs to, a part folded into its archive.""" + part = _PART_NAME.match(name) + return f"{part['stem']}.zip" if part else name + + +def part_name(pack_name: str, index: int, count: int) -> str: + return f"{pack_name[: -len('.zip')]}.part{index}of{count}.zip" + + +def marker_name(pack_name: str, index: int, count: int) -> str: + return f"{pack_name[: -len('.zip')]}.part{index}of{count}.txt" + + +def is_marker(name: str) -> bool: + """Whether an archive member is the marker a split writes in each part.""" + return _MARKER_NAME.match(name) is not None + + +def marker_text(pack_name: str, index: int, sizes: list[int]) -> bytes: + """The marker of part *index* of a pack published in ``len(sizes)`` parts. + + Plain text a person can read, in a form install.py parses back: the + lines that matter are `pack:`, `part:` and one `file:` per part. + """ + count = len(sizes) + lines = [ + "RetroBIOS split pack", + f"This folder holds part {index} of {count} of {pack_name}.", + "Every part is needed: extract them all into this same folder.", + "The installer's --check names a part missing from the folder.", + "", + f"pack: {pack_name}", + f"part: {index} of {count}", + ] + lines += [ + f"file: {size:>{_SIZE_WIDTH}} {part_name(pack_name, number, count)}" + for number, size in enumerate(sizes, 1) + ] + return ("\n".join(lines) + "\n").encode("utf-8") + + +def _marker_weight(pack_name: str, index: int, count: int) -> int: + name = len(marker_name(pack_name, index, count).encode("utf-8")) + body = len(marker_text(pack_name, index, [0] * count)) + return _LOCAL.size + name + body + _CENTRAL.size + name + + +def _name_bytes(info: zipfile.ZipInfo) -> bytes: + encoding = "utf-8" if info.flag_bits & _UTF8_NAME else "cp437" + return info.orig_filename.encode(encoding) + + +def _weight(info: zipfile.ZipInfo) -> int: + """Bytes a member adds to a part: both headers and its stored data.""" + name = len(_name_bytes(info)) + return _LOCAL.size + name + info.compress_size + _CENTRAL.size + name + + +def plan_parts( + members: list[zipfile.ZipInfo], limit: int, reserve: int = 0 +) -> list[list[zipfile.ZipInfo]]: + """Fill each part in archive order, up to the limit less *reserve*.""" + parts: list[list[zipfile.ZipInfo]] = [[]] + floor = _END.size + reserve + size = floor + for info in members: + weight = _weight(info) + if floor + weight >= limit: + raise ValueError( + f"{info.filename} needs {weight:,} bytes, more than a part of " + f"{limit:,} can hold" + ) + if info.compress_size > _MAX_FIELD or info.file_size > _MAX_FIELD: + raise ValueError(f"{info.filename} needs ZIP64, which a part does not use") + if size + weight >= limit or len(parts[-1]) >= _MAX_ENTRIES - 1: + parts.append([]) + size = floor + parts[-1].append(info) + size += weight + return parts + + +def _dos_stamp(info: zipfile.ZipInfo) -> tuple[int, int]: + year, month, day, hour, minute, second = info.date_time + return ( + (hour << 11) | (minute << 5) | (second // 2), + ((year - 1980) << 9) | (month << 5) | day, + ) + + +def _data_offset(source: io.BufferedReader, info: zipfile.ZipInfo) -> int: + """Where a member's stored bytes begin, read from its own local header.""" + source.seek(info.header_offset) + header = _LOCAL.unpack(source.read(_LOCAL.size)) + if header[0] != _LOCAL_SIG: + raise ValueError(f"{info.filename}: no local header at its offset") + return info.header_offset + _LOCAL.size + header[10] + header[11] + + +def _marker_info(name: str, body: bytes) -> zipfile.ZipInfo: + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_STORED + info.CRC = zlib.crc32(body) + info.compress_size = info.file_size = len(body) + info.create_system = 3 + info.external_attr = (0o100000 | 0o644) << 16 + return info + + +def _write_part( + source: io.BufferedReader, members: list[zipfile.ZipInfo], dest: Path, + marker: tuple[str, bytes], +) -> None: + directory = [] + marker_info = _marker_info(*marker) + with open(dest, "wb") as out: + for info in [marker_info, *members]: + name = _name_bytes(info) + flags = info.flag_bits & ~_DATA_DESCRIPTOR + dos_time, dos_date = _dos_stamp(info) + offset = out.tell() + out.write( + _LOCAL.pack( + _LOCAL_SIG, info.extract_version, info.reserved, flags, + info.compress_type, dos_time, dos_date, info.CRC, + info.compress_size, info.file_size, len(name), 0, + ) + ) + out.write(name) + if info is marker_info: + out.write(marker[1]) + remaining = 0 + else: + source.seek(_data_offset(source, info)) + remaining = info.compress_size + while remaining: + chunk = source.read(min(_CHUNK, remaining)) + if not chunk: + raise ValueError(f"{info.filename}: the pack ends inside it") + out.write(chunk) + remaining -= len(chunk) + directory.append( + _CENTRAL.pack( + _CENTRAL_SIG, info.create_version, info.create_system, + info.extract_version, info.reserved, flags, + info.compress_type, dos_time, dos_date, info.CRC, + info.compress_size, info.file_size, len(name), 0, 0, 0, + info.internal_attr, info.external_attr, offset, + ) + + name + ) + start = out.tell() + for record in directory: + out.write(record) + out.write( + _END.pack( + _END_SIG, 0, 0, len(directory), len(directory), + out.tell() - start, start, 0, + ) + ) + + +def _identity(archive: zipfile.ZipFile) -> list[tuple[str, int, int]]: + return [ + (info.filename, info.CRC, info.file_size) + for info in archive.infolist() + if not is_marker(info.filename) + ] + + +def marker_weight(pack_name: str, count: int) -> int: + """Bytes the largest marker of a pack in *count* parts adds to its part.""" + return max(_marker_weight(pack_name, index, count) for index in (1, count)) + + +def _plan_with_markers( + pack_name: str, members: list[zipfile.ZipInfo], limit: int +) -> list[list[zipfile.ZipInfo]]: + """Plan the parts with room for the marker each one carries. + + The marker lists every part, so its length grows with their count: the + plan is made again until the count it assumed is the count it gives. + """ + count = 1 + while True: + reserve = marker_weight(pack_name, count) + plan = plan_parts(members, limit, reserve) + if len(plan) <= count: + return plan + count = len(plan) + + +def split_pack(zip_path: Path, limit: int = ASSET_LIMIT) -> list[Path]: + """Replace a pack at or over the limit by parts that each fit under it. + + Returns the files to publish. The pack is removed only once every part + has been read back in full and the parts together list exactly its + members, so a failure leaves the pack as it was and no part behind. + """ + zip_path = Path(zip_path) + if zip_path.stat().st_size < limit: + return [zip_path] + + with zipfile.ZipFile(zip_path) as archive: + members = archive.infolist() + expected = _identity(archive) + taken = [info.filename for info in members if is_marker(info.filename)] + if taken: + raise ValueError(f"{zip_path.name} already holds {taken[0]}, a part marker name") + plan = _plan_with_markers(zip_path.name, members, limit) + count = len(plan) + parts = [ + zip_path.with_name(part_name(zip_path.name, index, count)) + for index in range(1, count + 1) + ] + sizes = [ + _END.size + _marker_weight(zip_path.name, index, count) + + sum(_weight(info) for info in chosen) + for index, chosen in enumerate(plan, 1) + ] + try: + with open(zip_path, "rb") as source: + for index, (dest, chosen) in enumerate(zip(parts, plan), 1): + marker = (marker_name(zip_path.name, index, count), + marker_text(zip_path.name, index, sizes)) + _write_part(source, chosen, dest, marker) + if dest.stat().st_size != sizes[index - 1]: + raise ValueError( + f"{dest.name} is {dest.stat().st_size:,} bytes, its marker " + f"says {sizes[index - 1]:,}" + ) + found: list[tuple[str, int, int]] = [] + for dest in parts: + with zipfile.ZipFile(dest) as archive: + damaged = archive.testzip() + if damaged: + raise ValueError(f"{dest.name}: {damaged} does not read back") + found.extend(_identity(archive)) + if dest.stat().st_size >= limit: + raise ValueError(f"{dest.name} reached the limit of {limit:,} bytes") + if found != expected: + raise ValueError(f"the parts of {zip_path.name} do not add up to it") + except (OSError, ValueError, zipfile.BadZipFile): + for dest in parts: + dest.unlink(missing_ok=True) + raise + zip_path.unlink() + return parts + + +def split_directory(directory: Path, limit: int = ASSET_LIMIT) -> list[Path]: + """Split every pack of a directory that needs it. Returns what to publish.""" + published: list[Path] = [] + for path in sorted(Path(directory).glob(f"*{PACK_SUFFIX}")): + published.extend(split_pack(path, limit)) + return published diff --git a/scripts/packpaths.py b/scripts/packs/paths.py similarity index 100% rename from scripts/packpaths.py rename to scripts/packs/paths.py diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py new file mode 100644 index 000000000..b9f4fa492 --- /dev/null +++ b/scripts/packs/platformpack.py @@ -0,0 +1,1142 @@ +"""Building a platform pack: plan, variant choice, slot settlement, the archive.""" + +from __future__ import annotations + +import contextlib +import os +import tempfile +import zipfile +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, TypedDict + +from core.hashing import compute_hashes +from core.paths import sanitize_pack_path +from model.alternatives import core_file_spares +from model.declarations import OUTER_ROOTS, declared_root +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from model.safeparse import yaml_load +from packs import slots +from packs.archive import ( + CASE_FOLDING_OS, + PackRecord, + _Placed, + _add_pack_member, + _add_zip_to_pack, + _extract_zip_to_archive, + _reject_unknown, + _same_bytes, + _write_generated_member, + _writing_pack, +) +from packs.datatrees import _data_directory_members, core_data_trees, pack_markers +from packs.extras import ( + ExtraResolver, + _collect_emulator_extras, + _detect_extras_prefix, + extra_full_destination, + extra_region_key, + extras_for_systems as _extras_for_systems, + platform_region_groups, + undeclared_report, +) +from packs.naming import _narrowings, _platform_pack_name +from packs.paths import _flat, save_layout +from packs.readme import _build_agnostic_rename_readme, _build_readme, save_place +from resolve import packfiles as packresolve, regions as resolve_regions, slot as slot_mod +from resolve.contentlayout import TARGET_KEY +from resolve.cores import platform_scope_systems, system_scope_error +from resolve.gamedata import GameDataCut, without_game_data +from resolve.nativemode import digest_algorithm, hash_mismatch_excludes_file, reads_file_contents +from resolve.packfiles import ( + download_external, + preferred_entries as _preferred_entries, + resolve_declaration, + resolve_file, +) +from resolve.validation import ( + _build_validation_index, + _parse_validation, + agnostic_substitute, + baseline_verdict, + destination_owners, + existence_discrepancy, + extra_alternatives, + validated_choice, +) + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def _case_twin_pairs( + twins: list[str], seen_destinations: set[str], base_dest: str, flatten: bool, +) -> list[tuple[str, str]]: + """Each spelling left out, with the spelling the pack holds.""" + held = { + _flat(dest, base_dest, flatten).lower(): _flat(dest, base_dest, flatten) + for dest in seen_destinations + } + return sorted({(twin, held[twin.lower()]) for twin in twins if twin.lower() in held}) + + +def _report_pack_counts( + zip_path: str, + file_status: dict, + total_files: int, + core_count: int, + source: str, + verification_mode: str, + tree_count: int = 0, +) -> None: + """Print the line the pipeline's consistency check reads. + + The check compares these counts against what verify.py reports for + the same platform, so the wording is a contract: parse_pack_counts + in pipeline.py matches on it. + """ + files_ok = sum(1 for s in file_status.values() if s == "ok") + files_untested = sum(1 for s in file_status.values() if s == "untested") + files_excluded = sum(1 for s in file_status.values() if s == "excluded") + files_miss = sum(1 for s in file_status.values() if s == "missing") + total_checked = len(file_status) + + parts = [f"{files_ok}/{total_checked} files OK"] + if files_untested: + parts.append(f"{files_untested} untested") + if files_excluded: + parts.append(f"{files_excluded} unsafe excluded") + if files_miss: + parts.append(f"{files_miss} missing") + if source == "platform": + print( + f" {zip_path}: {total_files} files packed (platform baseline only), " + f"{', '.join(parts)} [{verification_mode}]" + ) + elif source == "truth": + print( + f" {zip_path}: {total_files} files packed (ground truth only), " + f"{core_count} from emulator profiles [{verification_mode}]" + ) + else: + baseline = total_files - core_count - tree_count + trees = f"{tree_count} in core data trees + " if tree_count else "" + print( + f" {zip_path}: {total_files} files packed ({baseline} baseline + " + f"{trees}{core_count} from cores), {', '.join(parts)} [{verification_mode}]" + ) + +class _VariantOptions(TypedDict, total=False): + """The keyword options of _select_variants.""" + + regions: list[str] | None + one_per_slot: bool + required_only: bool + undeclared: list[dict] | None + zip_contents: dict | None + data_registry: dict | None + slot_overrides: dict[str, str] | None + + +def _select_variants( + config: dict, + pack_systems: dict, + emulators_dir: str, + db: dict, + base_dest: str, + emu_profiles: dict | None, + target_cores: set[str] | None, + source: str, + **options: Unpack[_VariantOptions], +) -> tuple[set, list, list]: + """Which regional and slot alternatives this pack leaves out. + + Both reductions are decided once, over the platform baseline and the + core extras together: deciding them separately is how the report and + the pack came to withdraw different files for the same request. + Returns the destinations to drop, the groups kept only as a + fallback, and the slots no profile puts in order. + """ + _reject_unknown("_select_variants", options, _VariantOptions.__optional_keys__) + regions = options.get("regions") + one_per_slot = options.get("one_per_slot", False) + region_drops: set[str] = set() + region_fallbacks: list[str] = [] + # One grouping for both passes: a file judged in its own system by one + # pass must not land in every system of its profile for the other. + region_groups: dict[str, list[tuple[str, str]]] = {} + held: set[str] = set() + if regions or one_per_slot: + region_groups, _extra_dests = platform_region_groups( + config, + pack_systems, + emulators_dir, + db, + base_dest, + emu_profiles, + target_cores=target_cores, + include_extras=(source != "platform"), + include_all=(source == "truth"), + required_only=options.get("required_only", False), + held_out=held, + undeclared=options.get("undeclared"), + zip_contents=options.get("zip_contents"), + data_registry=options.get("data_registry"), + slot_overrides=options.get("slot_overrides"), + ) + if regions: + region_index = resolve_regions.platform_region_index( + config, emu_profiles or {}, target_cores + ) + region_drops = resolve_regions.resolve_region_drops( + region_groups, region_index, regions, held + ) + region_fallbacks = resolve_regions.fallback_groups( + region_groups, region_index, regions + ) + + slot_undecidable: list[str] = [] + if one_per_slot: + slot_drops, slot_undecidable = _slot_drops( + config, emu_profiles, target_cores, region_groups, region_drops, held + ) + region_drops = region_drops | slot_drops + if slot_undecidable: + print( + f" {len(slot_undecidable)} slot(s) with no declared order: " + f"every candidate kept" + ) + + return region_drops, region_fallbacks, slot_undecidable + + +def _slot_drops( + config: dict, + emu_profiles: dict | None, + target_cores: set[str] | None, + region_groups: dict[str, list[tuple[str, str]]], + region_drops: set[str], + held: set[str], +) -> tuple[set[str], list[str]]: + """What --one-per-slot withdraws once the regions have, and the slots no + declared order decides. The pack and the manifest both read it.""" + slot_groups = { + sys_id: [(d, n) for d, n in members if d not in region_drops] + for sys_id, members in region_groups.items() + } + return slot_mod.resolve_slot_drops( + slot_groups, + slot_mod.platform_slot_index(config, emu_profiles or {}, target_cores), + held, + ) + + +def _matches_an_alternative(fe: dict, local_path: str, profiles: dict) -> bool: + """Whether the copy is another version the same profile accepts there. + + A profile lists every version its code takes under one name (each GRP + of Raze's table, eduke32's demo and retail NWINTER.GRP). The extra + carries the first, and the held copy matching a sibling is no mismatch. + """ + siblings = extra_alternatives(fe, profiles) + if len(siblings) < 2: + return False + # A sibling the code takes without a check (Raze's "BLOOD: Unknown + # Version") accepts whatever copy fills the slot. + if any(not _parse_validation(entry.get("validation")) for entry in siblings): + return True + actual = compute_hashes(local_path, frozenset({"sha1", "md5", "crc32"})) + for entry in siblings: + for algorithm in ("sha1", "md5", "crc32"): + declared = entry.get(algorithm) + values = declared if isinstance(declared, list) else [declared] + if any(v and str(v).lower() == actual.get(algorithm, "") for v in values): + return True + return False + + +def _report_left_out(cut: GameDataCut, systems: set[str], cores: bool) -> None: + """Name the game data a --no-game-data build left out, and why. + + ``systems`` limits the platform layer to the systems this pack covers, + and ``cores`` says whether this pack collected the core files itself: + a split part does not, its run names them once. + """ + kept = [ + item for item in cut.left_out + if (item.layer == "platform" and item.system in systems) + or (item.layer == "core" and cores) + ] + for line in GameDataCut(cut.config, cut.profiles, kept).report_lines(): + print(f" {line}") + + +class PackNarrowing(TypedDict, total=False): + """How a platform pack is narrowed, shared by a pack and its split parts.""" + + emulators_dir: str + zip_contents: dict | None + data_registry: dict | None + emu_profiles: dict | None + target_cores: set[str] | None + required_only: bool + source: str + regions: list[str] | None + target_name: str | None + one_per_slot: bool + offline: bool | None + no_game_data: bool + + +class _PartScope(TypedDict, total=False): + """What one split part keeps of the platform.""" + + system_filter: list[str] | None + precomputed_extras: list[dict] | None + extras_only: bool + + +class PackOptions(PackNarrowing, _PartScope, total=False): + """The keyword options of generate_pack.""" + + flatten: bool + pack_name: str | None + record: PackRecord | None + within: dict[str, str] | None + + +@dataclass(frozen=True) +class _PackSettings: + """PackOptions with their defaults.""" + + emulators_dir: str = "emulators" + zip_contents: dict | None = None + data_registry: dict | None = None + emu_profiles: dict | None = None + target_cores: set[str] | None = None + required_only: bool = False + system_filter: list[str] | None = None + precomputed_extras: list[dict] | None = None + extras_only: bool = False + source: str = "full" + flatten: bool = True + regions: list[str] | None = None + target_name: str | None = None + one_per_slot: bool = False + offline: bool | None = None + pack_name: str | None = None + no_game_data: bool = False + record: PackRecord | None = None + within: dict[str, str] | None = None + + +@dataclass +class _PlatformPlan: + """What a platform pack is built from, settled before its first member.""" + + platform_name: str + platforms_dir: str + db: dict + bios_dir: str + opts: _PackSettings + config: dict + emu_profiles: dict + zip_contents: dict + cut: GameDataCut | None + narrowings: list[tuple[str, str]] + zip_path: str + validation_index: dict + platform_profiles: dict[str, dict] + validation_owners: dict + slot_overrides: dict[str, str] + pack_systems: dict + preferred_entries: dict[str, int] = field(default_factory=dict) + undeclared: list[dict] | None = None + region_drops: set[str] = field(default_factory=set) + region_fallbacks: list = field(default_factory=list) + slot_undecidable: list[str] = field(default_factory=list) + + @property + def verification_mode(self) -> str: + return self.config.get("verification_mode", "existence") + + @property + def platform_display(self) -> str: + return self.config.get("platform", self.platform_name) + + @property + def base_dest(self) -> str: + return self.config.get("base_destination", "") + + @property + def case_insensitive(self) -> bool: + # Case-insensitive dedup only for platforms targeting Windows/macOS. + # Linux-only platforms (Batocera, Recalbox, RetroDECK, Lakka, RomM) + # are case-sensitive and may have distinct files like DISK.ROM vs disk.rom. + return self.config.get("case_insensitive_fs", False) + + +def _plan_platform_pack( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + output_dir: str, + opts: _PackSettings, +) -> _PlatformPlan | None: + """The configuration, scope and checks a platform pack reads, or None + when the systems asked for leave nothing to build.""" + config = load_platform_config(platform_name, platforms_dir) + if opts.target_name: + config = {**config, TARGET_KEY: opts.target_name} + zip_contents = {} if opts.zip_contents is None else opts.zip_contents + emu_profiles = opts.emu_profiles + if emu_profiles is None: + # The pipeline always passes them, but a caller that does not must get the + # same pack, not one built without validation, slots or agnostic cores. + emu_profiles = load_emulator_profiles(opts.emulators_dir) + # Cut from the full config and profiles: the category of a platform + # entry is read from the profiles' game data entries. + cut = ( + without_game_data(config, emu_profiles, opts.data_registry, opts.target_cores) + if opts.no_game_data else None + ) + if cut is not None: + config, emu_profiles = cut.config, cut.profiles + + narrowings = _narrowings( + opts.source, opts.regions, opts.target_name, opts.one_per_slot, opts.required_only, + no_game_data=opts.no_game_data, + ) + zip_path = os.path.join( + output_dir, + _platform_pack_name( + platform_name, platforms_dir, narrowings, opts.system_filter, opts.pack_name + ), + ) + if opts.record is None: + os.makedirs(output_dir, exist_ok=True) + + # Build emulator-level validation index from the platform's own + # emulators (same scope as verify.py) + from resolve.cores import resolve_platform_cores + + validation_index = {} + platform_profiles: dict[str, dict] = {} + if emu_profiles: + platform_profiles = { + name: emu_profiles[name] + for name in resolve_platform_cores(config, emu_profiles) + } + validation_index = _build_validation_index(platform_profiles) + validation_owners = destination_owners(platform_profiles) + slot_overrides = slots.pack_overrides( + config, emu_profiles or {}, db, zip_contents, opts.data_registry, + target_cores=opts.target_cores, source=opts.source, + ) + + pack_systems = platform_scope_systems( + config, emu_profiles or {}, opts.target_cores, opts.system_filter + ) + if opts.system_filter and not pack_systems: + reason = system_scope_error(config, platform_name, opts.system_filter, opts.target_name) + print(f" WARNING: {reason}") + return None + if opts.extras_only: + # The part of a split that carries the core extras no platform system + # owns: the platform's own files and trees went to the other parts. + pack_systems = {} + + plan = _PlatformPlan( + platform_name, platforms_dir, db, bios_dir, opts, config, emu_profiles, + zip_contents, cut, narrowings, zip_path, validation_index, platform_profiles, + validation_owners, slot_overrides, pack_systems, + ) + _settle_pack_choices(plan) + return plan + + +def _settle_pack_choices(plan: _PlatformPlan) -> None: + """The declaration each destination takes and the variants left out.""" + opts = plan.opts + if opts.source != "truth": + # Decided among the declarations this pack keeps: a preferred entry + # that --required-only drops must not silence its required twin, or + # the destination leaves the pack without a trace (RetroDECK's four + # Atari 5200 ROMs, optional under atari-400-800 and required under + # atari-5200). No data directories: the choice is about the baseline. + plan.preferred_entries = _preferred_entries( + plan.pack_systems, plan.db, plan.bios_dir, plan.base_dest, opts.required_only, + plan.zip_contents, opts.offline, + ) + + # Region selection is decided once, over both the platform baseline and the + # core extras, so the two phases below consult a single set. Grouping uses a + # dedicated extras pass with an empty seen set: it only needs group + # membership, never destinations, and a superset of members is the safe + # direction. Runs only when --region is given. + # The gap report both extras passes read, computed once: the region + # grouping and the core complement below ask it the same question. + plan.undeclared = ( + undeclared_report( + plan.config, opts.emulators_dir, plan.db, plan.emu_profiles, opts.target_cores, + include_all=(opts.source == "truth"), + ) + if opts.source != "platform" and opts.precomputed_extras is None + else None + ) + plan.region_drops, plan.region_fallbacks, plan.slot_undecidable = _select_variants( + plan.config, plan.pack_systems, opts.emulators_dir, plan.db, plan.base_dest, + plan.emu_profiles, opts.target_cores, opts.source, regions=opts.regions, + one_per_slot=opts.one_per_slot, required_only=opts.required_only, + undeclared=plan.undeclared, zip_contents=plan.zip_contents, + data_registry=opts.data_registry, slot_overrides=plan.slot_overrides, + ) + + +_STATUS_LABELS = {"untested": "UNTESTED", "excluded": "EXCLUDED", "missing": "MISSING"} + + +@dataclass +class _PlatformPackBuild: + """One platform pack being written: its members and what each slot came to. + + The four lookups are bound by generate_pack, the one place that says how + a platform file and a core extra are found and judged. + """ + + plan: _PlatformPlan + zf: zipfile.ZipFile | PackRecord + resolve: Callable[[dict, str], tuple[str | None, str]] + verdict: Callable[[dict, str | None, str], tuple[str, str | None]] + judge: Callable[[dict, str | None, str], tuple[str | None, str | None]] + resolve_extra: Callable[[dict, str], tuple[str | None, str, str]] + placed: _Placed = field(init=False) + total_files: int = 0 + core_count: int = 0 + save_count: int = 0 + tree_count: int = 0 + # Per-destination status. ``excluded`` means a same-named local payload + # exists but contradicts the declaration and is intentionally not shipped. + # It is distinct from a genuine coverage gap (``missing``). + file_status: dict[str, str] = field(default_factory=dict) + file_reasons: dict[str, str] = field(default_factory=dict) + # Core extras whose local copy contradicts the profile hash: packed, + # reported, and never counted against the platform's own file total. + core_discrepancies: list[str] = field(default_factory=list) + # Spellings left out as case twins of a packed file, for the README. + case_twins: list[str] = field(default_factory=list) + + def __post_init__(self) -> None: + self.placed = _Placed(self.plan.case_insensitive) + + def _flat(self, path: str) -> str: + return _flat(path, self.plan.base_dest, self.plan.opts.flatten) + + def run(self) -> None: + if self.plan.opts.source != "truth": + for sys_id, system in sorted(self.plan.pack_systems.items()): + for file_entry in system.get("files", []): + self._pack_declared(sys_id, file_entry) + # Core requirements: files platform's cores need but YAML doesn't declare + self._pack_core_files() + self._pack_trees() + self._write_readme() + + def _judge_conflict(self, file_entry: dict, full_dest: str) -> None: + # Content ships under the conflicting shape (file vs dir, + # e.g. SGB1.sfc). verify.py resolves each declaration on + # its own, so this one is counted by what it resolves to: + # an unresolved one counted OK had the pack claim a file + # verify reports missing. + plan = self.plan + conflict_path, conflict_status = resolve_file( + file_entry, plan.db, plan.bios_dir, plan.zip_contents, + data_dir_registry=plan.opts.data_registry, offline=plan.opts.offline, + ) + # The verdict of the main path: a zipped_file archive is + # judged by the member inside, and a frontend that hashes + # one digest accepts a file another declared hash + # contradicts, as verify judges it. + conflict_status, refusal = baseline_verdict( + file_entry, conflict_path, conflict_status, plan.verification_mode, + plan.config.get("hash_rule", ""), + ) + if conflict_status == "not_found": + self.file_status[full_dest] = "missing" + self.file_reasons[full_dest] = "not found" + elif refusal: + self.file_status[full_dest] = "excluded" + self.file_reasons[full_dest] = refusal + else: + self.file_status.setdefault(full_dest, "ok") + + def _pack_declared(self, sys_id: str, file_entry: dict) -> None: + plan, opts = self.plan, self.plan.opts + if opts.required_only and file_entry.get("required") is False: + return + dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) + if plan.region_drops and dest in plan.region_drops: + return + if not dest: + self._judge_unnamed(sys_id, file_entry) + return + full_dest = f"{plan.base_dest}/{dest}" if plan.base_dest else dest + already_packed = self.placed.holds(full_dest) + + preferred = plan.preferred_entries.get(full_dest) + if preferred is not None and id(file_entry) != preferred: + return + if self.placed.conflicts(full_dest): + self._judge_conflict(file_entry, full_dest) + return + storage = file_entry.get("storage", "embedded") + if storage == "user_provided": + if not already_packed: + self._write_instructions(file_entry, full_dest) + return + + local_path, status = self.resolve(file_entry, full_dest) + if status == "external": + self._pack_external(file_entry, full_dest) + return + if status == "not_found": + local_path = self._agnostic_fallback(sys_id, file_entry, full_dest, already_packed) + if local_path is None: + return + status = "agnostic_fallback" + # Fall through to normal packing below + chosen = self._settle_declared(file_entry, full_dest, dest, local_path, status, already_packed) + if chosen is not None: + self._ship_declared(file_entry, full_dest, chosen, already_packed) + + def _judge_unnamed(self, sys_id: str, file_entry: dict) -> None: + # EmuDeck-style entries (system:md5 whitelist, no filename). + # Judged as verify judges it: resolved on disk, the md5 + # list parsed once (case, comma lists). + plan = self.plan + fkey = f"{sys_id}/{file_entry.get('name', '')}" + held, held_status = resolve_file( + file_entry, plan.db, plan.bios_dir, plan.zip_contents, + data_dir_registry=plan.opts.data_registry, offline=plan.opts.offline, + ) + if held_status == "not_found" or not held: + self.file_status[fkey] = "missing" + elif self.verdict(file_entry, held, held_status)[1]: + self.file_status[fkey] = "excluded" + else: + self.file_status.setdefault(fkey, "ok") + + def _write_instructions(self, file_entry: dict, full_dest: str) -> None: + base_dest = self.plan.base_dest + self.placed.take(full_dest) + self.file_status.setdefault(full_dest, "ok") + instructions = file_entry.get( + "instructions", "Please provide this file manually." + ) + instr_name = f"INSTRUCTIONS_{file_entry['name']}.txt" + instr_path = ( + f"{base_dest}/{instr_name}" if base_dest else instr_name + ) + _write_generated_member( + self.zf, + self._flat(instr_path), + f"File needed: {file_entry['name']}\n\n{instructions}\n", + ) + self.total_files += 1 + + def _pack_external(self, file_entry: dict, full_dest: str) -> None: + file_ext = os.path.splitext(file_entry["name"])[1] or "" + with tempfile.NamedTemporaryFile( + delete=False, suffix=file_ext, dir=packresolve.scratch_dir() + ) as tmp: + tmp_path = tmp.name + + # The slot is the platform's file whether the download + # arrives or not: verify cannot fetch, and a core file + # filling it on a failed download made the two differ. + self.placed.take(full_dest) + try: + if self.plan.opts.record is None and download_external(file_entry, tmp_path): + extract = file_entry.get("extract", False) + if extract and tmp_path.endswith(".zip"): + _extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf) + else: + _add_pack_member(self.zf, tmp_path, self._flat(full_dest)) + self.file_status.setdefault(full_dest, "ok") + self.total_files += 1 + else: + self.file_status[full_dest] = "missing" + self.file_reasons[full_dest] = "external download failed" + finally: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + + def _agnostic_fallback( + self, sys_id: str, file_entry: dict, full_dest: str, already_packed: bool, + ) -> str | None: + # A filename-agnostic core takes any image of its system, + # renamed. Only an existence frontend accepts that. + plan = self.plan + found = None + if not reads_file_contents(plan.verification_mode): + found = agnostic_substitute(file_entry, sys_id, plan.db, plan.platform_profiles) + if not found or not found[0]: + if not already_packed: + self.file_status[full_dest] = "missing" + self.file_reasons[full_dest] = "not found" + return None + local_path, agnostic_path = found + original_name = os.path.basename(local_path) + dest_name = file_entry.get("name", "") + if original_name != dest_name and agnostic_path: + alt_names = [ + entry.get("name", "") + for entry in plan.db.get("files", {}).values() + if entry.get("path", "").startswith(agnostic_path) + and entry.get("name", "") and entry.get("name", "") != original_name + ] + readme_text = _build_agnostic_rename_readme(dest_name, original_name, alt_names) + readme_name = f"RENAMED_{dest_name}.txt" + readme_full = f"{plan.base_dest}/{readme_name}" if plan.base_dest else readme_name + if readme_full not in self.placed.destinations: + _write_generated_member(self.zf, self._flat(readme_full), readme_text) + self.placed.destinations.add(readme_full) + return local_path + + def _settle_declared( + self, + file_entry: dict, + full_dest: str, + dest: str, + local_path: str | None, + status: str, + already_packed: bool, + ) -> str | None: + """The copy a declaration ships once judged, or None when refused.""" + plan = self.plan + # The verdict the install manifest reads too: a member missing + # from a zipped_file archive, or a hash the frontend rejects. + status, refusal = self.verdict(file_entry, local_path, status) + if refusal: + # An earlier declaration of this path shipped a file this + # one refuses: it is in the pack, untested as verify + # counts it, not excluded. + self.file_status[full_dest] = "untested" if already_packed else "excluded" + self.file_reasons[full_dest] = refusal + return None + if not hash_mismatch_excludes_file(plan.verification_mode) and ( + status == "hash_mismatch" and local_path + ): + # Existence platforms accept any file at the declared path: + # their code never reads the bytes. An upstream hash that + # contradicts a local dump is reported, not acted on. + self.file_reasons.setdefault( + full_dest, + existence_discrepancy(file_entry, local_path, plan.platform_display), + ) + if self.file_status.get(full_dest) == "missing": + # An earlier declaration of this path found nothing, and this + # one fills it, as verify counts it. + del self.file_status[full_dest] + self.file_reasons.pop(full_dest, None) + self.file_status.setdefault(full_dest, "ok") + + # Emulator-level validation: informational only for platform packs. + # Platform verification (existence/md5) is the authority for pack status. + # Emulator checks are supplementary: logged but don't downgrade. + # When a discrepancy is found, try to find a file satisfying both. + if self.file_status.get(full_dest) == "ok": + local_path, disagreement = self.judge(file_entry, local_path, dest) + if disagreement: + self.file_reasons.setdefault( + full_dest, f"{plan.platform_display} says OK but {disagreement}" + ) + return local_path + + def _ship_declared( + self, file_entry: dict, full_dest: str, local_path: str, already_packed: bool, + ) -> None: + within = self.plan.opts.within + if already_packed: + if full_dest not in self.placed.destinations: + self.case_twins.append(self._flat(full_dest)) + return + if within is not None and not _same_bytes(local_path, within.get(self._flat(full_dest))): + # The full pack holds another system's file here. + return + if self.file_status.get(full_dest) == "excluded": + # An earlier declaration refused the file this one ships. + self.file_status[full_dest] = "untested" + self.placed.take(full_dest) + + extract = file_entry.get("extract", False) + flat_dest = self._flat(full_dest) + if extract and local_path.endswith(".zip"): + _extract_zip_to_archive(local_path, flat_dest, self.zf) + elif local_path.endswith(".zip"): + _add_zip_to_pack(local_path, flat_dest, self.zf, file_entry) + else: + _add_pack_member(self.zf, local_path, flat_dest) + self.total_files += 1 + + def _region_dropped(self, fe: dict) -> bool: + drops = self.plan.region_drops + return bool(drops) and extra_region_key(fe, declared_root(self.plan.config)) in drops + + def _spares(self, files: list[dict]) -> set[int]: + if not self.plan.opts.required_only: + return set() + return core_file_spares(files, self._region_dropped) + + def _core_files(self) -> list[dict]: + plan, opts = self.plan, self.plan.opts + if opts.source == "platform": + return [] + if opts.precomputed_extras is not None: + return opts.precomputed_extras + if opts.system_filter: + # The systems asked for, with what their cores need: the split + # packs get exactly this, and a full pack of one system had none. + return _extras_for_systems( + _collect_emulator_extras( + plan.config, opts.emulators_dir, plan.db, set(), plan.base_dest, + plan.emu_profiles, target_cores=opts.target_cores, + include_all=(opts.source == "truth"), undeclared=plan.undeclared, + ), + opts.system_filter, + ) + return _collect_emulator_extras( + plan.config, + opts.emulators_dir, + plan.db, + self.placed.destinations, + plan.base_dest, + plan.emu_profiles, + target_cores=opts.target_cores, + include_all=(opts.source == "truth"), + undeclared=plan.undeclared, + ) + + def _pack_core_files(self) -> None: + core_files = self._core_files() + spares = self._spares(core_files) + for fe in core_files: + if self.plan.opts.required_only and (fe.get("required") is False or id(fe) in spares): + continue + self._pack_core_file(fe) + + def _pack_core_file(self, fe: dict) -> None: + plan = self.plan + dest = sanitize_pack_path(fe.get("destination", fe["name"])) + if self._region_dropped(fe): + return + if not dest: + return + if fe.get("root") in OUTER_ROOTS: + # Read below the roms directory or in an emulator folder: the + # pack is extracted into the BIOS folder and cannot reach + # them, the installer places these files. + return + # Core extras: _collect_emulator_extras already adjusted + # destinations for slug-based platforms. Apply the effective + # prefix (base_dest, or inferred from YAML when base_dest is + # empty, as RetroDECK infers "bios"). A file read below the save + # directory goes to the pack's save folder instead. + full_dest = extra_full_destination( + fe, _detect_extras_prefix(plan.config, plan.base_dest) + ) + if not full_dest: + return + # Taken, a case twin on a case-insensitive filesystem, or a + # file/directory conflict (SGB1.sfc vs SGB1.sfc/): verify replays + # the same rule (packextras.hidden_extras). + block = self.placed.block(full_dest) + if block: + if block == "case_twin" and self.resolve_extra(fe, dest)[0]: + self.case_twins.append(self._flat(full_dest)) + return + + # The emulator's own check picks the copy, as for a declared file + # and in the emulator pack: the name led RetroArch's GC/dsp_rom.bin + # to Dolphin's obsolete v0.3.1 free ROM, beside Nintendo's coef + # ROM, a pair Dolphin warns about at every start. + local_path, status, disagreement = self.resolve_extra(fe, dest) + if not local_path: + return + self._note_core_discrepancy(fe, full_dest, local_path, status, disagreement) + + flat_dest = self._flat(full_dest) + within = plan.opts.within + if within is not None and not _same_bytes(local_path, within.get(flat_dest)): + return + if local_path.endswith(".zip"): + _add_zip_to_pack(local_path, flat_dest, self.zf, fe) + else: + _add_pack_member(self.zf, local_path, flat_dest) + if self.file_status.get(full_dest) in ("missing", "excluded"): + self._core_fills_declaration(fe, full_dest) + self.placed.take(full_dest) + self.core_count += 1 + if fe.get("root") == "save": + self.save_count += 1 + self.total_files += 1 + + def _note_core_discrepancy( + self, fe: dict, full_dest: str, local_path: str, status: str, disagreement: str, + ) -> None: + if disagreement: + self.core_discrepancies.append(f"{full_dest}: {disagreement}") + if status == "hash_mismatch" and not _matches_an_alternative( + fe, local_path, self.plan.emu_profiles or {} + ): + # The core's declared hash comes from its source, the local dump + # is what the collection holds. Shipping it keeps the emulator + # working when the code never reads the hash, and the divergence is + # reported so it can be resolved at the profile or the dump. + # file_status tracks platform declarations only, so the report + # goes to its own list and never moves the pack's own count. + self.core_discrepancies.append( + f"{full_dest}: declared hash of " + f"{fe.get('source_profile') or fe.get('source_emulator', 'core profile')}" + " does not match the packed copy" + ) + + def _core_fills_declaration(self, fe: dict, full_dest: str) -> None: + source_name = fe.get("source_profile") or fe.get( + "source_emulator", "core profile" + ) + if reads_file_contents(self.plan.verification_mode): + # The frontend hashes what sits at the path, and the core's + # copy is not the hash it declares: the file ships for the + # core, the platform's own check still fails, as verify says. + self.file_reasons[full_dest] = ( + "platform-declared hash unavailable; " + f"packed the validated {source_name} requirement, " + "which the platform check does not accept" + ) + else: + # An existence frontend is satisfied by any file at the path. + self.file_status[full_dest] = "ok" + self.file_reasons.pop(full_dest, None) + + def _pack_trees(self) -> None: + plan, opts = self.plan, self.plan.opts + # The trees the cores read follow them as their extras do: by the + # systems asked for, and those of no system in the part of their own. + core_trees = ( + [] if opts.source == "platform" + else core_data_trees( + plan.config, plan.emu_profiles, plan.platform_name, opts.data_registry, + opts.target_cores, + ) + ) + if opts.extras_only: + owned = list(platform_scope_systems(plan.config, plan.emu_profiles, opts.target_cores)) + core_trees = [t for t in core_trees if not _extras_for_systems([t], owned)] + elif opts.system_filter: + core_trees = _extras_for_systems(core_trees, opts.system_filter) + # Counted apart: the trees a core reads are not on the platform's + # list. MyMinUI declares nothing and its line read "6944 baseline". + self.total_files += self._pack_data_directories(plan.pack_systems, ()) + self.tree_count = self._pack_data_directories({}, core_trees) + self.total_files += self.tree_count + + def _pack_data_directories(self, pack_systems: dict, core_trees: Iterable[dict]) -> int: + """Add the data directories to the pack. Returns how many files went in.""" + plan = self.plan + required_only = plan.opts.required_only + seen_parents = self.placed.parents + added = 0 + for src, full in _data_directory_members( + pack_systems, plan.opts.data_registry, plan.platform_name, plan.base_dest, + self.placed.fold, self.placed.destinations, self.placed.lower, + seen_parents, required_only=required_only, + core_trees=core_trees, + ): + _add_pack_member(self.zf, src, self._flat(full)) + if isinstance(self.zf, PackRecord): + self.zf.trees.append(self._flat(full)) + added += 1 + return added + + def _unfolded_twins(self) -> None: + # The spellings a folded platform counts as declared never reach + # the extras: collected as the filesystem that keeps case sees + # them, as the manifest's case_variants are (Mesen-CE's bios.col + # beside the declared BIOS.col). + plan, opts = self.plan, self.plan.opts + unfolded = _collect_emulator_extras( + {**plan.config, "case_insensitive_fs": False}, opts.emulators_dir, plan.db, set(), + plan.base_dest, plan.emu_profiles, target_cores=opts.target_cores, + include_all=(opts.source == "truth"), + ) + if opts.system_filter: + unfolded = _extras_for_systems(unfolded, opts.system_filter) + prefix = _detect_extras_prefix(plan.config, plan.base_dest) + unfolded_spares = self._spares(unfolded) + for fe in unfolded: + if opts.required_only and (fe.get("required") is False or id(fe) in unfolded_spares): + continue + if self._region_dropped(fe): + continue + full = extra_full_destination(fe, prefix) + if ( + full and full not in self.placed.destinations and full.lower() in self.placed.lower + and self.resolve_extra( + fe, sanitize_pack_path(fe.get("destination", fe["name"])) + )[0] + ): + self.case_twins.append(self._flat(full)) + + def _write_readme(self) -> None: + # README.txt for users: personalized step-by-step per platform + plan, opts = self.plan, self.plan.opts + registry = _platform_registry(plan.platforms_dir).get(plan.platform_name, {}) + install = registry.get("install", {}) or {} + keeps_case = plan.case_insensitive and any( + d.get("os") not in CASE_FOLDING_OS for d in install.get("detect", []) + ) + if keeps_case and opts.source != "platform" and opts.precomputed_extras is None: + self._unfolded_twins() + save_count = self.save_count + readme_text = _build_readme( + plan.platform_name, plan.platform_display, plan.base_dest, self.total_files, + len(plan.pack_systems), + source=opts.source, + contributors=registry.get("contributed_by", []), + regions=opts.regions, + fallback_systems=plan.region_fallbacks, + one_per_slot=opts.one_per_slot, + undecidable_slots=plan.slot_undecidable, + narrowings=plan.narrowings, + system_filter=opts.system_filter, + detect=install.get("detect", []), + standalone_copies=install.get("standalone_copies", []), + launch_folders=len(plan.config.get("core_system_dirs") or {}), + save_folder=(save_layout(plan.config).in_pack if save_count else ""), + save_where=( + save_place( + str(registry.get("extract_to") or ""), + save_layout(plan.config).folder, plan.base_dest, + ) if save_count else "" + ), + save_by_system=bool(save_count and save_layout(plan.config).by_system), + case_twins=( + _case_twin_pairs( + self.case_twins, self.placed.destinations, plan.base_dest, opts.flatten + ) + if keeps_case else [] + ), + ) + _write_generated_member(self.zf, "README.txt", readme_text) + for marker in pack_markers(plan.platform_name, opts.target_name, plan.platforms_dir): + _write_generated_member( + self.zf, + self._flat(f"{plan.base_dest}/{marker}" if plan.base_dest else marker), + "", + ) + + def report(self) -> None: + plan, opts = self.plan, self.plan.opts + _report_pack_counts( + plan.zip_path, self.file_status, self.total_files, self.core_count, opts.source, + plan.verification_mode, tree_count=self.tree_count, + ) + if plan.cut is not None: + _report_left_out( + plan.cut, + systems=set(plan.pack_systems) if opts.source != "truth" else set(), + cores=opts.source != "platform" and opts.precomputed_extras is None, + ) + for key, reason in sorted(self.file_reasons.items()): + label = _STATUS_LABELS.get(self.file_status.get(key, ""), "DISCREPANCY") + print(f" {label}: {key}: {reason}") + for note in sorted(self.core_discrepancies): + print(f" DISCREPANCY: {note}") + + +def _platform_registry(platforms_dir: str) -> dict: + """The platforms of _registry.yml, or nothing when the file is absent.""" + registry_path = Path(platforms_dir) / "_registry.yml" + if not registry_path.exists(): + return {} + with open(registry_path) as f: + return (yaml_load(f) or {}).get("platforms", {}) + + +def generate_pack( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + output_dir: str, + **options: Unpack[PackOptions], +) -> str | None: + """Generate a ZIP pack for a platform. + + ``no_game_data`` leaves out the platform's entries categorized as game + data and the cores' ``category: game_data`` files, and names each one. + + ``pack_name`` replaces the derived file name: a split part is named after + its group, and a name built from every system of a hundred-system group + is longer than a file name can be. + + ``record`` builds the pack in memory (PackRecord): no archive is written, + no external file fetched, and the paths are kept on it. + + ``within`` is the full pack's PackRecord.sources, given to a split part: + a declared file or core extra is written only where the full pack writes + the same bytes. A part sees neither the other systems' declarations nor + their extras, so a path the full pack settles (a file/directory conflict, + a case twin, a path another system's file takes) was written again. + + Returns the path to the generated ZIP, or None on failure. + """ + _reject_unknown("generate_pack", options, PackOptions.__optional_keys__) + opts = _PackSettings(**options) + plan = _plan_platform_pack(platform_name, platforms_dir, db, bios_dir, output_dir, opts) + if plan is None: + return None + + def resolve(file_entry: dict, full_dest: str) -> tuple[str | None, str]: + return resolve_declaration( + file_entry, + db, + bios_dir, + plan.zip_contents, + opts.data_registry, + plan.slot_overrides.get(full_dest), + offline=opts.offline, + ) + + def verdict(file_entry: dict, local_path: str | None, status: str) -> tuple[str, str | None]: + return baseline_verdict( + file_entry, local_path, status, plan.verification_mode, + plan.config.get("hash_rule", ""), + ) + + def judge(file_entry: dict, local_path: str | None, dest: str) -> tuple[str | None, str | None]: + return validated_choice( + file_entry, local_path, db, plan.validation_index, bios_dir, + digest_algorithm(plan.verification_mode), dest, plan.validation_owners, + ) + + extra_resolver = ExtraResolver( + db, bios_dir, plan.zip_contents, opts.data_registry, plan.validation_index, + plan.validation_owners, opts.offline, profiles=plan.emu_profiles, + ) + + def resolve_extra(fe: dict, dest: str) -> tuple[str | None, str, str]: + return extra_resolver.resolve(fe, dest) + + with ( + contextlib.nullcontext(opts.record) if opts.record is not None + else _writing_pack(plan.zip_path) + ) as zf: + build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra) + build.run() + build.report() + return plan.zip_path diff --git a/scripts/packreadme.py b/scripts/packs/readme.py similarity index 99% rename from scripts/packreadme.py rename to scripts/packs/readme.py index 040b70bdc..778d9e908 100644 --- a/scripts/packreadme.py +++ b/scripts/packs/readme.py @@ -7,7 +7,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, TypedDict -from packextras import reject_unknown +from packs.extras import reject_unknown from model.region import label as region_label from siteguides import INSTALL_PS1, INSTALL_SH, pack_manual diff --git a/scripts/packs/report.py b/scripts/packs/report.py new file mode 100644 index 000000000..c5a71f640 --- /dev/null +++ b/scripts/packs/report.py @@ -0,0 +1,635 @@ +"""Verify results printed for a person, per platform and per emulator.""" + +from __future__ import annotations + +from collections import Counter + +from packs.verdicts import Severity, Status +from resolve.categories import BIOS +from resolve.nativemode import reads_file_contents + + +def _format_ground_truth_aggregate(ground_truth: list[dict]) -> str: + """Format ground truth as a single aggregated line. + + Example: beetle_psx [md5], pcsx_rearmed [existence] + """ + parts = [] + for gt in ground_truth: + checks_label = "+".join(gt["checks"]) if gt["checks"] else "existence" + parts.append(f"{gt['emulator']} [{checks_label}]") + return ", ".join(parts) + + +def _format_ground_truth_verbose(ground_truth: list[dict]) -> list[str]: + """Format ground truth as one line per core with expected values and source ref. + + Example: handy validates crc32=0d973c9d,size=512 [lynx/rom.h:48-49] + """ + lines = [] + for gt in ground_truth: + checks_label = "+".join(gt["checks"]) if gt["checks"] else "existence" + expected = gt.get("expected", {}) + if expected: + vals = ",".join(f"{k}={v}" for k, v in sorted(expected.items())) + part = f"{gt['emulator']} validates {vals}" + else: + part = f"{gt['emulator']} validates {checks_label}" + if gt.get("source_ref"): + part += f" [{gt['source_ref']}]" + lines.append(part) + return lines + + +def _print_ground_truth(gt: list[dict], verbose: bool) -> None: + """Print ground truth lines for a file entry.""" + if not gt: + return + if verbose: + for line in _format_ground_truth_verbose(gt): + print(f" {line}") + else: + print(f" {_format_ground_truth_aggregate(gt)}") + + +def _discrepancy_keys(details: list[dict]) -> set[str]: + """The DISCREPANCY lines _print_detail_entries prints for these details. + + A file already reported MISSING or UNTESTED on its own ground is not + printed again as a discrepancy, and is not counted as one either. + """ + shown = { + f"{d['system']}/{d['name']}" + for d in details + if d["status"] == Status.MISSING + or (d["status"] == Status.UNTESTED and not d.get("discrepancy")) + } + return { + key + for d in details + if d.get("discrepancy") + and (key := f"{d['system']}/{d['name']}") not in shown + } + + +# A platform entry that is not firmware, as the report names it. +_NOT_FIRMWARE = { + "game_data": "game data", + "unread": "no core the platform runs opens it", +} + + +def category_evidence_text(evidence: dict) -> str: + """One line saying what establishes a missing entry's category.""" + if evidence.get("read_by"): + groups: dict[bool, list[str]] = {True: [], False: []} + for reader in evidence["read_by"]: + refs = [ + f"{e['name']} at {e['source_ref']}" if e.get("source_ref") else e["name"] + for e in reader.get("entries", []) + ] + groups[bool(reader.get("runs_system"))].append( + f"{reader['emulator']} ({', '.join(refs)})" if refs + else f"{reader['emulator']} (by {reader['proof']})" + ) + if not groups[True]: + return "read by " + ", ".join(groups[False]) + text = "read by " + ", ".join(groups[True]) + if groups[False]: + text += ", also named by " + ", ".join(groups[False]) + return text + examined = evidence.get("cores_examined") or [] + cores = f"cores examined: {', '.join(examined)}" if examined else "no core examined" + if evidence.get("unsettled"): + return f"no reader found, not settled: {evidence['unsettled']} ({cores})" + return f"no reader found ({cores})" + + +def _print_category_evidence(detail: dict) -> None: + evidence = detail.get("category_evidence") + if evidence: + print(f" {category_evidence_text(evidence)}") + + +def _print_detail_entries(details: list[dict], seen: set[str], verbose: bool) -> None: + """Print UNTESTED, MISSING, and DISCREPANCY entries from verification details.""" + _print_untested_details(details, seen, verbose) + _print_missing_details(details, seen, verbose) + _print_discrepancy_details(details, seen, verbose) + if verbose: + _print_ok_details(details, seen) + + +def _print_untested_details(details: list[dict], seen: set[str], verbose: bool) -> None: + for d in details: + if d["status"] != Status.UNTESTED: + continue + if d.get("discrepancy"): + # Reported below with the ground for it: a declaration + # unmet at a path another declaration holds. + continue + key = f"{d['system']}/{d['name']}" + if key in seen: + continue + seen.add(key) + req = "required" if d.get("required", True) else "optional" + hle = ", HLE available" if d.get("hle_fallback") else "" + reason = d.get("reason", "") + print(f" UNTESTED ({req}{hle}): {key}: {reason}") + _print_ground_truth(d.get("ground_truth", []), verbose) + + +def _print_missing_details(details: list[dict], seen: set[str], verbose: bool) -> None: + for d in details: + if d["status"] != Status.MISSING: + continue + key = f"{d['system']}/{d['name']}" + if key in seen: + continue + label = _NOT_FIRMWARE.get(d.get("category", BIOS)) + if label: + # Counted on their own line, named on request. + if verbose: + seen.add(key) + print(f" MISSING ({label}): {key}") + _print_category_evidence(d) + continue + seen.add(key) + req = "required" if d.get("required", True) else "optional" + hle = ", HLE available" if d.get("hle_fallback") else "" + print(f" MISSING ({req}{hle}): {key}") + if verbose: + _print_category_evidence(d) + _print_ground_truth(d.get("ground_truth", []), verbose) + + +def _print_discrepancy_details(details: list[dict], seen: set[str], verbose: bool) -> None: + for d in details: + disc = d.get("discrepancy") + if disc: + key = f"{d['system']}/{d['name']}" + if key in seen: + continue + seen.add(key) + print(f" DISCREPANCY: {key}: {disc}") + _print_ground_truth(d.get("ground_truth", []), verbose) + + +def _print_ok_details(details: list[dict], seen: set[str]) -> None: + for d in details: + if d["status"] != Status.OK: + continue + key = f"{d['system']}/{d['name']}" + if key in seen: + continue + seen.add(key) + gt = d.get("ground_truth", []) + if gt: + req = "required" if d.get("required", True) else "optional" + print(f" OK ({req}): {key}") + for line in _format_ground_truth_verbose(gt): + print(f" {line}") + + +def _print_undeclared_entry( + u: dict, prefix: str, verbose: bool, repeated: frozenset[str] = frozenset() +) -> None: + """Print a single undeclared file entry with its validation checks. + + A name in ``repeated`` is read at more than one path, and the line names + the path: two identical lines told no one there were two slots to fill. + """ + name = u["path"] if u["name"] in repeated and u.get("path") else u["name"] + arc_count = u.get("archive_file_count") + if arc_count: + name_label = f"{name} ({arc_count} file{'s' if arc_count != 1 else ''})" + else: + name_label = name + if u.get("alternatives") and not u.get("in_repo"): + name_label += f" (or {', '.join(u['alternatives'])})" + print(f" {prefix}: {u['emulator']} needs {name_label}") + checks = u.get("checks", []) + if checks: + if verbose: + expected = u.get("expected", {}) + if expected: + vals = ",".join(f"{k}={v}" for k, v in sorted(expected.items())) + ref_part = f" [{u['source_ref']}]" if u.get("source_ref") else "" + print(f" validates {vals}{ref_part}") + else: + checks_label = "+".join(checks) + ref_part = f" [{u['source_ref']}]" if u.get("source_ref") else "" + print(f" validates {checks_label}{ref_part}") + else: + # A bare "[size]" under the entry said nothing to a reader. + print(f" validates {'+'.join(checks)}") + + +def _split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], list[dict]]: + """Game data, firmware the pack places, firmware it holds but cannot place. + + Everything that is not game data is firmware the core loads, archives + included: a bios_zip sat in neither list, so a required one that was + missing was never printed. + """ + game_data = [u for u in undeclared if u.get("category", "bios") == "game_data"] + firmware = [u for u in undeclared if u.get("category", "bios") != "game_data"] + unplaced = [u for u in firmware if u["in_repo"] and not u.get("in_pack", True)] + placed = [u for u in firmware if u.get("in_pack", True)] + return game_data, placed, unplaced + + +def _core_required_missing(bios_files: list[dict]) -> list[dict]: + """Core files a core cannot run without, absent from the collection. + + A file bundled with the emulator (DaedalusX64's n64.psh, the shader + library its renderer installs beside the binary) arrives with it: the + collection does not hold it by design, and listing it as missing sent + readers after a file every install already has. + """ + return [ + u + for u in bios_files + if u["required"] and not u["in_repo"] and not u.get("hle_fallback") + and not u.get("bundled") + ] + + +def _repeated_names(entries: list[dict]) -> frozenset[str]: + """Names more than one of ``entries`` carries.""" + counts = Counter(u["name"] for u in entries) + return frozenset(name for name, count in counts.items() if count > 1) + + +def _omission_reasons(entries: list[dict]) -> str: + """Each reason a held file was left out, with its count when several. + + Printing the first entry's reason for the whole count named one cause + for 412 RomM files when 20 carried it. + """ + counts = Counter(u.get("omitted", "not placed") for u in entries) + if len(counts) == 1: + return next(iter(counts)) + ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0])) + return ", ".join(f"{count} {reason}" for reason, count in ranked) + + +def _print_undeclared_section(result: dict, verbose: bool) -> None: + """Print cross-reference section for undeclared files used by cores.""" + undeclared = result.get("undeclared_files", []) + # The pack's core copies can come from no gap entry: recalbox + # --system nec-pc-engine packs six root syscard copies for geargrafx + # with an empty gap report, and returning here hid them. + packed = result.get("packed_extras") + if not undeclared and not (packed and any(packed.values())): + return + + game_data, bios_files, unplaced = _split_undeclared(undeclared) + + # A file installed with its emulator is never collected, firmware or + # game data, required or not: cross_reference counts it apart. The + # firmware already left the pack lists (_mark_unplaced), the game data + # did not, and Abuse's three bundled data files read as missing. + bundled = [u for u in undeclared if not u["in_repo"] and u.get("bundled")] + game_data = [u for u in game_data if u["in_repo"] or not u.get("bundled")] + + req_not_in_repo = _core_required_missing(bios_files) + req_hle_not_in_repo = [ + u + for u in bios_files + if u["required"] and not u["in_repo"] and u.get("hle_fallback") + ] + req_in_repo = [u for u in bios_files if u["required"] and u["in_repo"]] + opt_in_repo = [u for u in bios_files if not u["required"] and u["in_repo"]] + opt_not_in_repo = [u for u in bios_files if not u["required"] and not u["in_repo"]] + # The builder's count, one file per pack path, when the platform pass + # replayed it. Counting entries said 1130 for RetroArch, 48 more than the + # pack holds: rom.key alone was claimed by three Amiga cores. + core_in_pack = ( + packed["bios"] if packed is not None else len(req_in_repo) + len(opt_in_repo) + ) + core_missing_req = len(req_not_in_repo) + len(req_hle_not_in_repo) + core_missing_opt = len(opt_not_in_repo) + + # Required gaps are always named below, the optional ones on request. + listed = "" if verbose or not core_missing_opt else " (--verbose lists them)" + print( + f" Core files: {core_in_pack} in pack, {core_missing_req} required missing, " + f"{core_missing_opt} optional missing{listed}" + ) + # The missing files follow the line that counts them: printed after the + # held-but-not-packed line, they read as files installed with their emulator. + repeated = _repeated_names(req_not_in_repo + req_hle_not_in_repo + opt_not_in_repo) + for u in req_not_in_repo: + _print_undeclared_entry(u, "MISSING (required)", verbose, repeated) + for u in req_hle_not_in_repo: + _print_undeclared_entry(u, "MISSING (required, HLE fallback)", verbose, repeated) + if verbose: + for u in opt_not_in_repo: + _print_undeclared_entry(u, "MISSING (optional)", verbose, repeated) + if bundled: + # The required firmware is named, as a missing one would be. The + # rest (shaders, runtime libraries, engine data) on request. + shown = bundled if verbose else [ + u for u in bundled + if u["required"] and u.get("category", "bios") != "game_data" + ] + named = sorted({u["name"] for u in shown}) + # The required firmware alone read as the whole count: 14 names + # for 154 entries, nothing saying the rest existed. + hidden = len({u["name"] for u in bundled}) - len(named) + more = f"{hidden} more, " if named else "" + items = named + ([f"{more}--verbose lists them"] if hidden else []) + print( + f" Bundled with their emulator, not collected: {len(bundled)}" + + (f" ({', '.join(items)})" if items else "") + ) + if unplaced: + print(f" Core files held but not packed: {len(unplaced)} " + f"({_omission_reasons(unplaced)})") + + if game_data or (packed and packed.get("game_data")): + gd_missing = [u for u in game_data if not u["in_repo"]] + gd_packed = ( + packed["game_data"] if packed is not None + else sum(1 for u in game_data if u["in_repo"] and u.get("in_pack", True)) + ) + gd_unplaced = [u for u in game_data if u["in_repo"] and not u.get("in_pack", True)] + if gd_missing or gd_packed or gd_unplaced: + listed = "" if verbose or not gd_missing else " (--verbose lists them)" + print(f" Game data: {gd_packed} in pack, {len(gd_missing)} missing{listed}") + if verbose: + repeated = _repeated_names(gd_missing) + for u in gd_missing: + _print_undeclared_entry(u, "MISSING (game data)", verbose, repeated) + if gd_unplaced: + print( + f" Game data held but not packed: {len(gd_unplaced)} " + f"({_omission_reasons(gd_unplaced)})" + ) + + +def _print_launcher_unproven(result: dict, verbose: bool) -> None: + """Launcher records resting on a config file the code does not prove.""" + rows = result.get("launcher_unproven") or [] + if not rows: + return + listed = "" if verbose else " (--verbose lists them)" + print(f" Launcher records unproven: {len(rows)}{listed}") + if not verbose: + return + for row in rows: + print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}") + for link in row["missing"]: + print(f" missing {link}") + + +def _print_launcher_reads(result: dict, verbose: bool) -> None: + """Names the platform's launch code reads that the collection lacks.""" + every = result.get("launcher_reads_not_held") or [] + rows = [r for r in every if not r.get("unsourceable")] + unsourceable = [r for r in every if r.get("unsourceable")] + listed = "" if verbose else " (--verbose lists them)" + if rows: + print(f" Launcher reads, not held: {len(rows)}{listed}") + if unsourceable: + print(f" Launcher reads, unsourceable: {len(unsourceable)}{listed}") + if not verbose: + return + for row in unsourceable: + print(f" {row['name']} [{', '.join(row['emulators'])}]: {row['unsourceable']}") + for row in rows: + kinds = ", ".join(sorted({r["kind"] for r in row["readers"]})) + casing = f", held as {row['held_as']}" if row.get("held_as") else "" + print(f" {row['name']} [{', '.join(row['emulators'])}, {kinds}{casing}]") + for reader in row["readers"]: + print(f" {reader['emulator']}: {reader['source_ref']}") + + +def _platform_summary_parts(result: dict) -> list[str]: + """The counts of a platform's first report line, in its mode's terms.""" + mode = result["verification_mode"] + total = result["total_files"] + c = result["severity_counts"] + ok_count = c[Severity.OK] + problems = total - ok_count + + if not reads_file_contents(mode): + parts = [f"{ok_count}/{total} present"] + if problems: + missing = c.get(Severity.WARNING, 0) + c.get(Severity.CRITICAL, 0) + optional_missing = c.get(Severity.INFO, 0) + if missing: + parts.append(f"{missing} missing") + if optional_missing: + parts.append(f"{optional_missing} optional missing") + return parts + sc = result.get("status_counts", {}) + untested = sc.get(Status.UNTESTED, 0) + missing = sc.get(Status.MISSING, 0) + parts = [f"{ok_count}/{total} OK"] + if untested: + parts.append(f"{untested} untested") + if missing: + parts.append(f"{missing} missing") + return parts + + +def _print_release_assets(details: list[dict]) -> None: + fetched = sorted({d["name"] for d in details if d.get("release_asset")}) + if fetched: + # Counted present: an online build downloads them. --offline counts + # them missing, as an offline build leaves them out. + shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") + print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}") + + +def _print_platform_notices(result: dict, verbose: bool) -> None: + """What the counts leave unsaid: uncached trees, cuts, region and category gaps.""" + uncached = result.get("data_dir_notices") or [] + if uncached and result.get("status_counts", {}).get(Status.MISSING): + shown = ", ".join(uncached[:10]) + (f" (+{len(uncached) - 10})" if len(uncached) > 10 else "") + print( + f" Data directories not cached ({len(uncached)}), their files count missing " + f"until refresh_data_dirs.py runs (an online pack build refreshes them): {shown}" + ) + for line in result.get("left_out") or []: + print(f" {line}") + fallbacks = result.get("region_fallbacks") or [] + if fallbacks: + from packs.readme import _group_label + + print(f" No BIOS for the requested regions, all kept ({len(fallbacks)}): " + + ", ".join(_group_label(g) for g in fallbacks)) + + not_firmware = result.get("missing_not_firmware") or {} + if not_firmware: + counts = ", ".join( + f"{len(dests)} {_NOT_FIRMWARE[category]}" + for category, dests in not_firmware.items() + ) + listed = "" if verbose else " (--verbose lists them)" + print(f" Missing, not firmware: {counts}{listed}") + + +def _print_platform_coverage(result: dict, verbose: bool) -> None: + # The same notes come back for every platform running these cores and + # filled 985 of the 1114 lines of verify --all: counted, listed on ask. + exclusions = result.get("exclusion_notes", []) + if exclusions and verbose: + print(f" No external files ({len(exclusions)}):") + for ex in exclusions: + print(f" {ex['emulator']}: {ex['detail']} [{ex['reason']}]") + elif exclusions: + print(f" No external files: {len(exclusions)} cores (--verbose lists them)") + + gt_cov = result.get("ground_truth_coverage") + if gt_cov and not gt_cov.get("applicable", True): + # MiSTer declares no core by design: its BiosDB is the answer, and + # the site shows "-" for it rather than a 0% gap. + print(" Ground truth: not applicable, the platform runs no profiled core") + elif gt_cov and gt_cov["total"] > 0: + # Rounded, as the site rounds: truncated, RetroArch read 20% here + # and 21% there for one measure. + pct = round(gt_cov["with_validation"] * 100 / gt_cov["total"]) + print( + f" Ground truth: {gt_cov['with_validation']}/{gt_cov['total']} files have emulator validation ({pct}%)" + ) + no_profile = gt_cov["total"] - gt_cov.get("with_profile", gt_cov["with_validation"]) + if no_profile: + print(f" {no_profile} platform-only (no emulator profile)") + + +def print_platform_result( + result: dict, group: list[str], verbose: bool = False +) -> None: + mode = result["verification_mode"] + label = " / ".join(group) + if result.get("systems"): + label += f" ({', '.join(result['systems'])})" + parts = _platform_summary_parts(result) + print(f"{label}: {', '.join(parts)} [{mode}]") + _print_release_assets(result["details"]) + _print_platform_notices(result, verbose) + + seen_details: set[str] = set() + _print_detail_entries(result["details"], seen_details, verbose) + _print_undeclared_section(result, verbose) + _print_launcher_reads(result, verbose) + _print_launcher_unproven(result, verbose) + _print_platform_coverage(result, verbose) + + +def _emulator_summary_parts(result: dict) -> list[str]: + total = result["total_files"] + ok_count = result["severity_counts"][Severity.OK] + sc = result.get("status_counts", {}) + untested = sc.get(Status.UNTESTED, 0) + missing = sc.get(Status.MISSING, 0) + # Counted by slot, as missing is: xash3d's thirteen unsourceable + # pak0.pak and liblist.gam were three names and ten "missing". + missing_slots: dict[str, bool] = {} + for d in result["details"]: + if d["status"] == Status.MISSING: + slot = d.get("destination") or d["name"] + missing_slots[slot] = missing_slots.get(slot, True) and "unsourceable" in d + unsourceable = sum(missing_slots.values()) + parts = [f"{ok_count}/{total} OK"] + if untested: + parts.append(f"{untested} untested") + if missing - unsourceable > 0: + parts.append(f"{missing - unsourceable} missing") + if unsourceable: + parts.append(f"{unsourceable} unsourceable") + return parts + + +def _print_emulator_ground_truth(gt: list[dict], verbose: bool) -> None: + if gt: + if verbose: + for line in _format_ground_truth_verbose(gt): + print(f" {line}") + else: + print(f" {_format_ground_truth_aggregate(gt)}") + + +def _print_emulator_problems(details: list[dict], seen: set[str], verbose: bool) -> None: + """The UNTESTED, MISSING and UNSOURCEABLE lines of an emulator report.""" + for d in details: + if d["status"] == Status.UNTESTED: + if d["name"] in seen: + continue + seen.add(d["name"]) + req = "required" if d.get("required", True) else "optional" + hle = ", HLE available" if d.get("hle_fallback") else "" + reason = d.get("reason", "") + print(f" UNTESTED ({req}{hle}): {d['name']}: {reason}") + _print_emulator_ground_truth(d.get("ground_truth", []), verbose) + for d in details: + if d["status"] == Status.MISSING and "unsourceable" not in d: + if d["name"] in seen: + continue + seen.add(d["name"]) + req = "required" if d.get("required", True) else "optional" + hle = ", HLE available" if d.get("hle_fallback") else "" + others = d.get("alternatives") + either = f" (or {', '.join(others)})" if others else "" + print(f" MISSING ({req}{hle}): {d['name']}{either}") + _print_emulator_ground_truth(d.get("ground_truth", []), verbose) + for d in details: + if d["status"] == Status.MISSING and "unsourceable" in d: + if d["name"] in seen: + continue + seen.add(d["name"]) + why = d.get("unsourceable") or "documented as unobtainable" + print(f" UNSOURCEABLE: {d['name']}: {why}") + + +def _print_emulator_ok(details: list[dict], seen: set[str]) -> None: + for d in details: + if d["status"] == Status.OK: + if d["name"] in seen: + continue + seen.add(d["name"]) + gt = d.get("ground_truth", []) + if gt: + req = "required" if d.get("required", True) else "optional" + print(f" OK ({req}): {d['name']}") + for line in _format_ground_truth_verbose(gt): + print(f" {line}") + + +def print_emulator_result(result: dict, verbose: bool = False) -> None: + """Print verification result for emulator/system mode.""" + label = " + ".join(result["emulators"]) + mode = result["verification_mode"] + parts = _emulator_summary_parts(result) + print(f"{label}: {', '.join(parts)} [{mode}]") + fetched = sorted({d["name"] for d in result["details"] if d.get("release_asset")}) + if fetched: + shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") + print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}") + + seen: set[str] = set() + _print_emulator_problems(result["details"], seen, verbose) + + for d in result["details"]: + if d.get("note"): + print(f" {d['note']}") + + if verbose: + _print_emulator_ok(result["details"], seen) + + for ref in result.get("data_dir_notices", []): + print( + f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)" + ) + + gt_cov = result.get("ground_truth_coverage") + if gt_cov and gt_cov["total"] > 0: + pct = round(gt_cov["with_validation"] * 100 / gt_cov["total"]) + print( + f" Ground truth: {gt_cov['with_validation']}/{gt_cov['total']} files have emulator validation ({pct}%)" + ) + if gt_cov["platform_only"]: + print(f" {gt_cov['platform_only']} without declared validation") diff --git a/scripts/packs/scope.py b/scripts/packs/scope.py new file mode 100644 index 000000000..c761661b2 --- /dev/null +++ b/scripts/packs/scope.py @@ -0,0 +1,109 @@ +"""The systems a pack covers, with the titles a person reads.""" + +from __future__ import annotations + +from collections.abc import Iterable + + +def platform_list_version(config: dict, platform: str) -> str: + """The version of the list a platform's YAML transcribes: the release + tag the scraper read, or for a list kept on a branch with no release, + the date of the commit it pinned. load_platform_config never passes a + parent's version to a child, Lakka is not RetroArch v1.22.2. + + The installer compares it with the version a machine runs, so a missing + value is refused rather than written as a stand-in. + """ + version = str(config.get("version") or "").strip() + if not version: + raise ValueError( + f"{platform}: the platform YAML records no version of its own" + ) + return version + + +def system_titles(*entry_lists: Iterable[dict]) -> dict[str, str]: + """The name a person reads for each system the entries carry. + + Batocera names PlayStation `psx` and the installer showed + `sony-playstation (psx)`: neither is what a beginner looks for. The + title is the one the site prints, so a system reads the same on its + page and in the installer. A system the site cannot name is left out, + and the installer shows its id: the site build refuses such a system, + so only a test fixture reaches here with one. + """ + from siterender import system_name + + ids = { + sys_id + for entries in entry_lists for entry in entries + for sys_id in entry.get("systems") or [] + } + titles: dict[str, str] = {} + for sys_id in sorted(ids): + try: + titles[sys_id] = system_name(sys_id) + except KeyError: + continue + return titles + + +def pack_systems(install_manifest: dict, targets: dict | None = None) -> dict: + """What a pack's manifest.json records of its systems, from the install + list built with the same choices: each file's systems, by its path in + the pack, and the names a person reads for them. + + A pack recorded none: the installer refused --system with a pack alone + ("the file list comes from an older release") and offered no Choose + systems, the route of a handheld without Wi-Fi. + + The install list itself and the platform's cores per board (targets, as + install/targets/ publishes them) ride along: with the pack alone, a + board was never applied and --target was refused, and a Batocera RPi4 + card took 8.9 GB where its board reads 5.8. + """ + files = install_manifest.get("files", []) + entries = [*files, *install_manifest.get("omitted_files", [])] + # What the install list narrows by, the installer's recorded_axes: with + # the pack alone it names that list as the way to --core and --region + # only when the list records them. It named install/misterfpga.json for + # --core, a list that records no core. + records = {"systems"} if any("systems" in entry for entry in entries) else set() + if any(copy.get("cores") for entry in files + for copy in [entry, *entry.get("alternatives", []), + *entry.get("slot_choices", [])]): + records.add("cores") + if records or any("regions" in entry for entry in entries): + records.add("regions") + systems = { + "files": {entry["dest"]: list(entry.get("systems") or []) + for entry in files if "systems" in entry}, + "system_titles": dict(install_manifest.get("system_titles") or {}), + "system_names": dict(install_manifest.get("system_names") or {}), + "list_records": sorted(records), + } + # The version of the platform's list, which the installer compares with + # the one the machine runs when it has the pack alone. + if install_manifest.get("version"): + systems["list_version"] = install_manifest["version"] + systems["install_list"] = install_manifest + if targets is not None: + systems["targets"] = targets + return systems + + +def annotate_pack_systems(manifest: dict, systems: dict | None) -> None: + """Write pack_systems into a pack's manifest: a systems list on each + file the install list names, the titles and names beside.""" + if not systems: + return + for entry in manifest.get("files", []): + held = systems["files"].get(entry["path"]) + if held is not None: + entry["systems"] = held + for key in ("system_titles", "system_names"): + if systems.get(key): + manifest[key] = systems[key] + for key in ("list_records", "list_version", "install_list", "targets"): + if key in systems: + manifest[key] = systems[key] diff --git a/scripts/packs/slots.py b/scripts/packs/slots.py new file mode 100644 index 000000000..38a4eae06 --- /dev/null +++ b/scripts/packs/slots.py @@ -0,0 +1,643 @@ +"""Who decides what goes at a destination: the platform's claim against the emulator profile's.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +from core.hashing import parse_md5_list +from model.profiles import entry_system_ids +from resolve import nativemode +from resolve.archives import archive_entry, holds_required_members +from resolve.collisions import _accepted_by_all, _content_sha1, _lists_hashes, _normalize +from resolve.cores import resolve_platform_cores +from resolve.layout import system_dir_path +from resolve.localfile import resolution_is_hash_exact, resolve_local_file +from resolve.packfiles import preferred_entries +from resolve.standalone import platform_layouts, standalone_set as platform_standalone_set +from resolve.validation import ( + content_alternatives, + outside_gap_scope, + read_from_save_dir, + with_archive_members, +) + +if TYPE_CHECKING: + from packs.extras import ExtraPlacement + + +# A profile entry can prove a slot without declaring a hash: Dolphin names no +# checksum for the GameCube boot ROM because its source names none, and the +# proof is then the path the repository stores the file at. +# A profile entry that names an exact size, for a file the code reads in +# full (no hash to declare), is proven by a held copy of that size: the +# platform's xmil/IPLROM.X1T pinned the 2 KiB X1 font where xmil reads a +# 32 KiB Turbo IPL, and a name-only claim could not contest it. +SIZE_EXACT = "size_exact" +PROVEN_STATUSES = frozenset({"path_exact", "members_held", SIZE_EXACT}) + + +def _size_the_code_reads(entry: dict, local: str | None) -> bool: + """Whether a name-resolved copy has the exact size the entry declares.""" + size = entry.get("size") + if not local or not isinstance(size, int) or size <= 0: + return False + try: + return os.path.getsize(local) == size + except OSError: + return False + + +# A core that reads ROMs inside an archive proves the archive by its members: +# FBNeo's neocdz.zip is any copy holding neocd.bin and 000-lo.lo by crc. +MEMBERS_HELD = "members_held" + + +@dataclass +class Claim: + """One layer's answer to what belongs at a destination.""" + + origin: str + destination: str + name: str + emulator: str = "" + entry: dict = field(default_factory=dict) + local_path: str | None = None + status: str = "" + # A core that identifies its firmware by content reads no file by this + # name: any dump it takes for the same system and region answers for it. + accepts: tuple[dict, ...] = () + + @property + def is_proven(self) -> bool: + """Whether the claim rests on evidence rather than on a bare name.""" + return resolution_is_hash_exact(self.status) or self.status in PROVEN_STATUSES + + +@dataclass +class Conflict: + """Two proven claims on one destination that resolve to different files.""" + + destination: str + platform_claim: Claim + profile_claims: list[Claim] + + @property + def emulators(self) -> list[str]: + return sorted({c.emulator for c in self.profile_claims if c.emulator}) + + def files_read(self) -> list[tuple[str | None, list[str], str]]: + """Each file the profiles want here, with the emulators reading it + and the proof of the first claim on it. + + One file stood for every claim: Recalbox's neocdz.zip line gave + geolith the archive fbneo reads, not the one geolith pins. + """ + files: dict[str | None, tuple[list[str], str]] = {} + for claim in self.profile_claims: + emulators, status = files.setdefault(claim.local_path, ([], claim.status)) + if claim.emulator and claim.emulator not in emulators: + emulators.append(claim.emulator) + return [(path, sorted(emus), status) for path, (emus, status) in files.items()] + + +def platform_claims( + config: dict, + db: dict, + base_dest: str = "", + zip_contents: dict | None = None, + data_dir_registry: dict | None = None, +) -> list[Claim]: + """What the platform YAML says belongs at each of its destinations.""" + claims: list[Claim] = [] + for system in (config.get("systems") or {}).values(): + for entry in system.get("files") or []: + if not isinstance(entry, dict): + continue + dest = entry.get("destination") or entry.get("name") or "" + if not dest: + continue + full = f"{base_dest}/{dest}" if base_dest else dest + local, status = resolve_local_file( + entry, + db, + zip_contents, + dest_hint=dest, + data_dir_registry=data_dir_registry, + ) + claims.append( + Claim( + origin="platform", + destination=full, + name=entry.get("name", ""), + entry=entry, + local_path=local, + status=status, + ) + ) + return claims + + +def profile_claims( + profiles: dict, + db: dict, + base_dest: str = "", + standalone_cores: set[str] | None = None, + zip_contents: dict | None = None, + data_dir_registry: dict | None = None, + config: dict | None = None, +) -> list[Claim]: + """What each emulator profile says belongs at each destination it names. + + With the platform's config, a claim sits where the pack puts the core's + file (ExtraPlacement): under RetroDECK's bios/, under RomM's system + folder. A file the platform cannot place claims nothing. + + A file can exist in one build of an emulator and not the other, and the + two builds read from different directories. The mode is decided per + emulator, not per pack: a platform runs some of its emulators as libretro + cores and others standalone, naming the latter in ``standalone_cores``. + An entry the standalone build alone loads does not address a platform + running that emulator as a core, and where it does, the destination is + ``standalone_path``. This is the gate verify already applies. + """ + standalone_cores = standalone_cores or set() + placement = None + if config is not None: + from packs.extras import ExtraPlacement + + placement = ExtraPlacement(config, base_dest, profiles) + claims: list[Claim] = [] + for emu_name, profile in sorted(profiles.items()): + if profile.get("type") in ("launcher", "alias"): + continue + # The gap report skips a filename-agnostic profile whole: the builder + # carries its scan candidates, never its named entries. + if profile.get("bios_mode") == "agnostic": + continue + for layout, is_standalone in platform_layouts(emu_name, profile, standalone_cores): + claims.extend( + _archive_claims( + emu_name, layout, is_standalone, db, base_dest, placement, + zip_contents, data_dir_registry, + ) + ) + for entry in layout.get("files") or []: + if not isinstance(entry, dict): + continue + # The same rule as the gap report and the builder: an entry the + # pack never carries (a placeholder, a filename-agnostic scan) + # arbitrates nothing. One read below the save directory sits + # outside the BIOS tree, where no platform declares a file. + if outside_gap_scope(entry, is_standalone) or read_from_save_dir( + entry, is_standalone + ) or entry.get("unplaced"): + continue + # A member of a romset is not a file at the BIOS root: the archive + # holding it occupies the destination (_archive_claims). Claiming + # the member put FBNeo's msx.zip contents loose at the root. + if entry.get("archive"): + continue + dest = ( + (entry.get("standalone_path") or entry.get("path")) + if is_standalone + else system_dir_path(entry, entry.get("path") or entry.get("name") or "") + ) or entry.get("name") or "" + if not dest: + continue + if placement is None: + full = f"{base_dest}/{dest}" if base_dest else dest + else: + placed = placement.place( + { + "profile": emu_name, + "system": entry.get("system"), + "systems": entry_system_ids(entry, layout), + }, + dest, + ) + if placed is None: + continue + full = placed[1] + # The owner's own copy is the one the builder ships. + local, status = resolve_local_file( + { + **with_archive_members(entry, layout.get("files") or []), + "source_profile": emu_name, + }, + db, + zip_contents, + dest_hint=dest, + data_dir_registry=data_dir_registry, + ) + if status == "name_exact" and _size_the_code_reads(entry, local): + status = SIZE_EXACT + accepts = tuple(content_alternatives(entry, layout)) + claims.append( + Claim( + origin="profile", + destination=full, + name=entry.get("name", ""), + emulator=emu_name, + entry=entry, + local_path=local, + status=status, + accepts=accepts, + ) + ) + return claims + + +def _archive_claims( + emu_name: str, + profile: dict, + is_standalone: bool, + db: dict, + base_dest: str, + placement: ExtraPlacement | None, + zip_contents: dict | None, + data_dir_registry: dict | None, +) -> list[Claim]: + """The archives a core reads its ROMs from, where the builder places them. + + The archive sits at the root and, for a core that reads a directory of + its own (archive_prefix), under it as well. The claim is proven when the + copy holds every member the core requires. + """ + files = [ + entry for entry in profile.get("files") or [] + if isinstance(entry, dict) + and not outside_gap_scope(entry, is_standalone) + and not read_from_save_dir(entry, is_standalone) + and not entry.get("unplaced") + ] + prefix = profile.get("archive_prefix", "") + claims: list[Claim] = [] + for archive in sorted({entry["archive"] for entry in files if entry.get("archive")}): + entry = archive_entry(archive, files) + members = entry.get("members") + if not members: + continue + member = next(f for f in files if f.get("archive") == archive) + system = member.get("system") + if member.get("system_dir"): + entry = {**entry, "system_dir": member["system_dir"]} + root = system_dir_path(entry, archive) + for dest in (root, f"{prefix}/{archive}") if prefix else (root,): + if placement is None: + full = f"{base_dest}/{dest}" if base_dest else dest + else: + placed = placement.place({"profile": emu_name, "system": system}, dest) + if placed is None: + continue + full = placed[1] + local, status = resolve_local_file( + {**entry, "source_profile": emu_name}, + db, + zip_contents, + dest_hint=dest, + data_dir_registry=data_dir_registry, + ) + if ( + local + and not resolution_is_hash_exact(status) + and holds_required_members(local, members) + ): + status = MEMBERS_HELD + claims.append( + Claim( + origin="profile", + destination=full, + name=archive, + emulator=emu_name, + entry=entry, + local_path=local, + status=status, + ) + ) + return claims + + +def checked_by_path(mode: str, entry: dict, rule: str = "") -> bool: + """Whether the frontend checks this declaration by its path alone. + + Whether a frontend reads the bytes is a property of the platform, but + what it compares them with is the entry's: Batocera skips an empty md5 + (batocera-systems:1088), and EmuDeck declares neocdz.zip with no hash at + all. Such an entry is a path, in an md5 platform as in an existence one. + A member pinned inside an archive is content. + """ + if not nativemode.reads_file_contents(mode): + return True + if entry.get("zipped_file"): + return False + if rule == nativemode.SIZE_AND_ANY_HASH: + fields: tuple[str, ...] = ("md5", "sha1", "crc32") + else: + fields = (nativemode.digest_algorithm(mode) or "",) + return not any( + parse_md5_list(entry.get(name)) if name == "md5" else entry.get(name) + for name in fields + ) + + +def _claim_rank(claim: Claim) -> int: + """How strongly a platform claim speaks for what the pack ships.""" + if resolution_is_hash_exact(claim.status): + return 2 + return 1 if claim.is_proven else 0 + + +def _slot_claims( + config: dict, + profiles: dict, + db: dict, + base_dest: str, + standalone_cores: set[str] | None, + zip_contents: dict | None, + data_dir_registry: dict | None, +) -> tuple[dict[str, Claim], dict[str, list[Claim]]]: + """The platform claim and the proven profile claims at each destination.""" + fold = bool(config.get("case_insensitive_fs", False)) + # The builder's own choice among declarations sharing a destination, + # read from the same function: the most accepting archive for zipped_file + # members, then md5_exact. A rule of its own here compared profiles with + # a file the pack does not ship (Batocera adam_fdc.zip). + shipped = set( + preferred_entries( + config.get("systems") or {}, db, "bios", base_dest, False, + zip_contents, True, + ).values() + ) + by_dest: dict[str, Claim] = {} + for claim in platform_claims( + config, db, base_dest, zip_contents, data_dir_registry + ): + key = _normalize(claim.destination, fold) + held = by_dest.get(key) + if held is not None and id(held.entry) in shipped: + continue + # A bare sibling met first must not stand for the destination: it + # would hide the contradiction with the file actually shipped. + if ( + held is None + or id(claim.entry) in shipped + or _claim_rank(claim) > _claim_rank(held) + ): + by_dest[key] = claim + + # Grouped before judging: a profile may declare several revisions that are + # all acceptable at one destination, and the platform choosing one of them + # is agreement, not contradiction. Only a destination where no profile + # claim at all matches what ships is a disagreement. + # A platform claim resting on a bare name, or on a pin no local file + # matches, asserts nothing about content. Where the frontend never reads + # the bytes, a proven profile claim then decides: RetroArch's neocdz.zip + # pins an md5 nobody holds, and the primary shipped without the 000-lo.lo + # geolith and FBNeo read inside it. Decided per entry: EmuDeck, an md5 + # platform, declares the same archive with no hash. + mode = config.get("verification_mode", "existence") + rule = config.get("hash_rule", "") + by_slot: dict[str, list[Claim]] = {} + for claim in profile_claims( + profiles, db, base_dest, standalone_cores, zip_contents, data_dir_registry, + config=config, + ): + key = _normalize(claim.destination, fold) + platform = by_dest.get(key) + if platform is None or not claim.is_proven: + continue + if claim.status == SIZE_EXACT and ( + not platform.local_path + or _size_the_code_reads(claim.entry, platform.local_path) + ): + # A size proves a claim only against a file of another size. + continue + if not platform.is_proven and not ( + platform.local_path and checked_by_path(mode, platform.entry, rule) + ): + continue + by_slot.setdefault(key, []).append(claim) + + return by_dest, by_slot + + +def find_conflicts( + config: dict, + profiles: dict, + db: dict, + base_dest: str = "", + standalone_cores: set[str] | None = None, + zip_contents: dict | None = None, + data_dir_registry: dict | None = None, +) -> list[Conflict]: + """Destinations where a proven profile claim contradicts what ships. + + Only proven claims are compared. A claim resolved by filename alone + asserts nothing about content and cannot contradict anything. + """ + by_dest, by_slot = _slot_claims( + config, profiles, db, base_dest, standalone_cores, zip_contents, + data_dir_registry, + ) + # A declaration that lists several accepted hashes is satisfied by any of + # them: Recalbox names both scph1001.bin revisions, and mesence names + # four BS-X dumps among which System.dat pins one. The resolver stops on + # the first it finds, so the paths differ while both layers agree. + disputed = { + key: claims + for key, claims in by_slot.items() + if not any(_satisfies(c, by_dest[key], db) for c in claims) + } + + return [ + Conflict( + destination=by_dest[key].destination, + platform_claim=by_dest[key], + profile_claims=claims, + ) + for key, claims in sorted(disputed.items()) + ] + + +# Why a decision went the way it did. Not the mode's own name: the mode is +# spelt in one place only, and nativemode answers whether it reads content. +SERVES_BOTH = "path_only_check" +ADDRESSEE = "addressee" +FRONTEND_CHECKS_CONTENT = "frontend_checks_content" + + +@dataclass +class Decision: + """Which claim a pack should honour at a contested destination, and why.""" + + conflict: Conflict + winner: Claim + reason: str + + @property + def serves_both(self) -> bool: + """Whether honouring the winner still satisfies the other layer.""" + return self.reason == SERVES_BOTH + + +def pack_overrides( + config: dict, + profiles: dict, + db: dict, + zip_contents: dict | None = None, + data_dir_registry: dict | None = None, + target_cores: set[str] | None = None, + source: str = "full", + choices: dict[str, list[tuple[str, str | None]]] | None = None, +) -> dict[str, str]: + """Full pack destination -> the file a platform pack serves there instead. + + Where a source-verified profile contradicts the scraped baseline on one + destination, the pack answers to the platform it is built for. In + existence mode the frontend never reads the bytes, so serving the + emulator's file satisfies both. The ZIP builder, the install manifest and + verify all read this: two of them deciding alone gave the one-line + installer different bytes than the ZIP. ``choices`` is slot_choices + for the same arguments when the caller already holds it. + """ + # A baseline-only pack serves what the platform declares, and a target's + # pack answers to the cores that hardware builds: DuckStation does not + # exist on any RetroArch target and still replaced its scph5000.bin. + if not profiles or source == "platform": + return {} + cores = set(resolve_platform_cores(config, profiles, target_cores=target_cores)) + overrides: dict[str, str] = {} + if choices is None: + choices = slot_choices(config, profiles, db, zip_contents, data_dir_registry) + for destination, ordered in choices.items(): + path = next((path for emulator, path in ordered if emulator in cores), None) + if path: + overrides[destination] = path + return overrides + + +def slot_choices( + config: dict, + profiles: dict, + db: dict, + zip_contents: dict | None = None, + data_dir_registry: dict | None = None, +) -> dict[str, list[tuple[str, str | None]]]: + """Destination -> (core, the file it has served there) in decision order. + + A pack built for a set of cores serves the first choice whose core is in + it, None standing for the platform's own answer. No core in it leaves + the platform's answer too. The order is arbitrate's: a core agreeing with + the platform settles the slot whatever else is present, then the + strongest proof decides. Read for one core set by pack_overrides and + recorded whole in the install manifest, so a target narrowed from the + full manifest gets the bytes the target's own pack carries. + """ + mode = config.get("verification_mode", "existence") + rule = config.get("hash_rule", "") + platform_profiles = { + name: profiles[name] for name in resolve_platform_cores(config, profiles) + } + by_dest, by_slot = _slot_claims( + config, + platform_profiles, + db, + config.get("base_destination", ""), + platform_standalone_set(config), + zip_contents, + data_dir_registry, + ) + choices: dict[str, list[tuple[str, str | None]]] = {} + for key, claims in sorted(by_slot.items()): + platform = by_dest[key] + # Where the frontend compares a hash, the platform's file stays. + if not checked_by_path(mode, platform.entry, rule): + continue + agree = [_satisfies(c, platform, db) for c in claims] + agreeing = [c for c, ok in zip(claims, agree) if ok] + others = sorted( + (c for c, ok in zip(claims, agree) if not ok), + key=lambda claim: (-_claim_rank(claim), claims.index(claim)), + ) + if not others: + continue + choices[platform.destination] = [ + *((c.emulator, None) for c in agreeing), + *((c.emulator, c.local_path) for c in others), + ] + return choices + + +def _strongest(claims: list[Claim]) -> Claim: + """The profile claim with the strongest proof, the first emulator breaking ties. + + yaps2 pins its GameIndex.yaml by sha1 while armsx2 and lrps2 only match a + path: alphabetical order served armsx2's copy to all three. + """ + return max(claims, key=lambda claim: (_claim_rank(claim), -claims.index(claim))) + + +def arbitrate( + conflict: Conflict, mode: str, addressee: str = "platform", rule: str = "", +) -> Decision: + """Decide a contested destination for the pack being built. + + A pack answers to whoever asked for it. A platform pack must leave the + frontend's own check green, because a user reading red concludes the pack + is broken. A pack built for one emulator answers to that emulator. The + other layer is served as well whenever the destination allows it. + + In ``existence`` mode the frontend only looks for a path, so the emulator's + file satisfies both sides at once and there is nothing to trade away. In a + content-checking mode the two answers cannot share one path, and the pack's + addressee decides. The loss is reported rather than absorbed: only the + platform's own list can change what its frontend accepts there. + """ + profile = _strongest(conflict.profile_claims) + if addressee == "emulator": + return Decision(conflict, profile, ADDRESSEE) + if checked_by_path(mode, conflict.platform_claim.entry, rule): + return Decision(conflict, profile, SERVES_BOTH) + return Decision(conflict, conflict.platform_claim, FRONTEND_CHECKS_CONTENT) + + +def _satisfies(profile: Claim, platform: Claim, db: dict) -> bool: + """Whether the two layers agree on what ships at this destination. + + They agree when they resolve to the same bytes, when the platform's own + hash list accepts the profile's file, or when the profile's accepts the + platform's. A contradiction needs both lists to reject the other side. + A core found by content (found_by: content) reads no file by the + destination's name, so any dump it takes for the same system and region + settles the slot: DuckStation takes Batocera's scph1001.bin v2.0, which its profile + labels scph1001_v20.bin. + """ + if profile.local_path == platform.local_path: + return True + # Two paths can hold one content: AmberELEC's bluemsx declarations + # resolve into the data/bluemsx cache, the profile's into bios/. + if profile.local_path and platform.local_path: + shipped = _content_sha1(platform.local_path, db) + if shipped is not None and shipped == _content_sha1(profile.local_path, db): + return True + members = profile.entry.get("members") + if members and platform.local_path: + return holds_required_members(platform.local_path, members) + if ( + profile.local_path + and _lists_hashes(platform.entry) + and _accepted_by_all(profile.local_path, [platform.entry], db) + ): + return True + if platform.local_path and any( + _lists_hashes(label) and _accepted_by_all(platform.local_path, [label], db) + for label in profile.accepts + ): + return True + return bool( + platform.local_path + and _lists_hashes(profile.entry) + and _accepted_by_all(platform.local_path, [profile.entry], db) + ) diff --git a/scripts/packs/standalone.py b/scripts/packs/standalone.py new file mode 100644 index 000000000..295b0fcb9 --- /dev/null +++ b/scripts/packs/standalone.py @@ -0,0 +1,242 @@ +"""Files a standalone emulator reads where the platform places them.""" + +from __future__ import annotations + +import contextlib +import io +import re +from pathlib import PurePosixPath + +from core.paths import REPO_ROOT +from packs.archive import PackRecord +from packs.emulatorpack import generate_emulator_pack +from packs.manifestentry import _manifest_entry + + +def _placed_copies(copies: list[dict], dests: list[str]) -> list[dict]: + """Each standalone copy with the path this manifest gives its file. + + The registry names one path per file for every platform (one anchor), + while each manifest places the file its own way: EmuDeck installs + aes_keys.txt at the root and Batocera prod.keys under switch/, so the + installer looked for Citra/sysdata/aes_keys.txt, found nothing and + copied nothing. `file` stays as written, since it also lays out a custom + emulator root. `source` says where the installed file is. + """ + by_name: dict[str, list[str]] = {} + for dest in dests: + by_name.setdefault(dest.rsplit("/", 1)[-1].casefold(), []).append(dest) + placed: list[dict] = [] + for copy in copies: + wanted = copy.get("file") + if not wanted or wanted in dests: + placed.append(copy) + continue + tail = [d for d in dests if d.endswith("/" + wanted)] + if tail: + # The file whose path carries the least on top of the tail. + shortest = min(len(d) for d in tail) + tail = [d for d in tail if len(d) == shortest] + else: + tail = by_name.get(wanted.rsplit("/", 1)[-1].casefold(), []) + placed.append({**copy, "source": tail[0]} if len(tail) == 1 else copy) + return placed + + +# data_root keys of the profiles, as the copy targets name each system. +_DATA_ROOT_SYSTEMS = {"linux": "linux", "macos": "darwin", "windows": "windows", + "android": "android"} + + +def _data_root_target(system: str, text: str) -> str | None: + """A profile's data_root on one system as a copy target, or None when it + names no place a run can find: a folder beside an executable, a working + directory, a folder picked in the app. Of `A, else B` the alternative + under the home is kept, the default the registry's targets write. + """ + for choice in (part.strip() for part in text.split(", else ")): + if "<" in choice: + continue + if system == "windows" and re.match(r"^%[A-Za-z0-9_()]+%/", choice): + return choice.replace("/", "\\") + if system == "android" and choice.startswith("Android/data/"): + return "$EXTERNAL_STORAGE/" + choice + if system in ("linux", "darwin"): + if choice.startswith("~/"): + return "$HOME/" + choice[2:] + if choice.startswith("$HOME/"): + return choice + return None + + +def _one_content(held: list[str], entries: dict[str, dict], emulator: str) -> list[str]: + """The one dest a copy reads when every held dest carries the same bytes. + + Unchanged when the contents differ: the name then designates nothing. + """ + if len({entries[dest].get("sha1") for dest in held}) != 1: + return held + own = [dest for dest in held if emulator in (entries[dest].get("cores") or ())] + return [min(own or held, key=lambda dest: (dest.count("/"), len(dest), dest))] + + +def _profile_roots(profile: dict) -> dict[str, str]: + """The data_root of each system the profile names a findable place for.""" + return { + _DATA_ROOT_SYSTEMS[key]: target + for key, value in (profile.get("data_root") or {}).items() + if key in _DATA_ROOT_SYSTEMS and isinstance(value, dict) + and (target := _data_root_target(_DATA_ROOT_SYSTEMS[key], value.get("path", ""))) + } + + +def _copy_source( + entry: dict, + by_tail: dict[str, list[str]], + entries: dict[str, dict] | None, + profile_name: str, +) -> str | None: + """The manifest dest a profile entry's standalone copy is taken from.""" + standalone = entry.get("standalone_path") + if (not standalone or standalone.endswith("/") or entry.get("mode") == "libretro" + or entry.get("type") == "directory" or entry.get("found_by") == "content"): + return None + held = by_tail.get(entry.get("path") or entry["name"], []) + if len(held) > 1 and entries is not None: + held = _one_content(held, entries, profile_name) + if len(held) != 1: + return None + return held[0] + + +def _profile_copies( + profiles: dict[str, dict], dests: list[str], declared: list[dict], + entries: dict[str, dict] | None = None, +) -> list[dict]: + """The standalone copies the emulator profiles document: each file with + a standalone_path, into the data_root of each system that names a place. + + The registry's list was kept by hand for eight emulators, while the + profiles give the folder of 61 with the code that builds it: a machine + with standalone Cemu only got none of its keys. A target the registry + already gives for the same name is left to it, and a file the manifest + does not carry, or carries under the save directory, has no source. A + file found by content (found_by) sits wherever the folder the user set + for the scan points: Amiberry reads its ROMs from rom_path, which + amiberry.conf moves, so its name under data_root proves nothing. + ``entries`` maps each dest to its manifest entry: one file carried at + two paths with the same bytes is one source, the copy whose cores name + the emulator, else the shortest path. DuckStation's ps2_scph50006.bin + sits at the BIOS root and under pcsx2/bios/ for the libretro PS2 cores. + """ + from fnmatch import fnmatch + + taken: list[tuple[str, str, str, bool]] = [] + for copy in declared: + name = copy.get("pattern") or PurePosixPath(copy.get("file", "")).name + for system, targets in (copy.get("targets") or {}).items(): + taken += [(system, target, name, "pattern" in copy) for target in targets] + + def covered(system: str, target: str, name: str) -> bool: + return any( + system == t_system and target == t_target + and (fnmatch(name, t_name) if is_pattern else name == t_name) + for t_system, t_target, t_name, is_pattern in taken + ) + + by_tail: dict[str, list[str]] = {} + for dest in dests: + parts = dest.split("/") + for start in range(len(parts)): + by_tail.setdefault("/".join(parts[start:]), []).append(dest) + copies: list[dict] = [] + for profile_name in sorted(profiles): + profile = profiles[profile_name] + roots = _profile_roots(profile) + if not roots: + continue + for entry in profile.get("files", []): + source = _copy_source(entry, by_tail, entries, profile_name) + if source is None: + continue + where = PurePosixPath(entry["standalone_path"]) + placed: dict[str, list[str]] = {} + for system, root in roots.items(): + sep = "\\" if system == "windows" else "/" + target = root if str(where.parent) == "." else ( + root + sep + str(where.parent).replace("/", sep)) + if not covered(system, target, where.name): + placed[system] = [target] + if not placed: + continue + copy = {"file": source, "targets": placed} + if where.name != PurePosixPath(source).name: + copy["as"] = where.name + copies.append(copy) + return copies + + +def _standalone_copies( + declared: list[dict], profiles: dict[str, dict], manifest_files: list[dict], +) -> list[dict]: + """A manifest's standalone copies: the registry's, placed where this + manifest puts each file, then the ones the profiles document. A platform + whose registry entry declares none gets none.""" + if not declared: + return [] + kept = [entry for entry in manifest_files if entry.get("root") != "save"] + dests = [entry["dest"] for entry in kept] + entries = {entry["dest"]: entry for entry in kept} + return _placed_copies(declared, dests) + _profile_copies(profiles, dests, declared, entries) + + +STANDALONE_DIR = "standalone" + + +def _standalone_layouts( + profiles: dict[str, dict], + emulators_dir: str, + db: dict, + bios_dir: str, + zip_contents: dict, + offline: bool | None, + platforms_dir: str, + result: dict, +) -> dict[str, list]: + """Per emulator with a standalone build, the files `--emulator X + --standalone` packs, at the destinations that build reads. + + Built by the emulator pack itself, in memory. A file whose content the + list already carries is written as [dest, sha1], its download read from + that entry. Another is written whole. A data tree member is left to the + list's data directories. + """ + repo_root = str(REPO_ROOT) + known = { + copy["sha1"] + for entry in [*result["files"], *result.get("truth_files", [])] + for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])] + if copy.get("sha1") and (copy.get("repo_path") or copy.get("release_asset")) + } + layouts: dict[str, list] = {} + for name, profile in sorted(profiles.items()): + if "standalone" not in str(profile.get("type", "")): + continue + record = PackRecord() + with contextlib.redirect_stdout(io.StringIO()), \ + contextlib.redirect_stderr(io.StringIO()): + generate_emulator_pack( + [name], emulators_dir, db, bios_dir, "", standalone=True, + zip_contents=zip_contents, offline=offline, + platforms_dir=platforms_dir, record=record, + ) + items: list = [] + for member in record.files: + entry, _size = _manifest_entry( + record.sources.get(member), member, [name], db, repo_root, {} + ) + if entry is None: + continue + items.append([member, entry["sha1"]] if entry["sha1"] in known else entry) + layouts[name] = items + return layouts diff --git a/scripts/packs/targets.py b/scripts/packs/targets.py new file mode 100644 index 000000000..4742c895c --- /dev/null +++ b/scripts/packs/targets.py @@ -0,0 +1,108 @@ +"""The per-target core lists the installer reads.""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path + +from core.artifacts import write_text_atomic +from model.safeparse import yaml_load +from model.targets import load_target_config + + +def generate_target_manifests(targets_dir: str, output_dir: str) -> None: + """Convert target YAMLs to installer JSON manifests.""" + os.makedirs(output_dir, exist_ok=True) + targets_path = Path(targets_dir) + if not targets_path.is_dir(): + print(f"No targets directory at {targets_dir}", file=sys.stderr) + return + count = 0 + for yml_file in sorted(targets_path.glob("*.yml")): + if yml_file.name.startswith("_"): + continue + result = target_list(yml_file) + out_path = Path(output_dir) / f"{yml_file.stem}.json" + write_text_atomic(out_path, json.dumps(result, indent=2, sort_keys=True) + "\n") + count += 1 + print(f" {yml_file.stem}: {len(result)} targets") + print(f"Generated {count} target manifest(s) in {output_dir}") + + +def target_list(yml_file: Path) -> dict[str, list[str] | dict | None]: + """A platform's cores per hardware target, as install/targets/ publishes + them and a pack carries them: aliases included, overrides applied.""" + targets_path = yml_file.parent + with open(yml_file) as f: + data = yaml_load(f) or {} + targets = data.get("targets", {}) + if not isinstance(targets, dict): + raise ValueError(f"{yml_file}: targets must be a mapping") + + # The pack builder accepts the aliases declared in _overrides.yml, so + # --target switch works there. Emitting only canonical names left the + # installer rejecting the same word and, worse, carrying on with every + # file instead: the user asked for a filter and got the full pack. + overrides_path = targets_path / "_overrides.yml" + alias_map: dict[str, list[str]] = {} + platform_overrides: dict = {} + if overrides_path.is_file(): + with open(overrides_path) as f: + all_overrides = yaml_load(f) or {} + platform_overrides = ( + all_overrides.get(yml_file.stem, {}).get("targets", {}) or {} + ) + for tname, ovr in platform_overrides.items(): + names = [a for a in (ovr or {}).get("aliases", []) if isinstance(a, str)] + if names: + alias_map[tname] = names + + result: dict[str, list[str] | dict | None] = {} + for target_name, target_info in targets.items(): + if not isinstance(target_name, str) or not target_name: + raise ValueError(f"{yml_file}: target names must be non-empty strings") + if not isinstance(target_info, dict): + raise ValueError(f"{yml_file}: target {target_name!r} must be a mapping") + cores = target_info.get("cores") + if cores is None: + result[target_name] = None + continue + if ( + not isinstance(cores, list) + or any(not isinstance(core, str) or not core for core in cores) + or len(cores) != len(set(cores)) + ): + raise ValueError( + f"{yml_file}: target {target_name!r} cores must be unique " + "non-empty strings" + ) + # The builder's own reading, overrides included: a list published + # another way makes the installer serve what the pack does not. + # An empty list is a board with no core, not one with every core. + resolved = load_target_config( + yml_file.stem, target_name, str(targets_path.parent) + ) + listed = None if resolved is None else sorted(resolved) + images = target_info.get("images") + # The image names a card's board file holds (Batocera writes + # anbernic-rg35xx-plus for the h700 target): the installer reads + # the board of a card prepared on a computer through them. + result[target_name] = ( + {"cores": listed, "images": images} + if images and listed is not None else listed + ) + + for target_name, names in alias_map.items(): + if target_name not in result: + continue + for alias in names: + if alias in result: + raise ValueError( + f"{yml_file}: alias {alias!r} collides with a target name" + ) + # An alias names the board, not its images. + held = result[target_name] + result[alias] = held["cores"] if isinstance(held, dict) else held + return result diff --git a/scripts/packs/verdicts.py b/scripts/packs/verdicts.py new file mode 100644 index 000000000..a0998ef92 --- /dev/null +++ b/scripts/packs/verdicts.py @@ -0,0 +1,290 @@ +"""Per-file verdicts and their severity, in each platform's native mode.""" + +from __future__ import annotations + +from core.hashing import compute_hashes, md5sum, parse_md5_list +from core.ziptools import check_inside_zip +from resolve.nativemode import SIZE_AND_ANY_HASH, reads_file_contents +from resolve.validation import ( + check_file_validation, + existence_discrepancy, + frontend_digest_matches, + validated_choice, +) + + +DEFAULT_BIOS_DIR = "bios" + + +DEFAULT_EMULATORS_DIR = "emulators" + + +class Status: + OK = "ok" + UNTESTED = "untested" # file present, hash not confirmed: a warning, never --strict + MISSING = "missing" + + +# A declaration whose file is a release asset the cache does not hold yet: +# an online build fetches it, verify reads the database record instead. +RELEASE_ASSET_PENDING = "release_asset_pending" + + +class Severity: + CRITICAL = "critical" # required file missing or bad hash (Recalbox RED) + WARNING = "warning" # optional missing or hash mismatch (Recalbox YELLOW) + INFO = "info" # optional missing on existence-only platform + OK = "ok" # file verified + + +_STATUS_ORDER = {Status.OK: 0, Status.UNTESTED: 1, Status.MISSING: 2} +_SEVERITY_ORDER = { + Severity.OK: 0, + Severity.INFO: 1, + Severity.WARNING: 2, + Severity.CRITICAL: 3, +} + + +def verify_entry_existence( + file_entry: dict, + local_path: str | None, + validation_index: dict[str, dict] | None = None, + db: dict | None = None, + destination: str = "", + owners: dict | None = None, + resolve_status: str = "", + platform_display: str = "", +) -> dict: + """RetroArch verification: path_is_valid(), a file that exists is OK. + The result names the collection file found, as the hash modes do.""" + name = file_entry.get("name", "") + required = file_entry.get("required", True) + if not local_path: + return {"name": name, "status": Status.MISSING, "required": required} + result = {"name": name, "status": Status.OK, "required": required, "path": local_path} + if resolve_status == "hash_mismatch": + # The frontend reads no bytes, so the file stays, and the declared hash + # it contradicts is reported, as the pack does. + result["discrepancy"] = existence_discrepancy( + file_entry, local_path, platform_display + ) + return result + if not validation_index: + return result + if db: + # The pack ships the variant this returns, so a disagreement it + # settles is not reported. + _chosen, disagreement = validated_choice( + file_entry, local_path, db, validation_index, "bios", None, + destination, owners, + ) + else: + check = check_file_validation(local_path, name, validation_index) + disagreement = f"{', '.join(check[1])} says {check[0]}" if check else None + if disagreement: + result["discrepancy"] = f"file present (OK) but {disagreement}" + return result + + +def _verify_zipped_md5( + base: dict, local_path: str, zipped_file: str, md5_list: list[str], +) -> dict: + """The md5 check of an entry naming the ROM inside its ZIP (zipped_file).""" + found_in_zip = False + had_error = False + for md5_candidate in md5_list or [""]: + result = check_inside_zip(local_path, zipped_file, md5_candidate) + if result == Status.OK: + return {**base, "status": Status.OK, "path": local_path} + if result == "error": + had_error = True + elif result != "not_in_zip": + found_in_zip = True + if had_error and not found_in_zip: + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"{local_path} read error", + } + if not found_in_zip: + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"{zipped_file} not found inside ZIP", + } + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"{zipped_file} MD5 mismatch inside ZIP", + } + + +def verify_entry_md5( + file_entry: dict, + local_path: str | None, + resolve_status: str = "", + hash_rule: str = "", +) -> dict: + """MD5 verification -Batocera md5sum + Recalbox multi-hash + Md5Composite. + + Under SIZE_AND_ANY_HASH (RomM) the size and any one declared hash decide. + """ + name = file_entry.get("name", "") + expected_md5 = file_entry.get("md5", "") + zipped_file = file_entry.get("zipped_file") + required = file_entry.get("required", True) + base = {"name": name, "required": required} + + # One parse for verify, the builder and the pack check: Recalbox writes + # md5 in uppercase, and a copy that lowercased only comma lists judged + # a single uppercase value differently from the others. + md5_list = parse_md5_list(expected_md5) + + if not local_path: + return {**base, "status": Status.MISSING} + + if hash_rule == SIZE_AND_ANY_HASH: + if frontend_digest_matches(file_entry, local_path, "md5", hash_rule): + return {**base, "status": Status.OK, "path": local_path} + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": "the declared size and at least one declared hash must match", + } + + if zipped_file: + return _verify_zipped_md5(base, local_path, zipped_file, md5_list) + + if not md5_list: + if resolve_status == "hash_mismatch": + # No md5 to compare does not mean nothing was compared: the entry + # declares a sha1 or a crc32 the local file contradicts, and the + # builder drops it for exactly that. Reporting OK here said the + # collection holds bytes it does not. + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": "declared hash contradicted by the local file", + } + return {**base, "status": Status.OK, "path": local_path} + + if resolve_status == "md5_exact": + return {**base, "status": Status.OK, "path": local_path} + + # The builder's comparison, so the two count the same files as held. + if frontend_digest_matches(file_entry, local_path, "md5"): + return {**base, "status": Status.OK, "path": local_path} + actual_md5 = md5sum(local_path) + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"expected {md5_list[0][:12]}... got {actual_md5[:12]}...", + } + + +def verify_entry_sha1( + file_entry: dict, + local_path: str | None, +) -> dict: + """SHA1 verification -BizHawk firmware hash check.""" + name = file_entry.get("name", "") + expected_sha1 = file_entry.get("sha1", "") + required = file_entry.get("required", True) + base = {"name": name, "required": required} + + if not local_path: + return {**base, "status": Status.MISSING} + + if not expected_sha1: + return {**base, "status": Status.OK, "path": local_path} + + hashes = compute_hashes(local_path) + actual_sha1 = hashes["sha1"].lower() + if actual_sha1 == expected_sha1.lower(): + return {**base, "status": Status.OK, "path": local_path} + + return { + **base, + "status": Status.UNTESTED, + "path": local_path, + "reason": f"expected {expected_sha1[:12]}... got {actual_sha1[:12]}...", + } + + +def _emulator_severity(status: str, required: bool, hle_fallback: bool) -> str: + """Severity when the emulator's own code is the check. + + A file present but refused by the core's validation, or a different dump + than the one the profile declares, is not a file the core runs with: + read in existence mode it counted OK, and `verify --emulator` announced + 1/1 OK above the line that said the core would refuse it. + """ + if status == Status.UNTESTED: + return Severity.WARNING + return compute_severity(status, required, "existence", hle_fallback) + + +def compute_severity( + status: str, + required: bool, + mode: str, + hle_fallback: bool = False, +) -> str: + """Map (status, required, verification_mode, hle_fallback) -> severity. + + Based on native platform behavior + emulator HLE capability: + - RetroArch (existence): required+missing = warning, optional+missing = info + - Batocera/Recalbox/RetroBat/EmuDeck (md5): hash-based verification + - BizHawk (sha1): same severity rules as md5 + - hle_fallback: core works without this file via HLE -> always INFO when missing + """ + if status == Status.OK: + return Severity.OK + + # HLE fallback: core works without this file regardless of platform requirement + if hle_fallback and status == Status.MISSING: + return Severity.INFO + + if not reads_file_contents(mode): + if status == Status.MISSING: + return Severity.WARNING if required else Severity.INFO + return Severity.OK + + # md5 mode (Batocera, Recalbox, RetroBat, EmuDeck) + if status == Status.MISSING: + return Severity.CRITICAL if required else Severity.WARNING + if status == Status.UNTESTED: + return Severity.WARNING + return Severity.OK + + +def _storage_verdict(file_entry: dict, emulator_pack: bool) -> dict | None: + """The result a storage tier fixes before any lookup, as the builder sees it. + + A user_provided entry is never taken from the collection: a platform pack + writes its instructions in the slot and counts it filled, an emulator pack + lists it to provide. An external one is fetched from its URL when the pack + is built, never read from bios/. Resolving either by name credited a + same-named file the pack does not carry. + """ + storage = file_entry.get("storage", "embedded") + base = {"name": file_entry.get("name", ""), "required": file_entry.get("required", True)} + if storage == "user_provided": + if emulator_pack: + stated = file_entry.get("unsourceable") + why = ( + stated if isinstance(stated, str) and stated + else file_entry.get("instructions") or "the user provides it" + ) + return {**base, "status": Status.MISSING, "unsourceable": why} + return {**base, "status": Status.OK, "user_provided": True} + if storage == "external": + return {**base, "status": Status.MISSING, "reason": "fetched from its URL when the pack is built"} + return None diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 2f71afc0a..1275f7d1e 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -78,11 +78,11 @@ from core.artifacts import ( ) 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 +from packs.datadirs import hold_data_dirs +from packs.paths import MEDIA_MARKER if TYPE_CHECKING: - from generate_pack import PackRecord + from packs.archive import PackRecord class StepResults(dict): @@ -455,20 +455,20 @@ def _tree_members( platform: str, platforms_dir: str, emulators_dir: str = "emulators", ) -> dict[str, int]: """Archive path -> size of every file the platform's data trees can add.""" - import generate_pack + from packs import datatrees from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from packpaths import _flat + from packs.paths import _flat config = load_platform_config(platform, platforms_dir) base_dest = config.get("base_destination", "") registry = load_data_dir_registry(platforms_dir) - core_trees = generate_pack.core_data_trees( + core_trees = datatrees.core_data_trees( config, load_emulator_profiles(emulators_dir), platform, registry, ) members: dict[str, int] = {} with contextlib.redirect_stdout(io.StringIO()): - for src, full in generate_pack._data_directory_members( + for src, full in datatrees._data_directory_members( config.get("systems", {}), registry, platform, base_dest, False, set(), set(), set(), core_trees=core_trees, @@ -578,9 +578,10 @@ def check_emulator_packs( required-only rules are written twice, once per side, and only this comparison holds them together. No archive is written and no file read. """ - import generate_pack - import packresolve - import verify + from packs import archive + from packs import emulatorpack + from resolve import packfiles as packresolve + from packs import emulatorcheck from model.profiles import ( ProfileSelectionError, load_emulator_profiles, @@ -597,7 +598,7 @@ def check_emulator_packs( profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) def compare(names: list[str], standalone: bool, label: str, **narrowing: object) -> bool: - record = generate_pack.PackRecord() + record = archive.PackRecord() was_offline = packresolve._OFFLINE # The pack is built offline: verify counts a release asset the cache # lacks the same way, missing, as the narrowed-pack step does. @@ -605,12 +606,12 @@ def check_emulator_packs( try: with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): - generate_pack.generate_emulator_pack( + emulatorpack.generate_emulator_pack( names, emulators_dir, db, "bios", "", standalone, zip_contents=zip_contents, offline=True, platforms_dir=platforms_dir, record=record, **narrowing, ) - report = verify.verify_emulator( + report = emulatorcheck.verify_emulator( names, emulators_dir, db, standalone, platforms_dir=platforms_dir, **narrowing, ) @@ -750,9 +751,10 @@ def check_narrowed_packs( compares every value. NARROWINGS_NOT_COMPARED says why --source and --one-per-slot are not compared. """ - import generate_pack - import packresolve - import verify + from packs import archive + from packs import platformpack + from resolve import packfiles as packresolve + from packs import coverage from core.ziptools import build_zip_contents_index from resolve.grouping import group_identical_platforms from model.registry import list_registered_platforms @@ -784,17 +786,17 @@ def check_narrowed_packs( target_cores = ( load_target_config(platform, target, platforms_dir) if target else None ) - record = generate_pack.PackRecord() + record = archive.PackRecord() with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): - built = generate_pack.generate_pack( + built = platformpack.generate_pack( platform, platforms_dir, db, "bios", "", emulators_dir=emulators_dir, zip_contents=zip_contents, data_registry=registry, emu_profiles=profiles, target_cores=target_cores, offline=True, record=record, **narrowing, ) - report = verify.verify_platform( + report = coverage.verify_platform( load_platform_config(platform, platforms_dir), db, emulators_dir, profiles, target_cores=target_cores, data_dir_registry=registry, @@ -860,8 +862,10 @@ def check_split_packs( RetroBat's 21 openmsx/ twins of openMSX/ files. Offline, as every comparison of this step. """ - import generate_pack - import packresolve + from packs import archive + from packs import bysystem + from packs import platformpack + from resolve import packfiles as packresolve 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 @@ -886,17 +890,17 @@ def check_split_packs( emulators_dir=emulators_dir, zip_contents=zip_contents, data_registry=registry, emu_profiles=profiles, offline=True, ) - full = generate_pack.PackRecord() - parts: dict[str, generate_pack.PackRecord] = {} + full = archive.PackRecord() + parts: dict[str, archive.PackRecord] = {} with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): - generate_pack.generate_pack( + platformpack.generate_pack( platform, platforms_dir, db, "bios", "", record=full, **args, ) - generate_pack.generate_split_packs( + bysystem.generate_split_packs( platform, platforms_dir, db, "bios", "", records=parts, **args, ) - lines = split_differences(full, parts, generate_pack._same_bytes) + lines = split_differences(full, parts, archive._same_bytes) if lines: all_ok = False print(f" {platform} --split: {len(lines)} differences") diff --git a/scripts/profile_sync.py b/scripts/profile_sync.py index 77ffca307..90030df87 100644 --- a/scripts/profile_sync.py +++ b/scripts/profile_sync.py @@ -289,7 +289,7 @@ def project_base() -> str: is HEAD, and --changed --strict found nothing and passed while the PR's CI then failed. validate_pr.py resolves the same line the same way. """ - from validate_pr import _git_lines as git_lines, _project_main_line + from core.gitclone import _git_lines as git_lines, _project_main_line line = _project_main_line() if line: diff --git a/scripts/refresh_data_dirs.py b/scripts/refresh_data_dirs.py index 147f9f1da..285638666 100644 --- a/scripts/refresh_data_dirs.py +++ b/scripts/refresh_data_dirs.py @@ -13,648 +13,16 @@ Usage: from __future__ import annotations import argparse -import contextlib -import json import logging import os -import shutil -import tarfile -import tempfile -import time -import urllib.error -import urllib.request -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 core.cli import InputMissing, suggest_names -from core.github import github_token +from core.cli import suggest_names from model.cliargs import platform_arg, require_platform -from model.safeparse import yaml_load try: import yaml except ImportError: yaml = None - -log = logging.getLogger(__name__) - -DEFAULT_REGISTRY = "platforms/_data_dirs.yml" -VERSIONS_FILE = "data/.versions.json" -USER_AGENT = "retrobios/1.0" -REQUEST_TIMEOUT = 30 -DOWNLOAD_TIMEOUT = 300 -# A mirror sometimes answers with a page that is not the archive: the -# buildbot's ScummVM.zip failed CI once as "File is not a zip file" and -# downloaded fine minutes later. Seconds to wait before each retry. -DOWNLOAD_RETRY_WAITS = (5, 20) -_TRANSIENT = (urllib.error.URLError, OSError, tarfile.TarError, zipfile.BadZipFile, EOFError) - - -def load_registry(registry_path: str = DEFAULT_REGISTRY) -> dict[str, dict]: - if yaml is None: - raise ImportError("PyYAML required: pip install pyyaml") - path = Path(registry_path) - if not path.exists(): - raise InputMissing(f"Registry not found: {registry_path}") - with open(path) as f: - data = yaml_load(f) or {} - return data.get("data_directories", {}) - - -def cache_lock( - cache_dir: str | Path, shared: bool = False -) -> contextlib.AbstractContextManager[None]: - """The lock a refresh holds while it swaps cache_dir. - - A reader takes it shared: a pack walking data/sdlpal while another run - swapped the tree shipped part of it, or nothing. - """ - cache_dir = Path(cache_dir) - return _announced_lock(cache_dir.with_name(f".{cache_dir.name}.lock"), shared, cache_dir) - - -def _wait_message(lock_path: Path, shared: bool, cache_dir: Path) -> str: - """Who to wait for, and, for a refresh, how not to. - - The bare "another run holds it" named neither the lock nor its holder, - and the build waited with no limit. - """ - message = ( - f"waiting for {cache_dir}: another run holds {lock_path} " - f"(lsof {lock_path} names it)" - ) - if not shared: - message += ( - ". generate_pack.py --no-refresh-data, or --offline there and in" - " pipeline.py, builds from the cache as it is without waiting" - ) - return message - - -@contextlib.contextmanager -def _announced_lock(lock_path: Path, shared: bool, cache_dir: Path) -> Iterator[None]: - """file_lock, saying so when it has to wait. - - A pipeline holds every cache for its whole run: a refresh started beside - it waited hours with nothing on screen. - """ - try: - import fcntl - except ImportError: - with _file_lock(lock_path, shared=shared): - yield - return - lock_path.parent.mkdir(parents=True, exist_ok=True) - mode = fcntl.LOCK_SH if shared else fcntl.LOCK_EX - with open(lock_path, "a") as handle: - try: - fcntl.flock(handle, mode | fcntl.LOCK_NB) - except BlockingIOError: - log.warning(_wait_message(lock_path, shared, cache_dir)) - fcntl.flock(handle, mode) - try: - yield - finally: - fcntl.flock(handle, fcntl.LOCK_UN) - - -def hold_data_dirs(stack: contextlib.ExitStack, registry: dict) -> None: - """Hold every cached data directory shared for the life of *stack*. - - A pack resolves names against a tree, then copies the file minutes - later. A refresh swapping the tree in between shipped bytes nobody - verified, or died on a file the new tree no longer has. A refresh waits - for the holders. Never called before a refresh in the same process: - the exclusive lock would wait on this one. A cache not yet on disk is - held too: the lock sits beside the tree, and skipped, a refresh could - install the tree after verify ran and before the packs read it. - """ - for entry in registry.values(): - cache = entry.get("local_cache", "") - if cache: - stack.enter_context(cache_lock(cache, shared=True)) - - -def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]: - path = Path(versions_path) - if not path.exists(): - return {} - with open(path) as f: - return json.load(f) - - -def _save_versions( - versions: dict[str, dict], versions_path: str = VERSIONS_FILE -) -> None: - """Write the version file whole or not at all. - - Truncating in place let a concurrent reader load an empty file and die - on JSONDecodeError. The scratch file sits beside the target so the - rename stays on one filesystem. - """ - path = Path(versions_path) - path.parent.mkdir(parents=True, exist_ok=True) - handle, scratch = tempfile.mkstemp( - dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" - ) - try: - with os.fdopen(handle, "w") as f: - json.dump(versions, f, indent=2, sort_keys=True) - f.write("\n") - set_plain_mode(scratch) - os.replace(scratch, path) - except BaseException: - with contextlib.suppress(OSError): - os.unlink(scratch) - raise - - -def _record_version(key: str, record: dict, versions_path: str) -> None: - """Set one key under the file lock, so two writers keep both updates.""" - path = Path(versions_path) - with _file_lock(path.with_name(f".{path.name}.lock")): - versions = _load_versions(versions_path) - versions[key] = record - _save_versions(versions, versions_path) - - -def _staging_dir(cache_dir: Path) -> tempfile.TemporaryDirectory: - """Scratch space beside the cache, on its filesystem. - - /tmp is a 4 GB tmpfs here: staging there filled it and turned the - promotion into a copy, during which the cache held a partial tree. - """ - cache_dir.parent.mkdir(parents=True, exist_ok=True) - return tempfile.TemporaryDirectory( - dir=cache_dir.parent, prefix=f".{cache_dir.name}-" - ) - - -def _promote(extract_dir: Path, cache_dir: Path, scratch: Path) -> None: - """Swap the new tree in by renames alone. - - The old tree steps aside into the run's own scratch directory, never a - fixed sibling name another run could be using, and comes back if the - new one cannot be moved in. - """ - previous = scratch / "previous" - if cache_dir.exists(): - os.replace(cache_dir, previous) - try: - os.replace(extract_dir, cache_dir) - except BaseException: - if previous.exists() and not cache_dir.exists(): - os.replace(previous, cache_dir) - raise - - -def _api_request(url: str) -> dict: - req = urllib.request.Request( - url, - headers={ - "User-Agent": USER_AGENT, - "Accept": "application/json", - }, - ) - token = github_token() - if token and "github" in url: - req.add_header("Authorization", f"token {token}") - with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: - return json.loads(resp.read()) - - -def _parse_repo_from_url(source_url: str) -> tuple[str, str, str]: - """Extract (host_type, owner, repo) from a tarball URL. - - Returns host_type as 'github' or 'gitlab'. - """ - if "github.com" in source_url: - # https://github.com/owner/repo/archive/{version}.tar.gz - parts = source_url.split("github.com/")[1].split("/") - return "github", parts[0], parts[1] - if "gitlab.com" in source_url: - parts = source_url.split("gitlab.com/")[1].split("/") - return "gitlab", parts[0], parts[1] - raise ValueError(f"Unsupported host in URL: {source_url}") - - -def get_remote_sha(source_url: str, version: str) -> str | None: - """Fetch the current commit SHA for a branch/tag from GitHub or GitLab.""" - try: - host_type, owner, repo = _parse_repo_from_url(source_url) - except ValueError: - log.warning("cannot parse repo from URL: %s", source_url) - return None - - try: - if host_type == "github": - url = f"https://api.github.com/repos/{owner}/{repo}/commits/{version}" - data = _api_request(url) - return data["sha"] - else: - encoded = f"{owner}%2F{repo}" - url = f"https://gitlab.com/api/v4/projects/{encoded}/repository/branches/{version}" - data = _api_request(url) - return data["commit"]["id"] - except (urllib.error.URLError, KeyError, OSError) as exc: - log.warning( - "failed to fetch remote SHA for %s/%s@%s: %s", owner, repo, version, exc - ) - return None - - -class NothingExtractedError(Exception): - """An archive that yields no file for the cache. - - Promoting it replaced the cache with an empty directory, recorded the new - version and reported success, so the next run read "up to date" and the - packs left without the directory. - """ - - -def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool: - """Reject path traversal, absolute paths, and symlinks in tar members.""" - if member.issym() or member.islnk(): - return False - if member.name.startswith("/") or ".." in member.name.split("/"): - return False - resolved = (dest / member.name).resolve() - dest_str = str(dest.resolve()) + os.sep - return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve()) - - -def _download_and_extract( - source_url: str, - source_path: str, - local_cache: str, - exclude: list[str] | None = None, - measured: Callable[[int], None] | None = None, -) -> int: - """Download tarball, extract source_path subtree to local_cache. - - Returns the number of files extracted. measured receives the size of - the archive downloaded. - """ - exclude = exclude or [] - cache_dir = Path(local_cache) - - with _staging_dir(cache_dir) as tmpdir: - tarball_path = Path(tmpdir) / "archive.tar.gz" - log.info("downloading %s", source_url) - - req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) - with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(tarball_path, "wb") as f: - while True: - chunk = resp.read(65536) - if not chunk: - break - f.write(chunk) - if measured is not None: - measured(tarball_path.stat().st_size) - - log.info("extracting %s -> %s", source_path, local_cache) - - prefix = source_path.rstrip("/") + "/" - file_count = 0 - - with tarfile.open(tarball_path, "r:gz") as tf: - extract_dir = Path(tmpdir) / "extract" - extract_dir.mkdir() - - for member in tf.getmembers(): - if not member.name.startswith(prefix) and member.name != source_path: - continue - - rel = member.name[len(prefix) :] - if not rel: - continue - - # skip excluded subdirectories - top_component = rel.split("/")[0] - if top_component in exclude: - continue - - if not _is_safe_tar_member(member, extract_dir): - log.warning("skipping unsafe tar member: %s", member.name) - continue - - # rewrite member name to relative path - member_copy = tarfile.TarInfo(name=rel) - member_copy.size = member.size - member_copy.mode = member.mode - member_copy.type = member.type - - if member.isdir(): - (extract_dir / rel).mkdir(parents=True, exist_ok=True) - elif member.isfile(): - dest_file = extract_dir / rel - dest_file.parent.mkdir(parents=True, exist_ok=True) - src = tf.extractfile(member) - if src is None: - continue - with src, open(dest_file, "wb") as dst: - shutil.copyfileobj(src, dst) - file_count += 1 - - if not file_count: - raise NothingExtractedError(f"no file under {source_path} in the archive") - _promote(extract_dir, cache_dir, Path(tmpdir)) - - return file_count - - -def _download_and_extract_zip( - source_url: str, - local_cache: str, - exclude: list[str] | None = None, - strip_components: int = 0, - measured: Callable[[int], None] | None = None, -) -> int: - """Download ZIP, extract to local_cache. Returns file count. - - strip_components removes N leading path components from each entry - (like tar --strip-components). Useful when a ZIP has a single root - directory that should be flattened. - """ - exclude = exclude or [] - cache_dir = Path(local_cache) - - with _staging_dir(cache_dir) as tmpdir: - zip_path = Path(tmpdir) / "archive.zip" - log.info("downloading %s", source_url) - - req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) - with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(zip_path, "wb") as f: - while True: - chunk = resp.read(65536) - if not chunk: - break - f.write(chunk) - if measured is not None: - measured(zip_path.stat().st_size) - - extract_dir = Path(tmpdir) / "extract" - extract_dir.mkdir() - file_count = 0 - - with zipfile.ZipFile(zip_path) as zf: - for info in zf.infolist(): - if info.is_dir(): - continue - name = info.filename - if ".." in name or name.startswith("/"): - continue - # strip leading path components - parts = name.split("/") - if strip_components > 0: - if len(parts) <= strip_components: - continue - parts = parts[strip_components:] - name = "/".join(parts) - # skip excludes (check against stripped path) - top = parts[0] if parts else "" - if top in exclude: - continue - dest = extract_dir / name - dest.parent.mkdir(parents=True, exist_ok=True) - with zf.open(info) as src, open(dest, "wb") as dst: - shutil.copyfileobj(src, dst) - file_count += 1 - - if not file_count: - raise NothingExtractedError("the archive holds no file to extract") - # The old tree is stepped aside rather than deleted: removing it - # first and then failing to move the new one in left the cache with - # nothing at all, and the next run reads that as "never fetched". - _promote(extract_dir, cache_dir, Path(tmpdir)) - - return file_count - - -def _measure_archive(source_url: str) -> int | None: - """The size of the archive at source_url, read by streaming it: a - tarball GitHub builds on request is sent without a Content-Length.""" - req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) - size = 0 - try: - with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp: - while chunk := resp.read(65536): - size += len(chunk) - except _TRANSIENT as exc: - log.warning("could not measure %s: %s", source_url, exc) - return None - return size or None - - -def _record_archive_size(key: str, entry: dict, versions_path: str) -> None: - """Record the archive size of a tree current since before it was kept. - - The installer announces a tree's download as that size: a tarball - whose tree is 10 KB is a download of 21 MB. Measured, not refetched, - so the tree the packs carry stays the one recorded. - """ - path = Path(versions_path) - with _file_lock(path.with_name(f".{path.name}.lock")): - versions = _load_versions(versions_path) - record = versions.get(key) - if record is None or "archive_size" in record: - return - version = entry.get("version", "master") - size = _measure_archive(entry["source_url"].format(version=version)) - if size is None: - return - with _file_lock(path.with_name(f".{path.name}.lock")): - versions = _load_versions(versions_path) - if key in versions and "archive_size" not in versions[key]: - versions[key]["archive_size"] = size - _save_versions(versions, versions_path) - log.info("[%s] archive size recorded: %d bytes", key, size) - - -def _get_remote_etag(source_url: str) -> str | None: - """HEAD request to get ETag or Last-Modified for freshness check.""" - try: - req = urllib.request.Request( - source_url, method="HEAD", headers={"User-Agent": USER_AGENT} - ) - with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: - return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "" - except (urllib.error.URLError, OSError): - return None - - -def _short_tag(tag: str | None) -> str: - """A commit sha or ETag cut for a log line, quotes dropped first: a - quoted ETag cut at 12 characters kept its opening quote only.""" - if not tag: - return "none" - return tag.strip().removeprefix("W/").strip('"')[:12] or "none" - - -def refresh_entry( - key: str, - entry: dict, - *, - force: bool = False, - dry_run: bool = False, - versions_path: str = VERSIONS_FILE, -) -> bool | None: - """Refresh a single data directory entry. - - Returns True if the entry was refreshed (or would be in dry-run mode). - The decision and the swap run under one lock per directory: a run that - waited for another session re-reads the version it recorded and finds - nothing left to do. - - The exclusive lock waits for every reader, and a pipeline reads the - trees for its whole run: a second build sat on "waiting" for a tree the - remote check would have found current. The check is made first without - it, and only a tree to replace waits. - """ - if dry_run: - return _refresh_entry(key, entry, force, dry_run, versions_path) - if not force: - needs, _remote, cached_tag = _decide(key, entry, False, versions_path) - if needs is None: - return None - if not needs: - log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag)) - _record_archive_size(key, entry, versions_path) - return False - with cache_lock(entry["local_cache"]): - return _refresh_entry(key, entry, force, dry_run, versions_path) - - -def _decide( - key: str, entry: dict, force: bool, versions_path: str -) -> tuple[bool | None, str | None, str | None]: - """(whether the tree needs a refresh, the remote tag read, the recorded - tag). None when the remote could not be read.""" - version = entry.get("version", "master") - cached = _load_versions(versions_path).get(key, {}) - cached_tag = cached.get("sha") or cached.get("etag") - if force or not Path(entry["local_cache"]).exists(): - return True, None, cached_tag - if entry.get("source_type", "tarball") == "zip": - remote_tag = _get_remote_etag(entry["source_url"].format(version=version)) - else: - remote_tag = get_remote_sha(entry["source_url"], version) - if remote_tag is None: - log.warning("[%s] could not check remote, skipping", key) - return None, None, cached_tag - return remote_tag != cached_tag, remote_tag, cached_tag - - -def _refresh_entry( - key: str, entry: dict, force: bool, dry_run: bool, versions_path: str -) -> bool | None: - source_type = entry.get("source_type", "tarball") - version = entry.get("version", "master") - source_url = entry["source_url"].format(version=version) - local_cache = entry["local_cache"] - exclude = entry.get("exclude", []) - - needs_refresh, remote_tag, cached_tag = _decide(key, entry, force, versions_path) - if needs_refresh is None: - return None - if not needs_refresh: - log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag)) - return False - - if dry_run: - if remote_tag is not None: - reason = f"cached: {_short_tag(cached_tag)}, remote: {_short_tag(remote_tag)}" - elif force: - reason = "forced" - else: - reason = "not cached" - log.info("[%s] would refresh (type: %s, %s)", key, source_type, reason) - return True - - if remote_tag is None: - # Read before the download. A release published in between then - # leaves an older tag on newer content, which the next run refreshes. - # Read after, it left a newer tag on older content, trusted for good. - if source_type == "zip": - remote_tag = _get_remote_etag(source_url) - else: - remote_tag = get_remote_sha(entry["source_url"], version) - - archive_sizes: list[int] = [] - - def fetch() -> int: - archive_sizes.clear() - if source_type == "zip": - return _download_and_extract_zip( - source_url, local_cache, exclude, entry.get("strip_components", 0), - measured=archive_sizes.append, - ) - source_path = entry["source_path"].format(version=version) - return _download_and_extract( - source_url, source_path, local_cache, exclude, measured=archive_sizes.append - ) - - # An archive that reads but holds nothing under the path is the same on - # every try: only a failed or unreadable download is tried again. - for attempt, wait in enumerate((*DOWNLOAD_RETRY_WAITS, None), start=1): - try: - file_count = fetch() - break - except NothingExtractedError as exc: - log.warning("[%s] download failed: %s", key, exc) - return None - except _TRANSIENT as exc: - if wait is None: - log.warning("[%s] download failed after %d tries: %s", key, attempt, exc) - return None - log.warning("[%s] download failed (%s), trying again in %d s", key, exc, wait) - time.sleep(wait) - - record = {"sha": remote_tag or "", "version": version} - if archive_sizes: - record["archive_size"] = archive_sizes[-1] - _record_version(key, record, versions_path) - - log.info("[%s] refreshed: %d files extracted to %s", key, file_count, local_cache) - return True - - -def refresh_all( - registry: dict[str, dict], - *, - force: bool = False, - dry_run: bool = False, - versions_path: str = VERSIONS_FILE, - platform: str | None = None, -) -> dict[str, bool | None]: - """Refresh all entries in the registry. - - If platform is set, only refresh entries whose for_platforms - includes that platform (or entries with no for_platforms restriction). - Returns a dict mapping key -> True when refreshed, False when already up - to date, None when the refresh failed. A single boolean conflated the last - two, so a run that reached no remote at all exited 0 like a run with - nothing to do. - """ - results = {} - for key, entry in registry.items(): - allowed = entry.get("for_platforms") - if platform and allowed and platform not in allowed: - continue - results[key] = refresh_entry( - key, - entry, - force=force, - dry_run=dry_run, - versions_path=versions_path, - ) - if any(results.values()): - # A cache the resolver indexed in this process has changed under it. - from resolve.datadirs import forget_data_dir_index - - forget_data_dir_index() - return results +from packs.datadirs import DEFAULT_REGISTRY, load_registry, log, refresh_all, refresh_entry def summarize(outcomes: dict[str, bool | None], dry_run: bool) -> str: diff --git a/scripts/release_record.py b/scripts/release_record.py index ffbce252c..48b2ae529 100644 --- a/scripts/release_record.py +++ b/scripts/release_record.py @@ -22,7 +22,7 @@ import sys import zipfile from pathlib import Path -import split_pack +from packs import parts from core.artifacts import ArtifactLockBusy, artifact_lock, write_text_atomic from model.registry import list_release_pack_platforms @@ -52,11 +52,11 @@ def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]: the full pack and was taken for the RetroArch pack. Only the platforms marked release_pack own a release pack. """ - import generate_pack + from packs import naming platforms = list_release_pack_platforms(platforms_dir) owners: dict[str, list[str]] = {} - for platform, names in generate_pack._expected_pack_names( + for platform, names in naming._expected_pack_names( platforms, platforms_dir, None, None ).items(): for name in names: @@ -88,9 +88,9 @@ def build_record( def _read_record(dist: Path, tag: str, owners: dict[str, list[str]]) -> dict: assets: dict[str, list[Path]] = {} for path in sorted(dist.glob("*_BIOS_Pack*.zip")): - assets.setdefault(split_pack.pack_of(path.name), []).append(path) + assets.setdefault(parts.pack_of(path.name), []).append(path) for paths in assets.values(): - whole = [p for p in paths if not split_pack.is_part(p.name)] + whole = [p for p in paths if not parts.is_part(p.name)] if whole and len(paths) > len(whole): raise UnfinishedSplitError( f"{whole[0].name} lies beside its parts: the split did not finish" @@ -110,7 +110,7 @@ def _read_record(dist: Path, tag: str, owners: dict[str, list[str]]) -> dict: # A part's marker names its siblings and is not pack content: # the manifest's pack_files is counted before any split. for info in archive.infolist(): - if not split_pack.is_marker(info.filename): + if not parts.is_marker(info.filename): members[info.filename] = info.file_size packs[name] = { "files": len(members), diff --git a/scripts/resolve/collisions.py b/scripts/resolve/collisions.py new file mode 100644 index 000000000..73f14fa7a --- /dev/null +++ b/scripts/resolve/collisions.py @@ -0,0 +1,230 @@ +"""Destinations a platform declares twice and resolves to two different files.""" + +from __future__ import annotations + +import os +import zlib +from dataclasses import dataclass, field + +from core.hashing import compute_hashes, parse_md5_list +from core.ziptools import check_inside_zip +from resolve.localfile import resolve_local_file, variant_base_name +from resolve.packfiles import preferred_entries + + +def _normalize(destination: str, fold: bool = True) -> str: + """Comparable form of a destination, since layers write it differently. + + Case is folded only where the platform's filesystem folds it: on Linux + RetroDECK ships bios/DISK.ROM and bios/disk.rom side by side. + """ + cleaned = destination.strip().strip("/").replace("\\", "/") + return cleaned.casefold() if fold else cleaned + + +@dataclass +class Collision: + """One destination a platform fills with two different files.""" + + destination: str + resolved: list[str] + # Each declaration with the file it resolved to, in the platform's order. + declarations: list[tuple[dict, str | None]] = field(default_factory=list) + # The system of each declaration, in the same order. + systems: list[str] = field(default_factory=list) + # The file the pack ships at the destination, as the builder decides it. + shipped: str | None = None + + +def find_collisions( + config: dict, + db: dict, + zip_contents: dict | None = None, + data_dir_registry: dict | None = None, +) -> list[Collision]: + """Destinations a platform declares twice and resolves two ways. + + One path holds one file, so whichever declaration the builder reaches + first decides in silence. Declaring an archive several times to name its + inner ROMs is the documented zipped_file pattern and resolves to one + archive. Two declarations landing on two files name two files for one + path. RetroDECK aims a PC-88 disk subsystem ROM and a + CoCo disk ROM at one bios/disk.rom. + """ + fold = bool(config.get("case_insensitive_fs", False)) + systems = config.get("systems") or {} + # The builder lets a hash-constrained declaration that resolves by + # content take the path, else the first it reaches walking the systems + # sorted: the same choice says which file ships. + preferred = set( + preferred_entries(systems, db, "bios", "", False, zip_contents, True).values() + ) + by_dest: dict[str, list[tuple[str, dict]]] = {} + for sys_id, system in systems.items(): + for entry in system.get("files") or []: + if not isinstance(entry, dict): + continue + dest = entry.get("destination") or entry.get("name") or "" + if dest: + by_dest.setdefault(_normalize(dest, fold), []).append((sys_id, entry)) + + collisions = [] + for key, claims in sorted(by_dest.items()): + if len(claims) < 2: + continue + entries = [entry for _sys_id, entry in claims] + resolved = [] + declarations = [] + for entry in entries: + local, _ = resolve_local_file( + entry, + db, + zip_contents, + dest_hint=entry.get("destination", ""), + data_dir_registry=data_dir_registry, + ) + declarations.append((entry, local)) + if local and local not in resolved: + resolved.append(local) + if len(resolved) > 1 and not _same_file_family(resolved): + # A file every declaration accepts settles the path: RetroDECK + # declares ATARIOSB.ROM twice, the second with an md5 list that + # also names the first one's file. + if any(_accepted_by_all(path, entries, db) for path in resolved): + continue + reached = sorted( + (sys_id, local) + for (sys_id, _entry), (_e, local) in zip(claims, declarations) if local + ) + shipped = next( + (local for entry, local in declarations if local and id(entry) in preferred), + reached[0][1], + ) + collisions.append( + Collision( + destination=key, + resolved=resolved, + declarations=declarations, + systems=[sys_id for sys_id, _entry in claims], + shipped=shipped, + ) + ) + return collisions + + +def _lists_hashes(entry: dict) -> bool: + """Whether a declaration says anything about content at all.""" + return any( + _declared_hashes(entry, field_name) + for field_name in ("md5", "sha1", "sha256", "crc32") + ) + + +def _declared_hashes(entry: dict, field_name: str) -> set[str]: + """Hashes an entry accepts for one field, declared as a string or a list.""" + value = entry.get(field_name) + values = value if isinstance(value, list) else [value] + # Recalbox writes its md5 list comma separated, and profiles do the + # same for sha256 (mesence names four BS-X dumps in one string). + return { + part.strip().lower() + for v in values + if v + for part in str(v).split(",") + if part.strip() + } + + +def _record_at(path: str, db: dict) -> dict | None: + """The database record stored at path, from an index built once per db. + + A scan of db['files'] on every call was O(calls x 19 000 files) on the + path verify --all and slots.py both take. + """ + files = db.get("files", {}) + cached = _PATH_INDEX.get(id(files)) + if cached is None or cached[0] is not files: + cached = (files, {e.get("path"): e for e in files.values()}) + _PATH_INDEX[id(files)] = cached + return cached[1].get(path) + + +_PATH_INDEX: dict[int, tuple[dict, dict[str, dict]]] = {} + + +def _content_sha1(path: str, db: dict) -> str | None: + """The sha1 of the file at path, from the database or read from disk. + + A data directory cache is not in the database, so its files are hashed. + """ + record = _record_at(path, db) + if record is not None: + return record.get("sha1") + if not os.path.isfile(path): + return None + return compute_hashes(path, frozenset({"sha1"}))["sha1"] + + +def _accepted_by_all(path: str, entries: list[dict], db: dict) -> bool: + """Whether every declaration's own hashes accept the file at path.""" + record = _record_at(path, db) + if record is None: + return False + for entry in entries: + if entry.get("zipped_file"): + declared = parse_md5_list(entry.get("md5")) + if declared and not any( + check_inside_zip(path, entry["zipped_file"], m) == "ok" for m in declared + ): + return False + continue + for field_name in ("md5", "sha1", "sha256", "crc32"): + declared = _declared_hashes(entry, field_name) + if declared and str(record.get(field_name, "")).lower() not in declared: + if field_name == "crc32" and _headerless_crc32(path, record, entry) in declared: + continue + return False + return True + + +COPIER_HEADER = 512 + + +def _headerless_crc32(path: str, record: dict, entry: dict) -> str | None: + """The crc32 of a file past its 512-byte copier header, when the entry + declares both the file's size and the size without the header. + + Geargrafx drops the header when the file is 512 bytes over the expected + size and computes the crc32 on the rest (src/media.cpp:754-773). The + profile lists both sizes. EmuELEC's headered syscard3.pce (crc32 + 64f78e3c) is the 6d9a73ef image the profile names. + """ + sizes = entry.get("size") + declared = sizes if isinstance(sizes, list) else [sizes] + size = record.get("size") + if not isinstance(size, int) or not {size, size - COPIER_HEADER} <= set(declared): + return None + try: + with open(path, "rb") as f: + f.seek(COPIER_HEADER) + return f"{zlib.crc32(f.read()):08x}" + except OSError: + return None + + +def _same_file_family(paths: list[str]) -> bool: + """Whether the paths are one file and its own pinned variants. + + A platform list built on an older romset pins bytes the primary no longer + carries, which the repository keeps side by side under .variants. That is + the documented multi-version case, not two machines fighting for a path. + """ + canonical = set() + for path in paths: + if "/.variants/" in path: + directory, _, name = path.rpartition("/") + directory = directory[: -len("/.variants")] + name = variant_base_name(name) + path = f"{directory}/{name}" + canonical.add(path.casefold()) + return len(canonical) == 1 diff --git a/scripts/packresolve.py b/scripts/resolve/packfiles.py similarity index 100% rename from scripts/packresolve.py rename to scripts/resolve/packfiles.py diff --git a/scripts/resolve/review.py b/scripts/resolve/review.py new file mode 100644 index 000000000..a7e32a7c5 --- /dev/null +++ b/scripts/resolve/review.py @@ -0,0 +1,915 @@ +"""Reviewing a contributed file: whether the collection knows it, accepts it, and where in bios/ it goes.""" + +from __future__ import annotations + +import hashlib +import os +import sys +import urllib.parse +import zipfile +from collections.abc import Callable, Iterable +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING, TypedDict + +try: + import yaml +except ImportError: + yaml = None + +from core.hashing import compute_hashes, parse_hash_list, parse_md5_list +from model.nodedup import _in_nodedup_dir +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from model.registry import list_registered_platforms +from resolve.nativemode import digest_algorithm +from resolve.validation import frontend_digest_matches, inner_rom_check + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +BLOCKED_EXTENSIONS = { + ".exe", + ".bat", + ".cmd", + ".sh", + ".ps1", + ".vbs", + ".js", + ".msi", + ".dll", + ".so", + ".dylib", + ".py", + ".rb", + ".pl", +} + +MAX_FILE_SIZE = 100 * 1024 * 1024 +LARGE_FILE_ISSUE_URL = ( + "https://github.com/Abdess/retrobios/issues/new?template=missing-bios.yml" +) + + +def large_file_issue_url(result: ValidationResult) -> str: + """The issue form with the values this run computed already filled in. + + GitHub fills an issue form field from the query parameter named by its + id: filename, sha1, md5 and size in missing-bios.yml. + """ + fields = { + "title": f"[BIOS] Missing: {result.filename}", + "filename": result.filename, + "sha1": result.sha1, + "md5": result.md5, + "size": str(result.size), + } + return f"{LARGE_FILE_ISSUE_URL}&{urllib.parse.urlencode(fields)}" + + +class ValidationResult: + def __init__(self, filepath: str) -> None: + self.filepath = filepath + self.filename = os.path.basename(filepath) + self.checks: list[tuple[str, str]] = [] # (status, message) tuples + self.sha1 = "" + self.md5 = "" + self.crc32 = "" + self.size = 0 + # "held" (a copy of a file the collection has) or "unknown" (no list + # or profile declares it): no check fails, and neither is a file + # the pull request adds to the collection. + self.outcome = "" + # Where --place copies the file: one folder and one declared name, or + # the .variants/ slot of a name the collection already holds. + self.destination = "" + + def add_check(self, passed: bool, message: str) -> None: + self.checks.append(("PASS" if passed else "FAIL", message)) + + def add_warning(self, message: str) -> None: + self.checks.append(("WARN", message)) + + def add_info(self, message: str) -> None: + self.checks.append(("INFO", message)) + + @property + def passed(self) -> bool: + return all(s != "FAIL" for s, _ in self.checks) + + @property + def status(self) -> str: + return "FAIL" if not self.passed else "REVIEW" if self.outcome else "PASS" + + def to_markdown(self) -> str: + status = self.status + lines = [f"### {status} `{self.filename}`"] + lines.append("") + lines.append(f"- **Path**: `{self.filepath}`") + # A path refused before it was read has no size or digest to show: + # empty fields read as an empty file contributed. + if self.sha1: + lines.append(f"- **Size**: {self.size:,} bytes") + lines.append(f"- **SHA1**: `{self.sha1}`") + lines.append(f"- **MD5**: `{self.md5}`") + lines.append(f"- **CRC32**: `{self.crc32}`") + lines.append("") + + for status_str, message in self.checks: + if status_str == "PASS": + lines.append(f"- Pass: {message}") + elif status_str == "FAIL": + lines.append(f"- Fail: {message}") + elif status_str == "WARN": + lines.append(f"- Warning: {message}") + else: + lines.append(f"- Info: {message}") + + return "\n".join(lines) + + +def _note_sizes(sizes: dict[str, list], names: list[str], entry: dict) -> None: + """Record the sizes an entry accepts under each of its names. + + An entry that declares no size says nothing about it, so a name is + judged only by the declarations that do. + """ + size = entry.get("size") + accepted = [] + if isinstance(size, list): + accepted = [(int(v), int(v)) for v in size] + elif isinstance(size, int) and size > 0: + accepted = [(size, size)] + if entry.get("min_size") or entry.get("max_size"): + accepted.append((int(entry.get("min_size") or 0), + int(entry.get("max_size") or 2 ** 63))) + for name in names if accepted else []: + sizes.setdefault(name, []).extend(accepted) + + +def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict: + """Load all known hashes from platform configs. + + With the database, `folders` maps each declared hash to the + bios/// folders the collection files its system + under, read from the other files of that system it holds. + """ + known: dict[str, Any] = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(), + "names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}, + "name_systems": {}, "system_dirs": {}, "system_folders": {}} + systems_of: dict[str, set[str]] = {} + folders_of: dict[str, dict[str, int]] = {} + files = (db or {}).get("files", {}) + by_md5 = (db or {}).get("indexes", {}).get("by_md5", {}) + + if not os.path.isdir(platforms_dir) or yaml is None: + return known + + # Read the way verify reads them: inheritance and shared groups resolved, + # and a Recalbox md5 field split into the revisions it lists. The raw + # file kept "a,b,c" as one value, so a PR adding the seventh accepted + # falcon.img was told its hash differs. + for name in list_registered_platforms(platforms_dir): + try: + config = load_platform_config(name, platforms_dir) + except (OSError, yaml.YAMLError) as exc: + print(f"WARNING: {name}: {exc}", file=sys.stderr) + continue + + mode, rule = config.get("verification_mode"), config.get("hash_rule", "") + for system_id, system in config.get("systems", {}).items(): + for file_entry in system.get("files", []): + sha1s = parse_hash_list(file_entry.get("sha1")) + md5s = parse_md5_list(file_entry.get("md5")) + sha256s = parse_hash_list(file_entry.get("sha256")) + known["sha1"].update(sha1s) + known["md5"].update(md5s) + known["sha256"].update(sha256s) + if not (sha1s or md5s or sha256s) and isinstance(file_entry.get("size"), int): + # The resolver's reading: a crc32 counts where no stronger + # hash is declared, bounded by the declared size. + known["crc32"].update( + (crc.zfill(8), file_entry["size"]) + for crc in parse_hash_list(file_entry.get("crc32")) + ) + if "name" in file_entry: + known["names"].add(file_entry["name"]) + _note_sizes(known["sizes"], [file_entry["name"]], file_entry) + # A frontend that hashes a ZIP's member or its members + # together, or that takes any hash at the declared size, + # answers by its own rule, read per entry. + known["entries"].setdefault(file_entry["name"].lower(), []).append( + (file_entry, mode, rule, name) + ) + known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id) + for value in (*sha1s, *md5s): + systems_of.setdefault(value, set()).add(system_id) + for value in (*sha1s, *md5s, *sha256s): + if "name" in file_entry: + known["named"].setdefault(value, set()).add(file_entry["name"]) + _note_folder(folders_of, system_id, files, by_md5, sha1s, md5s, + known["system_dirs"]) + + known["folders"] = _system_homes(systems_of, folders_of) + known["system_folders"] = _single_maker_folders(folders_of) + return known + + +def _note_folder( + folders_of: dict[str, dict[str, int]], system_id: str, files: dict, + by_md5: dict, sha1s: list[str], md5s: list[str], + dirs_of: dict[str, set[str]] | None = None, +) -> None: + """Count the bios/// folder a held file sits in, + and note the directory it sits in under *dirs_of*.""" + held = next((s for s in sha1s if s in files), None) or next( + (by_md5[m] for m in md5s if m in by_md5), None + ) + path = str(files.get(held, {}).get("path", "")) + if dirs_of is not None and "/" in path and "/.variants/" not in path: + dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/") + parts = path.split("/") + if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."): + folder = "/".join(parts[:3]) + "/" + counts = folders_of.setdefault(system_id, {}) + counts[folder] = counts.get(folder, 0) + 1 + + +def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]: + """System id to the folders the collection files it under, for a system + filed under one manufacturer only, the rule _system_homes applies.""" + return { + system_id: set(held_in) for system_id, held_in in folders_of.items() + if len({folder.split("/")[1] for folder in held_in}) == 1 + } + + +def _system_homes( + systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]] +) -> dict[str, set[str]]: + """Hash value to the folders the collection files its systems under. + + A system whose files sit under several manufacturers (arcade sets, + computers sharing ROM chips) names no single home: only a system filed + under one manufacturer says where a newcomer belongs. + """ + homes: dict[str, set[str]] = {} + for value, systems in systems_of.items(): + folders: set[str] = set() + for system_id in systems: + held_in = folders_of.get(system_id, {}) + if len({folder.split("/")[1] for folder in held_in}) == 1: + folders.update(held_in) + if folders: + homes[value] = folders + return homes + + +def load_profile_hashes( + emulators_dir: str, db: dict | None = None +) -> dict[str, dict[str, set[str]]]: + """Hash value to the emulators whose profile declares it, per algorithm. + + A file only a core reads (a standalone emulator's firmware, a game + engine's data) is in no platform list: the review called every such + contribution "not referenced, needs manual review". With the database, + `folders` maps each declared hash to the folders the collection files + the entry's system under, as load_platform_hashes does: a contributor + holding a file only a profile declares was told to pick a + bios/Manufacturer/Console/ folder alone. + """ + known: dict[str, dict] = { + "sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {}, + "named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {}, + } + systems_of: dict[str, set[str]] = {} + folders_of: dict[str, dict[str, int]] = {} + files = (db or {}).get("files", {}) + indexes = (db or {}).get("indexes", {}) + by_md5, by_sha256 = indexes.get("by_md5", {}), indexes.get("by_sha256", {}) + for emulator, profile in load_emulator_profiles(emulators_dir).items(): + declared_systems = profile.get("systems") or [] + for entry in profile.get("files") or []: + if not isinstance(entry, dict): + continue + names = [entry.get("name"), *(entry.get("aliases") or [])] + _note_sizes(known["sizes"], [n for n in names if isinstance(n, str)], entry) + # The resolver's reading: comma lists split (mesence's four + # sha256), and a crc32 counts only where no stronger hash is + # declared, bounded by the declared size (626 entries name a + # file by crc32 alone, clk's Electron os.rom among them). + hashes = { + algo: parse_hash_list(entry.get(algo)) for algo in ("sha1", "sha256", "md5") + } + for algo, values in hashes.items(): + for value in values: + known[algo].setdefault(value, set()).add(emulator) + if isinstance(entry.get("name"), str): + known["named"].setdefault(value, set()).add(entry["name"]) + # The entry's own system, or the profile's when it emulates one. + system = entry.get("system") or ( + declared_systems[0] if len(declared_systems) == 1 else None + ) + if isinstance(system, str): + for value in (v for values in hashes.values() for v in values): + systems_of.setdefault(value, set()).add(system) + for n in names: + if isinstance(n, str): + known["name_systems"].setdefault(n.lower(), set()).add(system) + sha1s = [*hashes["sha1"], *( + by_sha256[v] for v in hashes["sha256"] if v in by_sha256 + )] + _note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"], + known["system_dirs"]) + if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")): + size = entry.get("size") + sizes = [int(v) for v in size] if isinstance(size, list) else ( + [int(size)] if size else [None] + ) + for value in parse_hash_list(entry.get("crc32")): + for accepted in sizes: + key = (value.zfill(8), accepted) + known["crc32"].setdefault(key, set()).add(emulator) + known["folders"] = _system_homes(systems_of, folders_of) + known["system_folders"] = _single_maker_folders(folders_of) + return known + + +def _archive_members( + filepath: str, db: dict | None, platform_hashes: dict, profile_hashes: dict +) -> list[str] | None: + """What each file of a ZIP is, None when filepath is not a ZIP. + + Read only for an archive no list declares as a whole: MAME and FBNeo + sets are ZIP BIOS files in their own right. + """ + if not zipfile.is_zipfile(filepath): + return None + held = (db or {}).get("files", {}) + described = [] + try: + with zipfile.ZipFile(filepath) as archive: + for info in archive.infolist(): + if info.is_dir(): + continue + if info.file_size > MAX_FILE_SIZE: + described.append(f"`{info.filename}` too large to read here") + continue + sha1, md5 = hashlib.sha1(), hashlib.md5() + with archive.open(info) as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + sha1.update(chunk) + md5.update(chunk) + sha1_hex, md5_hex = sha1.hexdigest(), md5.hexdigest() + crc = f"{info.CRC:08x}" + if sha1_hex in held: + state = f"already held at `{held[sha1_hex]['path']}`" + elif ( + sha1_hex in platform_hashes.get("sha1", set()) + or md5_hex in platform_hashes.get("md5", set()) + or (crc, info.file_size) in platform_hashes.get("crc32", set()) + or profile_hashes.get("sha1", {}).get(sha1_hex) + or profile_hashes.get("md5", {}).get(md5_hex) + or profile_hashes.get("crc32", {}).get((crc, info.file_size)) + ): + state = "declared and not held" + else: + state = "not recognised" + described.append(f"`{info.filename}` {state}") + except (zipfile.BadZipFile, RuntimeError, OSError) as exc: + # An encrypted member raises RuntimeError. + described.append(f"unreadable ({exc})") + return described + + +@dataclass(frozen=True) +class _Review: + """One file under review and the tables it is read against.""" + + filepath: str + db: dict | None + platform_hashes: dict + profile_hashes: dict + + +@dataclass(frozen=True) +class _Known: + """What declares the file: a platform's hash, its own check, a profile, its name.""" + + sha1: bool + md5: bool + other: bool + accepted_by: set[str] + by_profile: set[str] | None + name: bool + + @property + def by_platform(self) -> bool: + return bool(self.sha1 or self.md5 or self.other or self.accepted_by) + + +def _path_problem(filepath: str) -> str: + """Why the path cannot be reviewed, empty when it can.""" + # Whoever opened the pull request chose this path, so its shape is + # settled before anything is read. A symlink to an endless device would + # otherwise be hashed until the job timed out, and a symlink out of the + # checkout would be reported as though its target had been contributed. + if os.path.islink(filepath): + return "Symlinks are not allowed" + if not os.path.exists(filepath): + return (f"File not found: {filepath}. A path is read from the folder " + "the command runs in, or pass --changed to check the files " + "changed under bios/") + if os.path.isdir(filepath): + return "Folder with no file in it" + if not os.path.isfile(filepath): + return "Not a regular file: a device, a pipe or a socket" + return "" + + +def _check_size(result: ValidationResult) -> bool: + """The size checks, True when the file is too large for git.""" + too_large = result.size > MAX_FILE_SIZE + if too_large: + # GitHub refuses a pushed file over 100 MiB, so a pull request cannot + # carry it. Only a maintainer can add an asset to the release. + result.add_check( + False, + f"File too large for git ({result.size:,} > {MAX_FILE_SIZE:,} bytes). " + "Leave it out of the pull request and open an issue, its hashes " + f"filled in ({large_file_issue_url(result)}), saying where the file " + "can be obtained: a maintainer adds it to the `large-files` release.", + ) + elif result.size == 0: + result.add_check(False, "File is empty (0 bytes)") + else: + result.add_check(True, f"File size within limits ({result.size:,} bytes)") + return too_large + + +def _relative_path(filepath: str) -> str: + # Paths are compared as the database writes them, relative to the + # checkout: an absolute path to the file itself read as its duplicate. + if os.path.isabs(filepath): + candidate = os.path.relpath(filepath, os.getcwd()) + if not candidate.startswith(".."): + return candidate + return filepath + + +def _check_duplicate(result: ValidationResult, db: dict, relative: str) -> None: + if result.sha1 not in db.get("files", {}): + result.add_check(True, "Not a duplicate in database") + return + existing = db["files"][result.sha1] + held_at = { + os.path.normpath(p) + for p in [existing.get("path"), *(existing.get("paths") or [])] if p + } + if os.path.normpath(relative) in held_at: + # The file the database was built from, not a copy of it: a + # PR that regenerated database.json was told each new file + # duplicated itself. + result.add_check(True, "Already in the database at this path") + elif _in_nodedup_dir(relative): + result.add_info( + f"Identical to `{existing['path']}`, kept: this tree is read by path" + ) + else: + result.outcome = "held" + result.add_warning( + f"Already held at `{existing['path']}`: nothing to add, " + "leave this copy out of the pull request" + ) + + +def _identify(review: _Review, result: ValidationResult, sha256: str) -> _Known: + platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes + sha1_known = result.sha1 in platform_hashes.get("sha1", set()) + md5_known = result.md5 in platform_hashes.get("md5", set()) + other_known = ( + sha256 in platform_hashes.get("sha256", set()) + or (result.crc32, result.size) in platform_hashes.get("crc32", set()) + ) + accepted_by = ( + set() if sha1_known or md5_known or other_known + else _platforms_accepting(review.filepath, result.filename, platform_hashes) + ) + by_profile = ( + profile_hashes.get("sha1", {}).get(result.sha1) + or profile_hashes.get("sha256", {}).get(sha256) + or profile_hashes.get("md5", {}).get(result.md5) + or profile_hashes.get("crc32", {}).get((result.crc32, result.size)) + or profile_hashes.get("crc32", {}).get((result.crc32, None)) + ) + return _Known(sha1_known, md5_known, other_known, accepted_by, by_profile, + result.filename in platform_hashes.get("names", set())) + + +def _check_executable(result: ValidationResult, sha256: str, profile_hashes: dict, ext: str) -> None: + # An executable is refused unless an emulator profile pins its exact + # bytes: PICO-8's pico8.exe and SDL2.dll are declared by sha1 from the + # official archive. A weak hash (md5, crc32) never vouches for code. + pinned = ( + profile_hashes.get("sha1", {}).get(result.sha1) + or profile_hashes.get("sha256", {}).get(sha256) + ) + if pinned: + result.add_check( + True, + f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}", + ) + else: + result.add_check(False, f"Blocked file extension: {ext}") + + +def _check_known(review: _Review, result: ValidationResult, known: _Known, too_large: bool) -> list[str] | None: + """What declares the file, and the files of a ZIP no list declares + whole, when the upload is one.""" + if known.sha1: + result.add_check(True, "SHA1 matches known platform requirement") + elif known.md5: + result.add_check(True, "MD5 matches known platform requirement") + elif known.other: + result.add_check(True, "Hash matches known platform requirement") + elif known.accepted_by: + result.add_check( + True, "Accepted by the platform's own check: " + ", ".join(sorted(known.accepted_by)) + ) + elif known.by_profile: + names = sorted(known.by_profile) + shown = ", ".join(names[:5]) + (f" and {len(names) - 5} more" if len(names) > 5 else "") + result.add_check(True, f"Hash matches a file the emulator profile declares: {shown}") + elif known.name: + result.add_warning( + "Filename matches a known requirement but hash differs - may be a variant" + ) + else: + result.outcome = "unknown" + members = None if too_large else _archive_members( + review.filepath, review.db, review.platform_hashes, review.profile_hashes + ) + _report_unknown(result, members, too_large) + return members + return None + + +def _report_unknown(result: ValidationResult, members: list[str] | None, too_large: bool) -> None: + if members is not None: + # A folder zipped to upload many files at once was hashed as one + # file and its contributor asked where that dump came from. + shown = "; ".join(members[:10]) + ( + f"; and {len(members) - 10} more" if len(members) > 10 else "" + ) + result.add_warning( + "A ZIP no platform list or emulator profile declares as a whole: " + "add the files it holds, unzipped, not the archive. Inside: " + + (shown or "nothing") + ) + else: + result.add_warning( + "Not recognised: no platform list or emulator profile declares this " + f"file. Say in the {'issue' if too_large else 'pull request'} which " + "emulator reads it, for which system, and where the dump comes from" + ) + + +def _check_bios_placement(result: ValidationResult, normalized: str, expected: list[str]) -> None: + parts = normalized.split(os.sep) + here = f"bios/{parts[1]}/{parts[2]}/" if len(parts) >= 4 else "" + makers = {folder.split("/")[1] for folder in expected} + if expected and (len(parts) < 4 or parts[1] not in makers): + # Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/. + result.add_warning( + "Placed under " + (here or "the bios/ root") + ", while the other files of " + "its system are in " + " or ".join(f"`{f}`" for f in expected) + ) + elif len(parts) >= 4: + result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/") + else: + result.add_warning("File should be in bios/Manufacturer/Console/ structure") + + +def _suggest_destination(review: _Review, result: ValidationResult, values: tuple[str, ...], + known: _Known) -> None: + # The contributor asks before forking: say where it goes. + spot = placement( + values, result.filename, review.db, review.platform_hashes, review.profile_hashes, + declared=bool(known.by_platform or known.by_profile), + ) + result.destination = spot.destination(result.sha1) + copies = f". --place copies it to `{result.destination}`" if result.destination else "" + if spot.folders: + result.add_warning( + "File is not under bios/ yet. Its system's files are in " + + " or ".join(f"`{f}`" for f in spot.folders) + copies + ) + elif spot.home: + result.add_warning( + f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`" + + copies + ) + else: + result.add_warning( + "File is not under bios/ yet. Place it in bios/Manufacturer/Console/" + ) + + +def _check_declared_size(result: ValidationResult, platform_hashes: dict, profile_hashes: dict) -> bool: + """True when the size fits every declaration of the name.""" + declared = [ + *platform_hashes.get("sizes", {}).get(result.filename, []), + *profile_hashes.get("sizes", {}).get(result.filename, []), + ] + size_fits = not declared or any(lo <= result.size <= hi for lo, hi in declared) + if not size_fits: + expected = sorted({lo if lo == hi else f"{lo:,} to {hi:,}" for lo, hi in declared}, + key=str) + shown = ", ".join(f"{v:,}" if isinstance(v, int) else v for v in expected) + result.add_warning( + f"Every declaration of {result.filename} expects {shown} bytes, " + f"this file has {result.size:,}: truncated or another file" + ) + return size_fits + + +def _note_variant(review: _Review, result: ValidationResult, normalized: str) -> None: + platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes + owners = name_systems(result.filename, platform_hashes, profile_hashes) + home = _variant_home(review.db, result.filename, "", set() if len(owners) > 1 else { + d for table in (platform_hashes, profile_hashes) for s in owners + for d in table.get("system_dirs", {}).get(s, ()) + } if owners else None) + if not home and normalized.startswith("bios" + os.sep): + # Beside the file, in the folder the contributor chose. + home = os.path.dirname(normalized).replace(os.sep, "/") + "/" + slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}" + if home and not normalized.startswith("bios" + os.sep): + result.destination = slot + if home: + result.add_info( + f"This may be a valid variant. If accepted, it will be placed in `{slot}`" + ) + else: + result.add_info("This may be a valid variant of a file the collection lacks") + + +def validate_file( + filepath: str, + db: dict | None, + platform_hashes: dict, + profile_hashes: dict | None = None, +) -> ValidationResult: + """Run all validation checks on a file.""" + result = ValidationResult(filepath) + problem = _path_problem(filepath) + if problem: + result.add_check(False, problem) + return result + + result.size = os.path.getsize(filepath) + hashes = compute_hashes(filepath) + result.sha1 = hashes["sha1"] + result.md5 = hashes["md5"] + result.crc32 = hashes["crc32"] + sha256 = hashes.get("sha256", "") + + ext = os.path.splitext(filepath)[1].lower() + too_large = _check_size(result) + relative = _relative_path(filepath) + if db: + _check_duplicate(result, db, relative) + + review = _Review(filepath, db, platform_hashes, profile_hashes or {}) + known = _identify(review, result, sha256) + if ext in BLOCKED_EXTENSIONS: + _check_executable(result, sha256, review.profile_hashes, ext) + members = _check_known(review, result, known, too_large) + + normalized = os.path.normpath(relative) + values = (result.sha1, result.md5, sha256) + if too_large: + # The file stays out of the pull request, so no folder of bios/ is + # the contributor's to choose: the release asset is placed by hand. + pass + elif normalized.startswith("bios" + os.sep): + _check_bios_placement(result, normalized, + expected_folders(values, platform_hashes, review.profile_hashes)) + elif result.outcome == "held" or members is not None: + # Nothing to place: a copy, or an archive whose files go in unzipped. + pass + else: + _suggest_destination(review, result, values, known) + + size_fits = _check_declared_size(result, platform_hashes, review.profile_hashes) + if known.name and not known.by_platform and not known.by_profile and size_fits: + _note_variant(review, result, normalized) + return result + + +def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) -> set[str]: + """Platforms whose declaration of this name accepts the file by their + own check, as verify and the pack builder read it. + + Batocera pins a ROM inside the ZIP (zipped_file), Recalbox hashes a + ZIP's members together, RomM takes any hash at the declared size: the + container's sha1 or md5 is in none of those lists, and adam_fdc.zip, + which Batocera accepts, was called an unknown variant. + """ + accepted: set[str] = set() + for entry, mode, rule, platform in platform_hashes.get("entries", {}).get( + filename.lower(), [] + ): + if platform in accepted: + continue + if entry.get("zipped_file"): + ok = inner_rom_check(entry, filepath) == "ok" + else: + algorithm = digest_algorithm(mode) + ok = bool(algorithm or rule) and frontend_digest_matches( + entry, filepath, algorithm or "", rule + ) + if ok: + accepted.add(platform) + return accepted + + +def expected_folders( + values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None +) -> list[str]: + """The bios/// folders the files of a hash's + system are in, read from the first of *values* a table knows. + + A platform's declaration first, then a profile's: most files the gaps + page lists are declared by a profile alone. + """ + for table in (platform_hashes, profile_hashes or {}): + for value in values: + if value and value in table.get("folders", {}): + return sorted(table["folders"][value]) + return [] + + +@dataclass(frozen=True) +class Placement: + """Where a file not under bios/ yet goes. + + ``folders`` are those of its system, ``home`` the folder the collection + keeps its name in when its system names none. ``name`` is the name it + is copied under, empty when the declarations do not settle one. + ``variant`` says a file of that name is already in the folder: a copy + goes beside it in .variants/, never over it. + """ + + folders: tuple[str, ...] = () + home: str = "" + name: str = "" + variant: bool = False + + @property + def folder(self) -> str: + return self.folders[0] if self.folders else self.home + + def destination(self, sha1: str) -> str: + if not self.name: + return "" + if self.variant: + return f"{self.folder}.variants/{self.name}.{sha1[:8]}" + return self.folder + self.name + + +class PlacementOptions(TypedDict, total=False): + """How placement() tests a path, and the systems and directory a + declaration names.""" + + exists: Callable[[str], bool] + systems: Iterable[str] + directory: str + + +def placement( + values: Iterable[str], + filename: str, + db: dict | None, + platform_hashes: dict, + profile_hashes: dict | None, + *, + declared: bool, + **options: Unpack[PlacementOptions], +) -> Placement: + """Where a file goes, by its hashes and its name. + + The review and the site's wanted page both read this one rule, so the + folder a contributor is sent to is the folder the review accepts. + *declared* says a list or a profile declares one of the hashes: a file + known by its name alone gets a slot only once its size fits. + + Without a folder from its hashes, the folder comes from its system: + *systems*, or every system that declares the name (several of them + name no copy to sit beside). A file of that name held elsewhere is a + homonym and says nothing: AmberELEC's MSX config.ini + was sent beside msx.emu's ColecoVision config.ini. A declared + *directory* (Machines/MSX2/ for one machine's config.ini) narrows it: a + copy by name counts only in a directory of that tail, and a held + directory of that tail is the folder. + """ + exists = options.get("exists", os.path.exists) + systems = options.get("systems", ()) + directory = options.get("directory", "") + values = [value for value in values if value] + folders = expected_folders(values, platform_hashes, profile_hashes) + if folders: + names = { + name + for table in (platform_hashes, profile_hashes or {}) + for value in values + for name in table.get("named", {}).get(value, ()) + } + name = next(iter(names)) if len(names) == 1 else "" + if len(folders) == 1 and name and "/" not in name: + return Placement(tuple(folders), name=name, variant=exists(folders[0] + name)) + return Placement(tuple(folders)) + held = next((value for value in values if value in (db or {}).get("files", {})), "") + owners = set(systems) or name_systems(filename, platform_hashes, profile_hashes) + tables = (platform_hashes, profile_hashes or {}) + # A name several systems declare does not say which one a file is: + # a copy held for one of them is no answer. + dirs: set[str] = set() if not systems and len(owners) > 1 else { + d for table in tables for s in owners for d in table.get("system_dirs", {}).get(s, ()) + } + tail = _directory_tail(db, directory) + within: set[str] | None = dirs + if tail: + within = {d for d in dirs if d.endswith("/" + tail) or d == tail} if owners else None + home = _variant_home(db, filename, held, within if owners or tail else None) + if declared and home and filename and "/" not in filename: + # The folder holds a file of that name already. + return Placement(home=home, name=filename, variant=True) + if home: + return Placement(home=home) + if tail: + return Placement(home=next(d for d in _held_directories(db) if d.endswith("/" + tail) or d == tail)) + homes = {f for table in tables for s in owners for f in table.get("system_folders", {}).get(s, ())} + return Placement(tuple(sorted(homes))) + + +_HELD_DIRECTORIES: dict[int, frozenset[str]] = {} + + +def _held_directories(db: dict | None) -> frozenset[str]: + """Every directory a file of the database sits in, .variants/ aside.""" + key = id(db) + if key not in _HELD_DIRECTORIES: + _HELD_DIRECTORIES[key] = frozenset( + path.rsplit("/", 1)[0] + "/" + for record in (db or {}).get("files", {}).values() + for path in [record.get("path"), *(record.get("paths") or [])] + if path and "/" in path and "/.variants/" not in path + ) + return _HELD_DIRECTORIES[key] + + +def _directory_tail(db: dict | None, directory: str) -> str: + """The longest tail of a declared directory, two segments at least, + that exactly one held directory ends with, empty when none does.""" + parts = [p for p in directory.strip("/").split("/") if p] + held = _held_directories(db) + for size in range(len(parts), 1, -1): + tail = "/".join(parts[-size:]) + "/" + found = [d for d in held if d.endswith("/" + tail) or d == tail] + if len(found) == 1: + return tail + if found: + return "" + return "" + + +def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]: + """The systems whose platform or profile entries declare this name.""" + return { + system for table in (platform_hashes, profile_hashes or {}) + for system in table.get("name_systems", {}).get(filename.lower(), ()) + } + + +def _variant_home(db: dict | None, name: str, held: str = "", + within: set[str] | None = None) -> str: + """The folder the collection keeps a name in, for its variants beside it. + + The folder of an identical copy comes first: adam_fdc.zip, held in + bios/Coleco/Adam/, was sent to bios/Arcade/MAME/, the first folder + the name index gave. A copy found by name alone counts only in a + directory of *within*, those the file's own systems are held in, when + the systems are known. + """ + files = (db or {}).get("files", {}) + by_name = (db or {}).get("indexes", {}).get("by_name", {}).get(name, []) + copies = [(held, True)] if held in files else [] + for sha1, identical in copies + [(sha1, False) for sha1 in by_name]: + path = str(files.get(sha1, {}).get("path", "")) + folder = path.rsplit("/", 1)[0] + "/" if "/" in path else "" + if not folder or "/.variants" in "/" + folder: + continue + if identical or within is None or folder in within: + return folder + return "" diff --git a/scripts/sitewanted.py b/scripts/sitewanted.py index 371ab7b7d..2f70f01e6 100644 --- a/scripts/sitewanted.py +++ b/scripts/sitewanted.py @@ -24,9 +24,9 @@ from pathlib import Path import archive_build from resolve.layout import runs_standalone from model.profiles import unique_emulator_profiles -from cross_reference import _first_hash +from packs.crossref import _first_hash from core.hashing import cut_md5_owner, parse_hash_list -from validate_pr import LARGE_FILE_ISSUE_URL, Placement, placement +from resolve.review import LARGE_FILE_ISSUE_URL, Placement, placement from resolve.validation import deliverable, filter_files_by_mode, installed_with_emulator ALGORITHMS = ("sha1", "sha256", "md5", "crc32") diff --git a/scripts/slots.py b/scripts/slots.py index 0a188df9f..a8385c6b3 100644 --- a/scripts/slots.py +++ b/scripts/slots.py @@ -19,620 +19,22 @@ feeds the report this module prints. from __future__ import annotations -import os -import zlib -from dataclasses import dataclass, field from typing import TYPE_CHECKING -from resolve import nativemode -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 core.ziptools import build_zip_contents_index +from model.profiles import 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, - outside_gap_scope, - read_from_save_dir, - with_archive_members, -) +from resolve.localfile import resolution_is_hash_exact +from resolve.standalone import standalone_set as platform_standalone_set if TYPE_CHECKING: - from packextras import ExtraPlacement - -# A profile entry can prove a slot without declaring a hash: Dolphin names no -# checksum for the GameCube boot ROM because its source names none, and the -# proof is then the path the repository stores the file at. -# A profile entry that names an exact size, for a file the code reads in -# full (no hash to declare), is proven by a held copy of that size: the -# platform's xmil/IPLROM.X1T pinned the 2 KiB X1 font where xmil reads a -# 32 KiB Turbo IPL, and a name-only claim could not contest it. -SIZE_EXACT = "size_exact" -PROVEN_STATUSES = frozenset({"path_exact", "members_held", SIZE_EXACT}) - - -def _size_the_code_reads(entry: dict, local: str | None) -> bool: - """Whether a name-resolved copy has the exact size the entry declares.""" - size = entry.get("size") - if not local or not isinstance(size, int) or size <= 0: - return False - try: - return os.path.getsize(local) == size - except OSError: - return False - - -# A core that reads ROMs inside an archive proves the archive by its members: -# FBNeo's neocdz.zip is any copy holding neocd.bin and 000-lo.lo by crc. -MEMBERS_HELD = "members_held" - - -@dataclass -class Claim: - """One layer's answer to what belongs at a destination.""" - - origin: str - destination: str - name: str - emulator: str = "" - entry: dict = field(default_factory=dict) - local_path: str | None = None - status: str = "" - # A core that identifies its firmware by content reads no file by this - # name: any dump it takes for the same system and region answers for it. - accepts: tuple[dict, ...] = () - - @property - def is_proven(self) -> bool: - """Whether the claim rests on evidence rather than on a bare name.""" - return resolution_is_hash_exact(self.status) or self.status in PROVEN_STATUSES - - -@dataclass -class Conflict: - """Two proven claims on one destination that resolve to different files.""" - - destination: str - platform_claim: Claim - profile_claims: list[Claim] - - @property - def emulators(self) -> list[str]: - return sorted({c.emulator for c in self.profile_claims if c.emulator}) - - def files_read(self) -> list[tuple[str | None, list[str], str]]: - """Each file the profiles want here, with the emulators reading it - and the proof of the first claim on it. - - One file stood for every claim: Recalbox's neocdz.zip line gave - geolith the archive fbneo reads, not the one geolith pins. - """ - files: dict[str | None, tuple[list[str], str]] = {} - for claim in self.profile_claims: - emulators, status = files.setdefault(claim.local_path, ([], claim.status)) - if claim.emulator and claim.emulator not in emulators: - emulators.append(claim.emulator) - return [(path, sorted(emus), status) for path, (emus, status) in files.items()] - - -def _normalize(destination: str, fold: bool = True) -> str: - """Comparable form of a destination, since layers write it differently. - - Case is folded only where the platform's filesystem folds it: on Linux - RetroDECK ships bios/DISK.ROM and bios/disk.rom side by side. - """ - cleaned = destination.strip().strip("/").replace("\\", "/") - return cleaned.casefold() if fold else cleaned - - -def platform_claims( - config: dict, - db: dict, - base_dest: str = "", - zip_contents: dict | None = None, - data_dir_registry: dict | None = None, -) -> list[Claim]: - """What the platform YAML says belongs at each of its destinations.""" - claims: list[Claim] = [] - for system in (config.get("systems") or {}).values(): - for entry in system.get("files") or []: - if not isinstance(entry, dict): - continue - dest = entry.get("destination") or entry.get("name") or "" - if not dest: - continue - full = f"{base_dest}/{dest}" if base_dest else dest - local, status = resolve_local_file( - entry, - db, - zip_contents, - dest_hint=dest, - data_dir_registry=data_dir_registry, - ) - claims.append( - Claim( - origin="platform", - destination=full, - name=entry.get("name", ""), - entry=entry, - local_path=local, - status=status, - ) - ) - return claims - - -def profile_claims( - profiles: dict, - db: dict, - base_dest: str = "", - standalone_cores: set[str] | None = None, - zip_contents: dict | None = None, - data_dir_registry: dict | None = None, - config: dict | None = None, -) -> list[Claim]: - """What each emulator profile says belongs at each destination it names. - - With the platform's config, a claim sits where the pack puts the core's - file (ExtraPlacement): under RetroDECK's bios/, under RomM's system - folder. A file the platform cannot place claims nothing. - - A file can exist in one build of an emulator and not the other, and the - two builds read from different directories. The mode is decided per - emulator, not per pack: a platform runs some of its emulators as libretro - cores and others standalone, naming the latter in ``standalone_cores``. - An entry the standalone build alone loads does not address a platform - running that emulator as a core, and where it does, the destination is - ``standalone_path``. This is the gate verify already applies. - """ - standalone_cores = standalone_cores or set() - placement = None - if config is not None: - from packextras import ExtraPlacement - - placement = ExtraPlacement(config, base_dest, profiles) - claims: list[Claim] = [] - for emu_name, profile in sorted(profiles.items()): - if profile.get("type") in ("launcher", "alias"): - continue - # The gap report skips a filename-agnostic profile whole: the builder - # carries its scan candidates, never its named entries. - if profile.get("bios_mode") == "agnostic": - continue - for layout, is_standalone in platform_layouts(emu_name, profile, standalone_cores): - claims.extend( - _archive_claims( - emu_name, layout, is_standalone, db, base_dest, placement, - zip_contents, data_dir_registry, - ) - ) - for entry in layout.get("files") or []: - if not isinstance(entry, dict): - continue - # The same rule as the gap report and the builder: an entry the - # pack never carries (a placeholder, a filename-agnostic scan) - # arbitrates nothing. One read below the save directory sits - # outside the BIOS tree, where no platform declares a file. - if outside_gap_scope(entry, is_standalone) or read_from_save_dir( - entry, is_standalone - ) or entry.get("unplaced"): - continue - # A member of a romset is not a file at the BIOS root: the archive - # holding it occupies the destination (_archive_claims). Claiming - # the member put FBNeo's msx.zip contents loose at the root. - if entry.get("archive"): - continue - dest = ( - (entry.get("standalone_path") or entry.get("path")) - if is_standalone - else system_dir_path(entry, entry.get("path") or entry.get("name") or "") - ) or entry.get("name") or "" - if not dest: - continue - if placement is None: - full = f"{base_dest}/{dest}" if base_dest else dest - else: - placed = placement.place( - { - "profile": emu_name, - "system": entry.get("system"), - "systems": entry_system_ids(entry, layout), - }, - dest, - ) - if placed is None: - continue - full = placed[1] - # The owner's own copy is the one the builder ships. - local, status = resolve_local_file( - { - **with_archive_members(entry, layout.get("files") or []), - "source_profile": emu_name, - }, - db, - zip_contents, - dest_hint=dest, - data_dir_registry=data_dir_registry, - ) - if status == "name_exact" and _size_the_code_reads(entry, local): - status = SIZE_EXACT - accepts = tuple(content_alternatives(entry, layout)) - claims.append( - Claim( - origin="profile", - destination=full, - name=entry.get("name", ""), - emulator=emu_name, - entry=entry, - local_path=local, - status=status, - accepts=accepts, - ) - ) - return claims - - -def _archive_claims( - emu_name: str, - profile: dict, - is_standalone: bool, - db: dict, - base_dest: str, - placement: ExtraPlacement | None, - zip_contents: dict | None, - data_dir_registry: dict | None, -) -> list[Claim]: - """The archives a core reads its ROMs from, where the builder places them. - - The archive sits at the root and, for a core that reads a directory of - its own (archive_prefix), under it as well. The claim is proven when the - copy holds every member the core requires. - """ - files = [ - entry for entry in profile.get("files") or [] - if isinstance(entry, dict) - and not outside_gap_scope(entry, is_standalone) - and not read_from_save_dir(entry, is_standalone) - and not entry.get("unplaced") - ] - prefix = profile.get("archive_prefix", "") - claims: list[Claim] = [] - for archive in sorted({entry["archive"] for entry in files if entry.get("archive")}): - entry = archive_entry(archive, files) - members = entry.get("members") - if not members: - continue - member = next(f for f in files if f.get("archive") == archive) - system = member.get("system") - if member.get("system_dir"): - entry = {**entry, "system_dir": member["system_dir"]} - root = system_dir_path(entry, archive) - for dest in (root, f"{prefix}/{archive}") if prefix else (root,): - if placement is None: - full = f"{base_dest}/{dest}" if base_dest else dest - else: - placed = placement.place({"profile": emu_name, "system": system}, dest) - if placed is None: - continue - full = placed[1] - local, status = resolve_local_file( - {**entry, "source_profile": emu_name}, - db, - zip_contents, - dest_hint=dest, - data_dir_registry=data_dir_registry, - ) - if ( - local - and not resolution_is_hash_exact(status) - and holds_required_members(local, members) - ): - status = MEMBERS_HELD - claims.append( - Claim( - origin="profile", - destination=full, - name=archive, - emulator=emu_name, - entry=entry, - local_path=local, - status=status, - ) - ) - return claims - - -def checked_by_path(mode: str, entry: dict, rule: str = "") -> bool: - """Whether the frontend checks this declaration by its path alone. - - Whether a frontend reads the bytes is a property of the platform, but - what it compares them with is the entry's: Batocera skips an empty md5 - (batocera-systems:1088), and EmuDeck declares neocdz.zip with no hash at - all. Such an entry is a path, in an md5 platform as in an existence one. - A member pinned inside an archive is content. - """ - if not nativemode.reads_file_contents(mode): - return True - if entry.get("zipped_file"): - return False - if rule == nativemode.SIZE_AND_ANY_HASH: - fields: tuple[str, ...] = ("md5", "sha1", "crc32") - else: - fields = (nativemode.digest_algorithm(mode) or "",) - return not any( - parse_md5_list(entry.get(name)) if name == "md5" else entry.get(name) - for name in fields - ) - - -def _claim_rank(claim: Claim) -> int: - """How strongly a platform claim speaks for what the pack ships.""" - if resolution_is_hash_exact(claim.status): - return 2 - return 1 if claim.is_proven else 0 - - -def _slot_claims( - config: dict, - profiles: dict, - db: dict, - base_dest: str, - standalone_cores: set[str] | None, - zip_contents: dict | None, - data_dir_registry: dict | None, -) -> tuple[dict[str, Claim], dict[str, list[Claim]]]: - """The platform claim and the proven profile claims at each destination.""" - fold = bool(config.get("case_insensitive_fs", False)) - # The builder's own choice among declarations sharing a destination, - # read from the same function: the most accepting archive for zipped_file - # members, then md5_exact. A rule of its own here compared profiles with - # a file the pack does not ship (Batocera adam_fdc.zip). - shipped = set( - preferred_entries( - config.get("systems") or {}, db, "bios", base_dest, False, - zip_contents, True, - ).values() - ) - by_dest: dict[str, Claim] = {} - for claim in platform_claims( - config, db, base_dest, zip_contents, data_dir_registry - ): - key = _normalize(claim.destination, fold) - held = by_dest.get(key) - if held is not None and id(held.entry) in shipped: - continue - # A bare sibling met first must not stand for the destination: it - # would hide the contradiction with the file actually shipped. - if ( - held is None - or id(claim.entry) in shipped - or _claim_rank(claim) > _claim_rank(held) - ): - by_dest[key] = claim - - # Grouped before judging: a profile may declare several revisions that are - # all acceptable at one destination, and the platform choosing one of them - # is agreement, not contradiction. Only a destination where no profile - # claim at all matches what ships is a disagreement. - # A platform claim resting on a bare name, or on a pin no local file - # matches, asserts nothing about content. Where the frontend never reads - # the bytes, a proven profile claim then decides: RetroArch's neocdz.zip - # pins an md5 nobody holds, and the primary shipped without the 000-lo.lo - # geolith and FBNeo read inside it. Decided per entry: EmuDeck, an md5 - # platform, declares the same archive with no hash. - mode = config.get("verification_mode", "existence") - rule = config.get("hash_rule", "") - by_slot: dict[str, list[Claim]] = {} - for claim in profile_claims( - profiles, db, base_dest, standalone_cores, zip_contents, data_dir_registry, - config=config, - ): - key = _normalize(claim.destination, fold) - platform = by_dest.get(key) - if platform is None or not claim.is_proven: - continue - if claim.status == SIZE_EXACT and ( - not platform.local_path - or _size_the_code_reads(claim.entry, platform.local_path) - ): - # A size proves a claim only against a file of another size. - continue - if not platform.is_proven and not ( - platform.local_path and checked_by_path(mode, platform.entry, rule) - ): - continue - by_slot.setdefault(key, []).append(claim) - - return by_dest, by_slot - - -def find_conflicts( - config: dict, - profiles: dict, - db: dict, - base_dest: str = "", - standalone_cores: set[str] | None = None, - zip_contents: dict | None = None, - data_dir_registry: dict | None = None, -) -> list[Conflict]: - """Destinations where a proven profile claim contradicts what ships. - - Only proven claims are compared. A claim resolved by filename alone - asserts nothing about content and cannot contradict anything. - """ - by_dest, by_slot = _slot_claims( - config, profiles, db, base_dest, standalone_cores, zip_contents, - data_dir_registry, - ) - # A declaration that lists several accepted hashes is satisfied by any of - # them: Recalbox names both scph1001.bin revisions, and mesence names - # four BS-X dumps among which System.dat pins one. The resolver stops on - # the first it finds, so the paths differ while both layers agree. - disputed = { - key: claims - for key, claims in by_slot.items() - if not any(_satisfies(c, by_dest[key], db) for c in claims) - } - - return [ - Conflict( - destination=by_dest[key].destination, - platform_claim=by_dest[key], - profile_claims=claims, - ) - for key, claims in sorted(disputed.items()) - ] - - -# Why a decision went the way it did. Not the mode's own name: the mode is -# spelt in one place only, and nativemode answers whether it reads content. -SERVES_BOTH = "path_only_check" -ADDRESSEE = "addressee" -FRONTEND_CHECKS_CONTENT = "frontend_checks_content" - - -@dataclass -class Decision: - """Which claim a pack should honour at a contested destination, and why.""" - - conflict: Conflict - winner: Claim - reason: str - - @property - def serves_both(self) -> bool: - """Whether honouring the winner still satisfies the other layer.""" - return self.reason == SERVES_BOTH - - -def pack_overrides( - config: dict, - profiles: dict, - db: dict, - zip_contents: dict | None = None, - data_dir_registry: dict | None = None, - target_cores: set[str] | None = None, - source: str = "full", - choices: dict[str, list[tuple[str, str | None]]] | None = None, -) -> dict[str, str]: - """Full pack destination -> the file a platform pack serves there instead. - - Where a source-verified profile contradicts the scraped baseline on one - destination, the pack answers to the platform it is built for. In - existence mode the frontend never reads the bytes, so serving the - emulator's file satisfies both. The ZIP builder, the install manifest and - verify all read this: two of them deciding alone gave the one-line - installer different bytes than the ZIP. ``choices`` is slot_choices - for the same arguments when the caller already holds it. - """ - # A baseline-only pack serves what the platform declares, and a target's - # pack answers to the cores that hardware builds: DuckStation does not - # exist on any RetroArch target and still replaced its scph5000.bin. - if not profiles or source == "platform": - return {} - cores = set(resolve_platform_cores(config, profiles, target_cores=target_cores)) - overrides: dict[str, str] = {} - if choices is None: - choices = slot_choices(config, profiles, db, zip_contents, data_dir_registry) - for destination, ordered in choices.items(): - path = next((path for emulator, path in ordered if emulator in cores), None) - if path: - overrides[destination] = path - return overrides - - -def slot_choices( - config: dict, - profiles: dict, - db: dict, - zip_contents: dict | None = None, - data_dir_registry: dict | None = None, -) -> dict[str, list[tuple[str, str | None]]]: - """Destination -> (core, the file it has served there) in decision order. - - A pack built for a set of cores serves the first choice whose core is in - it, None standing for the platform's own answer. No core in it leaves - the platform's answer too. The order is arbitrate's: a core agreeing with - the platform settles the slot whatever else is present, then the - strongest proof decides. Read for one core set by pack_overrides and - recorded whole in the install manifest, so a target narrowed from the - full manifest gets the bytes the target's own pack carries. - """ - mode = config.get("verification_mode", "existence") - rule = config.get("hash_rule", "") - platform_profiles = { - name: profiles[name] for name in resolve_platform_cores(config, profiles) - } - by_dest, by_slot = _slot_claims( - config, - platform_profiles, - db, - config.get("base_destination", ""), - platform_standalone_set(config), - zip_contents, - data_dir_registry, - ) - choices: dict[str, list[tuple[str, str | None]]] = {} - for key, claims in sorted(by_slot.items()): - platform = by_dest[key] - # Where the frontend compares a hash, the platform's file stays. - if not checked_by_path(mode, platform.entry, rule): - continue - agree = [_satisfies(c, platform, db) for c in claims] - agreeing = [c for c, ok in zip(claims, agree) if ok] - others = sorted( - (c for c, ok in zip(claims, agree) if not ok), - key=lambda claim: (-_claim_rank(claim), claims.index(claim)), - ) - if not others: - continue - choices[platform.destination] = [ - *((c.emulator, None) for c in agreeing), - *((c.emulator, c.local_path) for c in others), - ] - return choices - - -def _strongest(claims: list[Claim]) -> Claim: - """The profile claim with the strongest proof, the first emulator breaking ties. - - yaps2 pins its GameIndex.yaml by sha1 while armsx2 and lrps2 only match a - path: alphabetical order served armsx2's copy to all three. - """ - return max(claims, key=lambda claim: (_claim_rank(claim), -claims.index(claim))) - - -def arbitrate( - conflict: Conflict, mode: str, addressee: str = "platform", rule: str = "", -) -> Decision: - """Decide a contested destination for the pack being built. - - A pack answers to whoever asked for it. A platform pack must leave the - frontend's own check green, because a user reading red concludes the pack - is broken. A pack built for one emulator answers to that emulator. The - other layer is served as well whenever the destination allows it. - - In ``existence`` mode the frontend only looks for a path, so the emulator's - file satisfies both sides at once and there is nothing to trade away. In a - content-checking mode the two answers cannot share one path, and the pack's - addressee decides. The loss is reported rather than absorbed: only the - platform's own list can change what its frontend accepts there. - """ - profile = _strongest(conflict.profile_claims) - if addressee == "emulator": - return Decision(conflict, profile, ADDRESSEE) - if checked_by_path(mode, conflict.platform_claim.entry, rule): - return Decision(conflict, profile, SERVES_BOTH) - return Decision(conflict, conflict.platform_claim, FRONTEND_CHECKS_CONTENT) + pass +from packs.slots import ADDRESSEE, Claim, Conflict, Decision, arbitrate, find_conflicts +from resolve.collisions import Collision, find_collisions def _pinned_elsewhere(claims: list[Claim], winner: str | None) -> set[str]: @@ -679,20 +81,6 @@ def format_decision(decision: Decision) -> str: ) -@dataclass -class Collision: - """One destination a platform fills with two different files.""" - - destination: str - resolved: list[str] - # Each declaration with the file it resolved to, in the platform's order. - declarations: list[tuple[dict, str | None]] = field(default_factory=list) - # The system of each declaration, in the same order. - systems: list[str] = field(default_factory=list) - # The file the pack ships at the destination, as the builder decides it. - shipped: str | None = None - - def _collision_json(collision: Collision) -> dict: return { "destination": collision.destination, @@ -705,240 +93,6 @@ def _collision_json(collision: Collision) -> dict: } -def find_collisions( - config: dict, - db: dict, - zip_contents: dict | None = None, - data_dir_registry: dict | None = None, -) -> list[Collision]: - """Destinations a platform declares twice and resolves two ways. - - One path holds one file, so whichever declaration the builder reaches - first decides in silence. Declaring an archive several times to name its - inner ROMs is the documented zipped_file pattern and resolves to one - archive. Two declarations landing on two files name two files for one - path. RetroDECK aims a PC-88 disk subsystem ROM and a - CoCo disk ROM at one bios/disk.rom. - """ - fold = bool(config.get("case_insensitive_fs", False)) - systems = config.get("systems") or {} - # The builder lets a hash-constrained declaration that resolves by - # content take the path, else the first it reaches walking the systems - # sorted: the same choice says which file ships. - preferred = set( - preferred_entries(systems, db, "bios", "", False, zip_contents, True).values() - ) - by_dest: dict[str, list[tuple[str, dict]]] = {} - for sys_id, system in systems.items(): - for entry in system.get("files") or []: - if not isinstance(entry, dict): - continue - dest = entry.get("destination") or entry.get("name") or "" - if dest: - by_dest.setdefault(_normalize(dest, fold), []).append((sys_id, entry)) - - collisions = [] - for key, claims in sorted(by_dest.items()): - if len(claims) < 2: - continue - entries = [entry for _sys_id, entry in claims] - resolved = [] - declarations = [] - for entry in entries: - local, _ = resolve_local_file( - entry, - db, - zip_contents, - dest_hint=entry.get("destination", ""), - data_dir_registry=data_dir_registry, - ) - declarations.append((entry, local)) - if local and local not in resolved: - resolved.append(local) - if len(resolved) > 1 and not _same_file_family(resolved): - # A file every declaration accepts settles the path: RetroDECK - # declares ATARIOSB.ROM twice, the second with an md5 list that - # also names the first one's file. - if any(_accepted_by_all(path, entries, db) for path in resolved): - continue - reached = sorted( - (sys_id, local) - for (sys_id, _entry), (_e, local) in zip(claims, declarations) if local - ) - shipped = next( - (local for entry, local in declarations if local and id(entry) in preferred), - reached[0][1], - ) - collisions.append( - Collision( - destination=key, - resolved=resolved, - declarations=declarations, - systems=[sys_id for sys_id, _entry in claims], - shipped=shipped, - ) - ) - return collisions - - -def _satisfies(profile: Claim, platform: Claim, db: dict) -> bool: - """Whether the two layers agree on what ships at this destination. - - They agree when they resolve to the same bytes, when the platform's own - hash list accepts the profile's file, or when the profile's accepts the - platform's. A contradiction needs both lists to reject the other side. - A core found by content (found_by: content) reads no file by the - destination's name, so any dump it takes for the same system and region - settles the slot: DuckStation takes Batocera's scph1001.bin v2.0, which its profile - labels scph1001_v20.bin. - """ - if profile.local_path == platform.local_path: - return True - # Two paths can hold one content: AmberELEC's bluemsx declarations - # resolve into the data/bluemsx cache, the profile's into bios/. - if profile.local_path and platform.local_path: - shipped = _content_sha1(platform.local_path, db) - if shipped is not None and shipped == _content_sha1(profile.local_path, db): - return True - members = profile.entry.get("members") - if members and platform.local_path: - return holds_required_members(platform.local_path, members) - if ( - profile.local_path - and _lists_hashes(platform.entry) - and _accepted_by_all(profile.local_path, [platform.entry], db) - ): - return True - if platform.local_path and any( - _lists_hashes(label) and _accepted_by_all(platform.local_path, [label], db) - for label in profile.accepts - ): - return True - return bool( - platform.local_path - and _lists_hashes(profile.entry) - and _accepted_by_all(platform.local_path, [profile.entry], db) - ) - - -def _lists_hashes(entry: dict) -> bool: - """Whether a declaration says anything about content at all.""" - return any( - _declared_hashes(entry, field_name) - for field_name in ("md5", "sha1", "sha256", "crc32") - ) - - -def _declared_hashes(entry: dict, field_name: str) -> set[str]: - """Hashes an entry accepts for one field, declared as a string or a list.""" - value = entry.get(field_name) - values = value if isinstance(value, list) else [value] - # Recalbox writes its md5 list comma separated, and profiles do the - # same for sha256 (mesence names four BS-X dumps in one string). - return { - part.strip().lower() - for v in values - if v - for part in str(v).split(",") - if part.strip() - } - - -def _record_at(path: str, db: dict) -> dict | None: - """The database record stored at path, from an index built once per db. - - A scan of db['files'] on every call was O(calls x 19 000 files) on the - path verify --all and slots.py both take. - """ - files = db.get("files", {}) - cached = _PATH_INDEX.get(id(files)) - if cached is None or cached[0] is not files: - cached = (files, {e.get("path"): e for e in files.values()}) - _PATH_INDEX[id(files)] = cached - return cached[1].get(path) - - -_PATH_INDEX: dict[int, tuple[dict, dict[str, dict]]] = {} - - -def _content_sha1(path: str, db: dict) -> str | None: - """The sha1 of the file at path, from the database or read from disk. - - A data directory cache is not in the database, so its files are hashed. - """ - record = _record_at(path, db) - if record is not None: - return record.get("sha1") - if not os.path.isfile(path): - return None - return compute_hashes(path, frozenset({"sha1"}))["sha1"] - - -def _accepted_by_all(path: str, entries: list[dict], db: dict) -> bool: - """Whether every declaration's own hashes accept the file at path.""" - record = _record_at(path, db) - if record is None: - return False - for entry in entries: - if entry.get("zipped_file"): - declared = parse_md5_list(entry.get("md5")) - if declared and not any( - check_inside_zip(path, entry["zipped_file"], m) == "ok" for m in declared - ): - return False - continue - for field_name in ("md5", "sha1", "sha256", "crc32"): - declared = _declared_hashes(entry, field_name) - if declared and str(record.get(field_name, "")).lower() not in declared: - if field_name == "crc32" and _headerless_crc32(path, record, entry) in declared: - continue - return False - return True - - -COPIER_HEADER = 512 - - -def _headerless_crc32(path: str, record: dict, entry: dict) -> str | None: - """The crc32 of a file past its 512-byte copier header, when the entry - declares both the file's size and the size without the header. - - Geargrafx drops the header when the file is 512 bytes over the expected - size and computes the crc32 on the rest (src/media.cpp:754-773). The - profile lists both sizes. EmuELEC's headered syscard3.pce (crc32 - 64f78e3c) is the 6d9a73ef image the profile names. - """ - sizes = entry.get("size") - declared = sizes if isinstance(sizes, list) else [sizes] - size = record.get("size") - if not isinstance(size, int) or not {size, size - COPIER_HEADER} <= set(declared): - return None - try: - with open(path, "rb") as f: - f.seek(COPIER_HEADER) - return f"{zlib.crc32(f.read()):08x}" - except OSError: - return None - - -def _same_file_family(paths: list[str]) -> bool: - """Whether the paths are one file and its own pinned variants. - - A platform list built on an older romset pins bytes the primary no longer - carries, which the repository keeps side by side under .variants. That is - the documented multi-version case, not two machines fighting for a path. - """ - canonical = set() - for path in paths: - if "/.variants/" in path: - directory, _, name = path.rpartition("/") - directory = directory[: -len("/.variants")] - name = variant_base_name(name) - path = f"{directory}/{name}" - canonical.add(path.casefold()) - return len(canonical) == 1 - - def format_collision(collision: Collision) -> str: """One line naming the destination, which system declares which file, and the one the pack ships there.""" @@ -1033,7 +187,7 @@ def main() -> int: import contextlib from model.registry import load_data_dir_registry - from refresh_data_dirs import hold_data_dirs + from packs.datadirs import hold_data_dirs # Claims resolve against data/: the trees stay put until the process # ends, which releases the hold. diff --git a/scripts/split_pack.py b/scripts/split_pack.py index 81cd5ef9c..8fac7c2e2 100644 --- a/scripts/split_pack.py +++ b/scripts/split_pack.py @@ -20,301 +20,13 @@ Usage: from __future__ import annotations import argparse -import io import re -import struct import sys import zipfile -import zlib from pathlib import Path from core.artifacts import ArtifactLockBusy, artifact_lock - -# "Each file included in a release must be under 2 GiB." -ASSET_LIMIT = 2 * 1024**3 - -PACK_SUFFIX = "_BIOS_Pack.zip" -_PART_NAME = re.compile(r"^(?P.+_BIOS_Pack)\.part(?P\d+)of(?P\d+)\.zip$") -_MARKER_NAME = re.compile(r"^(?P.+_BIOS_Pack)\.part(?P\d+)of(?P\d+)\.txt$") -# Sizes are written at a fixed width, so a marker's length, and with it the -# size of its own part, does not depend on the sizes it records. -_SIZE_WIDTH = 13 - -_LOCAL = struct.Struct("<4s2B4HL2L2H") -_CENTRAL = struct.Struct("<4s4B4HL2L5H2L") -_END = struct.Struct("<4s4H2LH") -_LOCAL_SIG = b"PK\x03\x04" -_CENTRAL_SIG = b"PK\x01\x02" -_END_SIG = b"PK\x05\x06" -_DATA_DESCRIPTOR = 0x08 -_UTF8_NAME = 0x800 -_CHUNK = 1024 * 1024 -_MAX_ENTRIES = 0xFFFF -_MAX_FIELD = 0xFFFFFFFF - - -def is_part(name: str) -> bool: - """Whether a file name is one part of a split pack.""" - return _PART_NAME.match(name) is not None - - -def pack_of(name: str) -> str: - """The pack a published file belongs to, a part folded into its archive.""" - part = _PART_NAME.match(name) - return f"{part['stem']}.zip" if part else name - - -def part_name(pack_name: str, index: int, count: int) -> str: - return f"{pack_name[: -len('.zip')]}.part{index}of{count}.zip" - - -def marker_name(pack_name: str, index: int, count: int) -> str: - return f"{pack_name[: -len('.zip')]}.part{index}of{count}.txt" - - -def is_marker(name: str) -> bool: - """Whether an archive member is the marker a split writes in each part.""" - return _MARKER_NAME.match(name) is not None - - -def marker_text(pack_name: str, index: int, sizes: list[int]) -> bytes: - """The marker of part *index* of a pack published in ``len(sizes)`` parts. - - Plain text a person can read, in a form install.py parses back: the - lines that matter are `pack:`, `part:` and one `file:` per part. - """ - count = len(sizes) - lines = [ - "RetroBIOS split pack", - f"This folder holds part {index} of {count} of {pack_name}.", - "Every part is needed: extract them all into this same folder.", - "The installer's --check names a part missing from the folder.", - "", - f"pack: {pack_name}", - f"part: {index} of {count}", - ] - lines += [ - f"file: {size:>{_SIZE_WIDTH}} {part_name(pack_name, number, count)}" - for number, size in enumerate(sizes, 1) - ] - return ("\n".join(lines) + "\n").encode("utf-8") - - -def _marker_weight(pack_name: str, index: int, count: int) -> int: - name = len(marker_name(pack_name, index, count).encode("utf-8")) - body = len(marker_text(pack_name, index, [0] * count)) - return _LOCAL.size + name + body + _CENTRAL.size + name - - -def _name_bytes(info: zipfile.ZipInfo) -> bytes: - encoding = "utf-8" if info.flag_bits & _UTF8_NAME else "cp437" - return info.orig_filename.encode(encoding) - - -def _weight(info: zipfile.ZipInfo) -> int: - """Bytes a member adds to a part: both headers and its stored data.""" - name = len(_name_bytes(info)) - return _LOCAL.size + name + info.compress_size + _CENTRAL.size + name - - -def plan_parts( - members: list[zipfile.ZipInfo], limit: int, reserve: int = 0 -) -> list[list[zipfile.ZipInfo]]: - """Fill each part in archive order, up to the limit less *reserve*.""" - parts: list[list[zipfile.ZipInfo]] = [[]] - floor = _END.size + reserve - size = floor - for info in members: - weight = _weight(info) - if floor + weight >= limit: - raise ValueError( - f"{info.filename} needs {weight:,} bytes, more than a part of " - f"{limit:,} can hold" - ) - if info.compress_size > _MAX_FIELD or info.file_size > _MAX_FIELD: - raise ValueError(f"{info.filename} needs ZIP64, which a part does not use") - if size + weight >= limit or len(parts[-1]) >= _MAX_ENTRIES - 1: - parts.append([]) - size = floor - parts[-1].append(info) - size += weight - return parts - - -def _dos_stamp(info: zipfile.ZipInfo) -> tuple[int, int]: - year, month, day, hour, minute, second = info.date_time - return ( - (hour << 11) | (minute << 5) | (second // 2), - ((year - 1980) << 9) | (month << 5) | day, - ) - - -def _data_offset(source: io.BufferedReader, info: zipfile.ZipInfo) -> int: - """Where a member's stored bytes begin, read from its own local header.""" - source.seek(info.header_offset) - header = _LOCAL.unpack(source.read(_LOCAL.size)) - if header[0] != _LOCAL_SIG: - raise ValueError(f"{info.filename}: no local header at its offset") - return info.header_offset + _LOCAL.size + header[10] + header[11] - - -def _marker_info(name: str, body: bytes) -> zipfile.ZipInfo: - info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) - info.compress_type = zipfile.ZIP_STORED - info.CRC = zlib.crc32(body) - info.compress_size = info.file_size = len(body) - info.create_system = 3 - info.external_attr = (0o100000 | 0o644) << 16 - return info - - -def _write_part( - source: io.BufferedReader, members: list[zipfile.ZipInfo], dest: Path, - marker: tuple[str, bytes], -) -> None: - directory = [] - marker_info = _marker_info(*marker) - with open(dest, "wb") as out: - for info in [marker_info, *members]: - name = _name_bytes(info) - flags = info.flag_bits & ~_DATA_DESCRIPTOR - dos_time, dos_date = _dos_stamp(info) - offset = out.tell() - out.write( - _LOCAL.pack( - _LOCAL_SIG, info.extract_version, info.reserved, flags, - info.compress_type, dos_time, dos_date, info.CRC, - info.compress_size, info.file_size, len(name), 0, - ) - ) - out.write(name) - if info is marker_info: - out.write(marker[1]) - remaining = 0 - else: - source.seek(_data_offset(source, info)) - remaining = info.compress_size - while remaining: - chunk = source.read(min(_CHUNK, remaining)) - if not chunk: - raise ValueError(f"{info.filename}: the pack ends inside it") - out.write(chunk) - remaining -= len(chunk) - directory.append( - _CENTRAL.pack( - _CENTRAL_SIG, info.create_version, info.create_system, - info.extract_version, info.reserved, flags, - info.compress_type, dos_time, dos_date, info.CRC, - info.compress_size, info.file_size, len(name), 0, 0, 0, - info.internal_attr, info.external_attr, offset, - ) - + name - ) - start = out.tell() - for record in directory: - out.write(record) - out.write( - _END.pack( - _END_SIG, 0, 0, len(directory), len(directory), - out.tell() - start, start, 0, - ) - ) - - -def _identity(archive: zipfile.ZipFile) -> list[tuple[str, int, int]]: - return [ - (info.filename, info.CRC, info.file_size) - for info in archive.infolist() - if not is_marker(info.filename) - ] - - -def marker_weight(pack_name: str, count: int) -> int: - """Bytes the largest marker of a pack in *count* parts adds to its part.""" - return max(_marker_weight(pack_name, index, count) for index in (1, count)) - - -def _plan_with_markers( - pack_name: str, members: list[zipfile.ZipInfo], limit: int -) -> list[list[zipfile.ZipInfo]]: - """Plan the parts with room for the marker each one carries. - - The marker lists every part, so its length grows with their count: the - plan is made again until the count it assumed is the count it gives. - """ - count = 1 - while True: - reserve = marker_weight(pack_name, count) - plan = plan_parts(members, limit, reserve) - if len(plan) <= count: - return plan - count = len(plan) - - -def split_pack(zip_path: Path, limit: int = ASSET_LIMIT) -> list[Path]: - """Replace a pack at or over the limit by parts that each fit under it. - - Returns the files to publish. The pack is removed only once every part - has been read back in full and the parts together list exactly its - members, so a failure leaves the pack as it was and no part behind. - """ - zip_path = Path(zip_path) - if zip_path.stat().st_size < limit: - return [zip_path] - - with zipfile.ZipFile(zip_path) as archive: - members = archive.infolist() - expected = _identity(archive) - taken = [info.filename for info in members if is_marker(info.filename)] - if taken: - raise ValueError(f"{zip_path.name} already holds {taken[0]}, a part marker name") - plan = _plan_with_markers(zip_path.name, members, limit) - count = len(plan) - parts = [ - zip_path.with_name(part_name(zip_path.name, index, count)) - for index in range(1, count + 1) - ] - sizes = [ - _END.size + _marker_weight(zip_path.name, index, count) - + sum(_weight(info) for info in chosen) - for index, chosen in enumerate(plan, 1) - ] - try: - with open(zip_path, "rb") as source: - for index, (dest, chosen) in enumerate(zip(parts, plan), 1): - marker = (marker_name(zip_path.name, index, count), - marker_text(zip_path.name, index, sizes)) - _write_part(source, chosen, dest, marker) - if dest.stat().st_size != sizes[index - 1]: - raise ValueError( - f"{dest.name} is {dest.stat().st_size:,} bytes, its marker " - f"says {sizes[index - 1]:,}" - ) - found: list[tuple[str, int, int]] = [] - for dest in parts: - with zipfile.ZipFile(dest) as archive: - damaged = archive.testzip() - if damaged: - raise ValueError(f"{dest.name}: {damaged} does not read back") - found.extend(_identity(archive)) - if dest.stat().st_size >= limit: - raise ValueError(f"{dest.name} reached the limit of {limit:,} bytes") - if found != expected: - raise ValueError(f"the parts of {zip_path.name} do not add up to it") - except (OSError, ValueError, zipfile.BadZipFile): - for dest in parts: - dest.unlink(missing_ok=True) - raise - zip_path.unlink() - return parts - - -def split_directory(directory: Path, limit: int = ASSET_LIMIT) -> list[Path]: - """Split every pack of a directory that needs it. Returns what to publish.""" - published: list[Path] = [] - for path in sorted(Path(directory).glob(f"*{PACK_SUFFIX}")): - published.extend(split_pack(path, limit)) - return published +from packs.parts import ASSET_LIMIT, split_directory, split_pack def _size(text: str) -> int: diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index e2002f24e..d758e66dd 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -18,984 +18,36 @@ Outputs a structured report suitable for PR comments. from __future__ import annotations import argparse -import hashlib import json import os -import re import shutil -import subprocess import sys -import urllib.parse -import zipfile -from collections.abc import Callable, Iterable -from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Any, TypedDict +from typing import TYPE_CHECKING if TYPE_CHECKING: - from typing_extensions import Unpack + pass sys.path.insert(0, os.path.dirname(__file__)) -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 -from resolve.validation import frontend_digest_matches, inner_rom_check try: import yaml except ImportError: yaml = None +from core.gitclone import _git_lines, _project_main_line +from resolve.review import ( + ValidationResult, + load_platform_hashes, + load_profile_hashes, + validate_file, +) DEFAULT_DB = "database.json" DEFAULT_PLATFORMS_DIR = "platforms" DEFAULT_EMULATORS_DIR = "emulators" -BLOCKED_EXTENSIONS = { - ".exe", - ".bat", - ".cmd", - ".sh", - ".ps1", - ".vbs", - ".js", - ".msi", - ".dll", - ".so", - ".dylib", - ".py", - ".rb", - ".pl", -} - -MAX_FILE_SIZE = 100 * 1024 * 1024 -LARGE_FILE_ISSUE_URL = ( - "https://github.com/Abdess/retrobios/issues/new?template=missing-bios.yml" -) - - -def large_file_issue_url(result: ValidationResult) -> str: - """The issue form with the values this run computed already filled in. - - GitHub fills an issue form field from the query parameter named by its - id: filename, sha1, md5 and size in missing-bios.yml. - """ - fields = { - "title": f"[BIOS] Missing: {result.filename}", - "filename": result.filename, - "sha1": result.sha1, - "md5": result.md5, - "size": str(result.size), - } - return f"{LARGE_FILE_ISSUE_URL}&{urllib.parse.urlencode(fields)}" - - -class ValidationResult: - def __init__(self, filepath: str) -> None: - self.filepath = filepath - self.filename = os.path.basename(filepath) - self.checks: list[tuple[str, str]] = [] # (status, message) tuples - self.sha1 = "" - self.md5 = "" - self.crc32 = "" - self.size = 0 - # "held" (a copy of a file the collection has) or "unknown" (no list - # or profile declares it): no check fails, and neither is a file - # the pull request adds to the collection. - self.outcome = "" - # Where --place copies the file: one folder and one declared name, or - # the .variants/ slot of a name the collection already holds. - self.destination = "" - - def add_check(self, passed: bool, message: str) -> None: - self.checks.append(("PASS" if passed else "FAIL", message)) - - def add_warning(self, message: str) -> None: - self.checks.append(("WARN", message)) - - def add_info(self, message: str) -> None: - self.checks.append(("INFO", message)) - - @property - def passed(self) -> bool: - return all(s != "FAIL" for s, _ in self.checks) - - @property - def status(self) -> str: - return "FAIL" if not self.passed else "REVIEW" if self.outcome else "PASS" - - def to_markdown(self) -> str: - status = self.status - lines = [f"### {status} `{self.filename}`"] - lines.append("") - lines.append(f"- **Path**: `{self.filepath}`") - # A path refused before it was read has no size or digest to show: - # empty fields read as an empty file contributed. - if self.sha1: - lines.append(f"- **Size**: {self.size:,} bytes") - lines.append(f"- **SHA1**: `{self.sha1}`") - lines.append(f"- **MD5**: `{self.md5}`") - lines.append(f"- **CRC32**: `{self.crc32}`") - lines.append("") - - for status_str, message in self.checks: - if status_str == "PASS": - lines.append(f"- Pass: {message}") - elif status_str == "FAIL": - lines.append(f"- Fail: {message}") - elif status_str == "WARN": - lines.append(f"- Warning: {message}") - else: - lines.append(f"- Info: {message}") - - return "\n".join(lines) - - -def _note_sizes(sizes: dict[str, list], names: list[str], entry: dict) -> None: - """Record the sizes an entry accepts under each of its names. - - An entry that declares no size says nothing about it, so a name is - judged only by the declarations that do. - """ - size = entry.get("size") - accepted = [] - if isinstance(size, list): - accepted = [(int(v), int(v)) for v in size] - elif isinstance(size, int) and size > 0: - accepted = [(size, size)] - if entry.get("min_size") or entry.get("max_size"): - accepted.append((int(entry.get("min_size") or 0), - int(entry.get("max_size") or 2 ** 63))) - for name in names if accepted else []: - sizes.setdefault(name, []).extend(accepted) - - -def load_platform_hashes(platforms_dir: str, db: dict | None = None) -> dict: - """Load all known hashes from platform configs. - - With the database, `folders` maps each declared hash to the - bios/// folders the collection files its system - under, read from the other files of that system it holds. - """ - known: dict[str, Any] = {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(), - "names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}, - "name_systems": {}, "system_dirs": {}, "system_folders": {}} - systems_of: dict[str, set[str]] = {} - folders_of: dict[str, dict[str, int]] = {} - files = (db or {}).get("files", {}) - by_md5 = (db or {}).get("indexes", {}).get("by_md5", {}) - - if not os.path.isdir(platforms_dir) or yaml is None: - return known - - # Read the way verify reads them: inheritance and shared groups resolved, - # and a Recalbox md5 field split into the revisions it lists. The raw - # file kept "a,b,c" as one value, so a PR adding the seventh accepted - # falcon.img was told its hash differs. - for name in list_registered_platforms(platforms_dir): - try: - config = load_platform_config(name, platforms_dir) - except (OSError, yaml.YAMLError) as exc: - print(f"WARNING: {name}: {exc}", file=sys.stderr) - continue - - mode, rule = config.get("verification_mode"), config.get("hash_rule", "") - for system_id, system in config.get("systems", {}).items(): - for file_entry in system.get("files", []): - sha1s = parse_hash_list(file_entry.get("sha1")) - md5s = parse_md5_list(file_entry.get("md5")) - sha256s = parse_hash_list(file_entry.get("sha256")) - known["sha1"].update(sha1s) - known["md5"].update(md5s) - known["sha256"].update(sha256s) - if not (sha1s or md5s or sha256s) and isinstance(file_entry.get("size"), int): - # The resolver's reading: a crc32 counts where no stronger - # hash is declared, bounded by the declared size. - known["crc32"].update( - (crc.zfill(8), file_entry["size"]) - for crc in parse_hash_list(file_entry.get("crc32")) - ) - if "name" in file_entry: - known["names"].add(file_entry["name"]) - _note_sizes(known["sizes"], [file_entry["name"]], file_entry) - # A frontend that hashes a ZIP's member or its members - # together, or that takes any hash at the declared size, - # answers by its own rule, read per entry. - known["entries"].setdefault(file_entry["name"].lower(), []).append( - (file_entry, mode, rule, name) - ) - known["name_systems"].setdefault(file_entry["name"].lower(), set()).add(system_id) - for value in (*sha1s, *md5s): - systems_of.setdefault(value, set()).add(system_id) - for value in (*sha1s, *md5s, *sha256s): - if "name" in file_entry: - known["named"].setdefault(value, set()).add(file_entry["name"]) - _note_folder(folders_of, system_id, files, by_md5, sha1s, md5s, - known["system_dirs"]) - - known["folders"] = _system_homes(systems_of, folders_of) - known["system_folders"] = _single_maker_folders(folders_of) - return known - - -def _note_folder( - folders_of: dict[str, dict[str, int]], system_id: str, files: dict, - by_md5: dict, sha1s: list[str], md5s: list[str], - dirs_of: dict[str, set[str]] | None = None, -) -> None: - """Count the bios/// folder a held file sits in, - and note the directory it sits in under *dirs_of*.""" - held = next((s for s in sha1s if s in files), None) or next( - (by_md5[m] for m in md5s if m in by_md5), None - ) - path = str(files.get(held, {}).get("path", "")) - if dirs_of is not None and "/" in path and "/.variants/" not in path: - dirs_of.setdefault(system_id, set()).add(path.rsplit("/", 1)[0] + "/") - parts = path.split("/") - if len(parts) >= 4 and parts[0] == "bios" and not parts[2].startswith("."): - folder = "/".join(parts[:3]) + "/" - counts = folders_of.setdefault(system_id, {}) - counts[folder] = counts.get(folder, 0) + 1 - - -def _single_maker_folders(folders_of: dict[str, dict[str, int]]) -> dict[str, set[str]]: - """System id to the folders the collection files it under, for a system - filed under one manufacturer only, the rule _system_homes applies.""" - return { - system_id: set(held_in) for system_id, held_in in folders_of.items() - if len({folder.split("/")[1] for folder in held_in}) == 1 - } - - -def _system_homes( - systems_of: dict[str, set[str]], folders_of: dict[str, dict[str, int]] -) -> dict[str, set[str]]: - """Hash value to the folders the collection files its systems under. - - A system whose files sit under several manufacturers (arcade sets, - computers sharing ROM chips) names no single home: only a system filed - under one manufacturer says where a newcomer belongs. - """ - homes: dict[str, set[str]] = {} - for value, systems in systems_of.items(): - folders: set[str] = set() - for system_id in systems: - held_in = folders_of.get(system_id, {}) - if len({folder.split("/")[1] for folder in held_in}) == 1: - folders.update(held_in) - if folders: - homes[value] = folders - return homes - - -def load_profile_hashes( - emulators_dir: str, db: dict | None = None -) -> dict[str, dict[str, set[str]]]: - """Hash value to the emulators whose profile declares it, per algorithm. - - A file only a core reads (a standalone emulator's firmware, a game - engine's data) is in no platform list: the review called every such - contribution "not referenced, needs manual review". With the database, - `folders` maps each declared hash to the folders the collection files - the entry's system under, as load_platform_hashes does: a contributor - holding a file only a profile declares was told to pick a - bios/Manufacturer/Console/ folder alone. - """ - known: dict[str, dict] = { - "sha1": {}, "sha256": {}, "md5": {}, "crc32": {}, "sizes": {}, "folders": {}, - "named": {}, "name_systems": {}, "system_dirs": {}, "system_folders": {}, - } - systems_of: dict[str, set[str]] = {} - folders_of: dict[str, dict[str, int]] = {} - files = (db or {}).get("files", {}) - indexes = (db or {}).get("indexes", {}) - by_md5, by_sha256 = indexes.get("by_md5", {}), indexes.get("by_sha256", {}) - for emulator, profile in load_emulator_profiles(emulators_dir).items(): - declared_systems = profile.get("systems") or [] - for entry in profile.get("files") or []: - if not isinstance(entry, dict): - continue - names = [entry.get("name"), *(entry.get("aliases") or [])] - _note_sizes(known["sizes"], [n for n in names if isinstance(n, str)], entry) - # The resolver's reading: comma lists split (mesence's four - # sha256), and a crc32 counts only where no stronger hash is - # declared, bounded by the declared size (626 entries name a - # file by crc32 alone, clk's Electron os.rom among them). - hashes = { - algo: parse_hash_list(entry.get(algo)) for algo in ("sha1", "sha256", "md5") - } - for algo, values in hashes.items(): - for value in values: - known[algo].setdefault(value, set()).add(emulator) - if isinstance(entry.get("name"), str): - known["named"].setdefault(value, set()).add(entry["name"]) - # The entry's own system, or the profile's when it emulates one. - system = entry.get("system") or ( - declared_systems[0] if len(declared_systems) == 1 else None - ) - if isinstance(system, str): - for value in (v for values in hashes.values() for v in values): - systems_of.setdefault(value, set()).add(system) - for n in names: - if isinstance(n, str): - known["name_systems"].setdefault(n.lower(), set()).add(system) - sha1s = [*hashes["sha1"], *( - by_sha256[v] for v in hashes["sha256"] if v in by_sha256 - )] - _note_folder(folders_of, system, files, by_md5, sha1s, hashes["md5"], - known["system_dirs"]) - if not any(entry.get(algo) for algo in ("sha1", "sha256", "md5")): - size = entry.get("size") - sizes = [int(v) for v in size] if isinstance(size, list) else ( - [int(size)] if size else [None] - ) - for value in parse_hash_list(entry.get("crc32")): - for accepted in sizes: - key = (value.zfill(8), accepted) - known["crc32"].setdefault(key, set()).add(emulator) - known["folders"] = _system_homes(systems_of, folders_of) - known["system_folders"] = _single_maker_folders(folders_of) - return known - - -def _archive_members( - filepath: str, db: dict | None, platform_hashes: dict, profile_hashes: dict -) -> list[str] | None: - """What each file of a ZIP is, None when filepath is not a ZIP. - - Read only for an archive no list declares as a whole: MAME and FBNeo - sets are ZIP BIOS files in their own right. - """ - if not zipfile.is_zipfile(filepath): - return None - held = (db or {}).get("files", {}) - described = [] - try: - with zipfile.ZipFile(filepath) as archive: - for info in archive.infolist(): - if info.is_dir(): - continue - if info.file_size > MAX_FILE_SIZE: - described.append(f"`{info.filename}` too large to read here") - continue - sha1, md5 = hashlib.sha1(), hashlib.md5() - with archive.open(info) as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - sha1.update(chunk) - md5.update(chunk) - sha1_hex, md5_hex = sha1.hexdigest(), md5.hexdigest() - crc = f"{info.CRC:08x}" - if sha1_hex in held: - state = f"already held at `{held[sha1_hex]['path']}`" - elif ( - sha1_hex in platform_hashes.get("sha1", set()) - or md5_hex in platform_hashes.get("md5", set()) - or (crc, info.file_size) in platform_hashes.get("crc32", set()) - or profile_hashes.get("sha1", {}).get(sha1_hex) - or profile_hashes.get("md5", {}).get(md5_hex) - or profile_hashes.get("crc32", {}).get((crc, info.file_size)) - ): - state = "declared and not held" - else: - state = "not recognised" - described.append(f"`{info.filename}` {state}") - except (zipfile.BadZipFile, RuntimeError, OSError) as exc: - # An encrypted member raises RuntimeError. - described.append(f"unreadable ({exc})") - return described - - -@dataclass(frozen=True) -class _Review: - """One file under review and the tables it is read against.""" - - filepath: str - db: dict | None - platform_hashes: dict - profile_hashes: dict - - -@dataclass(frozen=True) -class _Known: - """What declares the file: a platform's hash, its own check, a profile, its name.""" - - sha1: bool - md5: bool - other: bool - accepted_by: set[str] - by_profile: set[str] | None - name: bool - - @property - def by_platform(self) -> bool: - return bool(self.sha1 or self.md5 or self.other or self.accepted_by) - - -def _path_problem(filepath: str) -> str: - """Why the path cannot be reviewed, empty when it can.""" - # Whoever opened the pull request chose this path, so its shape is - # settled before anything is read. A symlink to an endless device would - # otherwise be hashed until the job timed out, and a symlink out of the - # checkout would be reported as though its target had been contributed. - if os.path.islink(filepath): - return "Symlinks are not allowed" - if not os.path.exists(filepath): - return (f"File not found: {filepath}. A path is read from the folder " - "the command runs in, or pass --changed to check the files " - "changed under bios/") - if os.path.isdir(filepath): - return "Folder with no file in it" - if not os.path.isfile(filepath): - return "Not a regular file: a device, a pipe or a socket" - return "" - - -def _check_size(result: ValidationResult) -> bool: - """The size checks, True when the file is too large for git.""" - too_large = result.size > MAX_FILE_SIZE - if too_large: - # GitHub refuses a pushed file over 100 MiB, so a pull request cannot - # carry it. Only a maintainer can add an asset to the release. - result.add_check( - False, - f"File too large for git ({result.size:,} > {MAX_FILE_SIZE:,} bytes). " - "Leave it out of the pull request and open an issue, its hashes " - f"filled in ({large_file_issue_url(result)}), saying where the file " - "can be obtained: a maintainer adds it to the `large-files` release.", - ) - elif result.size == 0: - result.add_check(False, "File is empty (0 bytes)") - else: - result.add_check(True, f"File size within limits ({result.size:,} bytes)") - return too_large - - -def _relative_path(filepath: str) -> str: - # Paths are compared as the database writes them, relative to the - # checkout: an absolute path to the file itself read as its duplicate. - if os.path.isabs(filepath): - candidate = os.path.relpath(filepath, os.getcwd()) - if not candidate.startswith(".."): - return candidate - return filepath - - -def _check_duplicate(result: ValidationResult, db: dict, relative: str) -> None: - if result.sha1 not in db.get("files", {}): - result.add_check(True, "Not a duplicate in database") - return - existing = db["files"][result.sha1] - held_at = { - os.path.normpath(p) - for p in [existing.get("path"), *(existing.get("paths") or [])] if p - } - if os.path.normpath(relative) in held_at: - # The file the database was built from, not a copy of it: a - # PR that regenerated database.json was told each new file - # duplicated itself. - result.add_check(True, "Already in the database at this path") - elif _in_nodedup_dir(relative): - result.add_info( - f"Identical to `{existing['path']}`, kept: this tree is read by path" - ) - else: - result.outcome = "held" - result.add_warning( - f"Already held at `{existing['path']}`: nothing to add, " - "leave this copy out of the pull request" - ) - - -def _identify(review: _Review, result: ValidationResult, sha256: str) -> _Known: - platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes - sha1_known = result.sha1 in platform_hashes.get("sha1", set()) - md5_known = result.md5 in platform_hashes.get("md5", set()) - other_known = ( - sha256 in platform_hashes.get("sha256", set()) - or (result.crc32, result.size) in platform_hashes.get("crc32", set()) - ) - accepted_by = ( - set() if sha1_known or md5_known or other_known - else _platforms_accepting(review.filepath, result.filename, platform_hashes) - ) - by_profile = ( - profile_hashes.get("sha1", {}).get(result.sha1) - or profile_hashes.get("sha256", {}).get(sha256) - or profile_hashes.get("md5", {}).get(result.md5) - or profile_hashes.get("crc32", {}).get((result.crc32, result.size)) - or profile_hashes.get("crc32", {}).get((result.crc32, None)) - ) - return _Known(sha1_known, md5_known, other_known, accepted_by, by_profile, - result.filename in platform_hashes.get("names", set())) - - -def _check_executable(result: ValidationResult, sha256: str, profile_hashes: dict, ext: str) -> None: - # An executable is refused unless an emulator profile pins its exact - # bytes: PICO-8's pico8.exe and SDL2.dll are declared by sha1 from the - # official archive. A weak hash (md5, crc32) never vouches for code. - pinned = ( - profile_hashes.get("sha1", {}).get(result.sha1) - or profile_hashes.get("sha256", {}).get(sha256) - ) - if pinned: - result.add_check( - True, - f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}", - ) - else: - result.add_check(False, f"Blocked file extension: {ext}") - - -def _check_known(review: _Review, result: ValidationResult, known: _Known, too_large: bool) -> list[str] | None: - """What declares the file, and the files of a ZIP no list declares - whole, when the upload is one.""" - if known.sha1: - result.add_check(True, "SHA1 matches known platform requirement") - elif known.md5: - result.add_check(True, "MD5 matches known platform requirement") - elif known.other: - result.add_check(True, "Hash matches known platform requirement") - elif known.accepted_by: - result.add_check( - True, "Accepted by the platform's own check: " + ", ".join(sorted(known.accepted_by)) - ) - elif known.by_profile: - names = sorted(known.by_profile) - shown = ", ".join(names[:5]) + (f" and {len(names) - 5} more" if len(names) > 5 else "") - result.add_check(True, f"Hash matches a file the emulator profile declares: {shown}") - elif known.name: - result.add_warning( - "Filename matches a known requirement but hash differs - may be a variant" - ) - else: - result.outcome = "unknown" - members = None if too_large else _archive_members( - review.filepath, review.db, review.platform_hashes, review.profile_hashes - ) - _report_unknown(result, members, too_large) - return members - return None - - -def _report_unknown(result: ValidationResult, members: list[str] | None, too_large: bool) -> None: - if members is not None: - # A folder zipped to upload many files at once was hashed as one - # file and its contributor asked where that dump came from. - shown = "; ".join(members[:10]) + ( - f"; and {len(members) - 10} more" if len(members) > 10 else "" - ) - result.add_warning( - "A ZIP no platform list or emulator profile declares as a whole: " - "add the files it holds, unzipped, not the archive. Inside: " - + (shown or "nothing") - ) - else: - result.add_warning( - "Not recognised: no platform list or emulator profile declares this " - f"file. Say in the {'issue' if too_large else 'pull request'} which " - "emulator reads it, for which system, and where the dump comes from" - ) - - -def _check_bios_placement(result: ValidationResult, normalized: str, expected: list[str]) -> None: - parts = normalized.split(os.sep) - here = f"bios/{parts[1]}/{parts[2]}/" if len(parts) >= 4 else "" - makers = {folder.split("/")[1] for folder in expected} - if expected and (len(parts) < 4 or parts[1] not in makers): - # Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/. - result.add_warning( - "Placed under " + (here or "the bios/ root") + ", while the other files of " - "its system are in " + " or ".join(f"`{f}`" for f in expected) - ) - elif len(parts) >= 4: - result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/") - else: - result.add_warning("File should be in bios/Manufacturer/Console/ structure") - - -def _suggest_destination(review: _Review, result: ValidationResult, values: tuple[str, ...], - known: _Known) -> None: - # The contributor asks before forking: say where it goes. - spot = placement( - values, result.filename, review.db, review.platform_hashes, review.profile_hashes, - declared=bool(known.by_platform or known.by_profile), - ) - result.destination = spot.destination(result.sha1) - copies = f". --place copies it to `{result.destination}`" if result.destination else "" - if spot.folders: - result.add_warning( - "File is not under bios/ yet. Its system's files are in " - + " or ".join(f"`{f}`" for f in spot.folders) + copies - ) - elif spot.home: - result.add_warning( - f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`" - + copies - ) - else: - result.add_warning( - "File is not under bios/ yet. Place it in bios/Manufacturer/Console/" - ) - - -def _check_declared_size(result: ValidationResult, platform_hashes: dict, profile_hashes: dict) -> bool: - """True when the size fits every declaration of the name.""" - declared = [ - *platform_hashes.get("sizes", {}).get(result.filename, []), - *profile_hashes.get("sizes", {}).get(result.filename, []), - ] - size_fits = not declared or any(lo <= result.size <= hi for lo, hi in declared) - if not size_fits: - expected = sorted({lo if lo == hi else f"{lo:,} to {hi:,}" for lo, hi in declared}, - key=str) - shown = ", ".join(f"{v:,}" if isinstance(v, int) else v for v in expected) - result.add_warning( - f"Every declaration of {result.filename} expects {shown} bytes, " - f"this file has {result.size:,}: truncated or another file" - ) - return size_fits - - -def _note_variant(review: _Review, result: ValidationResult, normalized: str) -> None: - platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes - owners = name_systems(result.filename, platform_hashes, profile_hashes) - home = _variant_home(review.db, result.filename, "", set() if len(owners) > 1 else { - d for table in (platform_hashes, profile_hashes) for s in owners - for d in table.get("system_dirs", {}).get(s, ()) - } if owners else None) - if not home and normalized.startswith("bios" + os.sep): - # Beside the file, in the folder the contributor chose. - home = os.path.dirname(normalized).replace(os.sep, "/") + "/" - slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}" - if home and not normalized.startswith("bios" + os.sep): - result.destination = slot - if home: - result.add_info( - f"This may be a valid variant. If accepted, it will be placed in `{slot}`" - ) - else: - result.add_info("This may be a valid variant of a file the collection lacks") - - -def validate_file( - filepath: str, - db: dict | None, - platform_hashes: dict, - profile_hashes: dict | None = None, -) -> ValidationResult: - """Run all validation checks on a file.""" - result = ValidationResult(filepath) - problem = _path_problem(filepath) - if problem: - result.add_check(False, problem) - return result - - result.size = os.path.getsize(filepath) - hashes = compute_hashes(filepath) - result.sha1 = hashes["sha1"] - result.md5 = hashes["md5"] - result.crc32 = hashes["crc32"] - sha256 = hashes.get("sha256", "") - - ext = os.path.splitext(filepath)[1].lower() - too_large = _check_size(result) - relative = _relative_path(filepath) - if db: - _check_duplicate(result, db, relative) - - review = _Review(filepath, db, platform_hashes, profile_hashes or {}) - known = _identify(review, result, sha256) - if ext in BLOCKED_EXTENSIONS: - _check_executable(result, sha256, review.profile_hashes, ext) - members = _check_known(review, result, known, too_large) - - normalized = os.path.normpath(relative) - values = (result.sha1, result.md5, sha256) - if too_large: - # The file stays out of the pull request, so no folder of bios/ is - # the contributor's to choose: the release asset is placed by hand. - pass - elif normalized.startswith("bios" + os.sep): - _check_bios_placement(result, normalized, - expected_folders(values, platform_hashes, review.profile_hashes)) - elif result.outcome == "held" or members is not None: - # Nothing to place: a copy, or an archive whose files go in unzipped. - pass - else: - _suggest_destination(review, result, values, known) - - size_fits = _check_declared_size(result, platform_hashes, review.profile_hashes) - if known.name and not known.by_platform and not known.by_profile and size_fits: - _note_variant(review, result, normalized) - return result - - -def _platforms_accepting(filepath: str, filename: str, platform_hashes: dict) -> set[str]: - """Platforms whose declaration of this name accepts the file by their - own check, as verify and the pack builder read it. - - Batocera pins a ROM inside the ZIP (zipped_file), Recalbox hashes a - ZIP's members together, RomM takes any hash at the declared size: the - container's sha1 or md5 is in none of those lists, and adam_fdc.zip, - which Batocera accepts, was called an unknown variant. - """ - accepted: set[str] = set() - for entry, mode, rule, platform in platform_hashes.get("entries", {}).get( - filename.lower(), [] - ): - if platform in accepted: - continue - if entry.get("zipped_file"): - ok = inner_rom_check(entry, filepath) == "ok" - else: - algorithm = digest_algorithm(mode) - ok = bool(algorithm or rule) and frontend_digest_matches( - entry, filepath, algorithm or "", rule - ) - if ok: - accepted.add(platform) - return accepted - - -def expected_folders( - values: Iterable[str], platform_hashes: dict, profile_hashes: dict | None -) -> list[str]: - """The bios/// folders the files of a hash's - system are in, read from the first of *values* a table knows. - - A platform's declaration first, then a profile's: most files the gaps - page lists are declared by a profile alone. - """ - for table in (platform_hashes, profile_hashes or {}): - for value in values: - if value and value in table.get("folders", {}): - return sorted(table["folders"][value]) - return [] - - -@dataclass(frozen=True) -class Placement: - """Where a file not under bios/ yet goes. - - ``folders`` are those of its system, ``home`` the folder the collection - keeps its name in when its system names none. ``name`` is the name it - is copied under, empty when the declarations do not settle one. - ``variant`` says a file of that name is already in the folder: a copy - goes beside it in .variants/, never over it. - """ - - folders: tuple[str, ...] = () - home: str = "" - name: str = "" - variant: bool = False - - @property - def folder(self) -> str: - return self.folders[0] if self.folders else self.home - - def destination(self, sha1: str) -> str: - if not self.name: - return "" - if self.variant: - return f"{self.folder}.variants/{self.name}.{sha1[:8]}" - return self.folder + self.name - - -class PlacementOptions(TypedDict, total=False): - """How placement() tests a path, and the systems and directory a - declaration names.""" - - exists: Callable[[str], bool] - systems: Iterable[str] - directory: str - - -def placement( - values: Iterable[str], - filename: str, - db: dict | None, - platform_hashes: dict, - profile_hashes: dict | None, - *, - declared: bool, - **options: Unpack[PlacementOptions], -) -> Placement: - """Where a file goes, by its hashes and its name. - - The review and the site's wanted page both read this one rule, so the - folder a contributor is sent to is the folder the review accepts. - *declared* says a list or a profile declares one of the hashes: a file - known by its name alone gets a slot only once its size fits. - - Without a folder from its hashes, the folder comes from its system: - *systems*, or every system that declares the name (several of them - name no copy to sit beside). A file of that name held elsewhere is a - homonym and says nothing: AmberELEC's MSX config.ini - was sent beside msx.emu's ColecoVision config.ini. A declared - *directory* (Machines/MSX2/ for one machine's config.ini) narrows it: a - copy by name counts only in a directory of that tail, and a held - directory of that tail is the folder. - """ - exists = options.get("exists", os.path.exists) - systems = options.get("systems", ()) - directory = options.get("directory", "") - values = [value for value in values if value] - folders = expected_folders(values, platform_hashes, profile_hashes) - if folders: - names = { - name - for table in (platform_hashes, profile_hashes or {}) - for value in values - for name in table.get("named", {}).get(value, ()) - } - name = next(iter(names)) if len(names) == 1 else "" - if len(folders) == 1 and name and "/" not in name: - return Placement(tuple(folders), name=name, variant=exists(folders[0] + name)) - return Placement(tuple(folders)) - held = next((value for value in values if value in (db or {}).get("files", {})), "") - owners = set(systems) or name_systems(filename, platform_hashes, profile_hashes) - tables = (platform_hashes, profile_hashes or {}) - # A name several systems declare does not say which one a file is: - # a copy held for one of them is no answer. - dirs: set[str] = set() if not systems and len(owners) > 1 else { - d for table in tables for s in owners for d in table.get("system_dirs", {}).get(s, ()) - } - tail = _directory_tail(db, directory) - within: set[str] | None = dirs - if tail: - within = {d for d in dirs if d.endswith("/" + tail) or d == tail} if owners else None - home = _variant_home(db, filename, held, within if owners or tail else None) - if declared and home and filename and "/" not in filename: - # The folder holds a file of that name already. - return Placement(home=home, name=filename, variant=True) - if home: - return Placement(home=home) - if tail: - return Placement(home=next(d for d in _held_directories(db) if d.endswith("/" + tail) or d == tail)) - homes = {f for table in tables for s in owners for f in table.get("system_folders", {}).get(s, ())} - return Placement(tuple(sorted(homes))) - - -_HELD_DIRECTORIES: dict[int, frozenset[str]] = {} - - -def _held_directories(db: dict | None) -> frozenset[str]: - """Every directory a file of the database sits in, .variants/ aside.""" - key = id(db) - if key not in _HELD_DIRECTORIES: - _HELD_DIRECTORIES[key] = frozenset( - path.rsplit("/", 1)[0] + "/" - for record in (db or {}).get("files", {}).values() - for path in [record.get("path"), *(record.get("paths") or [])] - if path and "/" in path and "/.variants/" not in path - ) - return _HELD_DIRECTORIES[key] - - -def _directory_tail(db: dict | None, directory: str) -> str: - """The longest tail of a declared directory, two segments at least, - that exactly one held directory ends with, empty when none does.""" - parts = [p for p in directory.strip("/").split("/") if p] - held = _held_directories(db) - for size in range(len(parts), 1, -1): - tail = "/".join(parts[-size:]) + "/" - found = [d for d in held if d.endswith("/" + tail) or d == tail] - if len(found) == 1: - return tail - if found: - return "" - return "" - - -def name_systems(filename: str, platform_hashes: dict, profile_hashes: dict | None) -> set[str]: - """The systems whose platform or profile entries declare this name.""" - return { - system for table in (platform_hashes, profile_hashes or {}) - for system in table.get("name_systems", {}).get(filename.lower(), ()) - } - - -def _variant_home(db: dict | None, name: str, held: str = "", - within: set[str] | None = None) -> str: - """The folder the collection keeps a name in, for its variants beside it. - - The folder of an identical copy comes first: adam_fdc.zip, held in - bios/Coleco/Adam/, was sent to bios/Arcade/MAME/, the first folder - the name index gave. A copy found by name alone counts only in a - directory of *within*, those the file's own systems are held in, when - the systems are known. - """ - files = (db or {}).get("files", {}) - by_name = (db or {}).get("indexes", {}).get("by_name", {}).get(name, []) - copies = [(held, True)] if held in files else [] - for sha1, identical in copies + [(sha1, False) for sha1 in by_name]: - path = str(files.get(sha1, {}).get("path", "")) - folder = path.rsplit("/", 1)[0] + "/" if "/" in path else "" - if not folder or "/.variants" in "/" + folder: - continue - if identical or within is None or folder in within: - return folder - return "" - - -def _git_lines(*args: str) -> list[str] | None: - """Output lines of a git command, or None when git refuses it.""" - result = subprocess.run(["git", *args], capture_output=True, text=True, check=False) - if result.returncode != 0: - return None - return [line for line in result.stdout.splitlines() if line] - - -PROJECT_URLS = ( - "https://github.com/Abdess/retrobios", - "https://github.com/Abdess/retroarch_system", -) - - -def _repo_key(url: str) -> str: - """owner/name of a clone URL, whatever its scheme.""" - path = url.strip().rstrip("/").removesuffix(".git") - return "/".join(re.split(r"[/:]", path)[-2:]).casefold() - - -def _project_main_line() -> str | None: - """The project's main line, fetched when this clone does not hold it. - - A fork's clone has origin alone. Once the commit is pushed to the fork's - main, origin/main is HEAD and the diff against it was empty, so --changed - found nothing and exited 0. A remote added as CONTRIBUTING says and never - fetched did the same: upstream/main did not exist and origin/main won. - None leaves the upstream/ and origin/ lines in charge when the clone has - no remote at all and only its uncommitted files can be read. - """ - remotes = _git_lines("remote") or [] - if not remotes: - return None - project = {_repo_key(url) for url in PROJECT_URLS} - source = PROJECT_URLS[0] - for remote in remotes: - urls = _git_lines("remote", "get-url", "--all", remote) or [] - if any(_repo_key(url) in project for url in urls): - if _git_lines("rev-parse", "--verify", "--quiet", f"{remote}/main"): - return f"{remote}/main" - source = remote - break - fetched = subprocess.run( - ["git", "fetch", "--quiet", "--no-tags", source, "main"], - capture_output=True, text=True, check=False, - ) - if fetched.returncode != 0: - raise RuntimeError( - f"this clone does not hold the main of {PROJECT_URLS[0]}, and " - f"fetching its main from {source} failed: {fetched.stderr.strip()}" - ) - return "FETCH_HEAD" - def get_changed_files() -> list[str]: """BIOS files this checkout changes against the project's main line. diff --git a/scripts/verify.py b/scripts/verify.py index 4cf96cd44..528931308 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -25,28 +25,14 @@ from __future__ import annotations import argparse import contextlib -import functools import json import os import sys -from collections import Counter -from collections.abc import Callable, Mapping -from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, TypedDict +from typing import TYPE_CHECKING -import slots sys.path.insert(0, os.path.dirname(__file__)) -from core.hashing import parse_md5_list -from model.alternatives import ( - core_file_spares, - set_fields, - set_keys, - set_requirements, - settle_sets, - slot_set_keys, -) from resolve.contentlayout import TARGET_KEY from model.targets import ( canonical_target_name, @@ -54,9 +40,6 @@ from model.targets import ( list_available_targets, build_target_cores_cache, ) -from model.declarations import OUTER_ROOTS -from resolve.layout import runs_standalone, system_dir_path -from resolve.ownership import _foreign_tree, _owner_tokens from model.cliargs import ( platform_arg, work_from_repo_root, @@ -66,23 +49,11 @@ from model.cliargs import ( list_system_ids, print_platform_listing, ) -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.systems import resolve_system_arg from model.profiles import ( - profiles_for_systems, - PROFILE_IDENTITY_FIELDS, load_emulator_profiles, - ProfileSelectionError, - entry_serves_systems, - entry_system_ids, - select_emulator_profiles, ) 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 @@ -90,3271 +61,52 @@ 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 REPO_ROOT, sanitize_pack_path -from resolve.categories import BIOS, EntryCategories -from resolve.launchers import LauncherLayer, declared_destinations, held_record, launcher_unproven -from cross_reference import launcher_reads_not_held -from resolve.nativemode import ( - SIZE_AND_ANY_HASH, - digest_algorithm, - hash_mismatch_excludes_file, - normalize as normalize_mode, - reads_file_contents, -) -from resolve.validation import ( - baseline_verdict, - case_folded_slots, - declaration_settles, - frontend_digest_matches, - existence_discrepancy, - destination_owners, - validated_choice, - agnostic_substitute, - _build_validation_index, - _parse_validation, - build_ground_truth, - check_file_validation, - deliverable, - installed_with_emulator, - unread_on, - outside_gap_scope, - read_from_save_dir, - with_archive_members, - core_size_refusal, - same_slot_entries, -) -from packpaths import core_save_folder if TYPE_CHECKING: - from typing_extensions import Unpack - from packextras import ExtraResolver + pass +from packs.coverage import verify_platform +from packs.emulatorcheck import verify_emulator, verify_system +from packs.report import ( + _NOT_FIRMWARE, + _core_required_missing, + _discrepancy_keys, + _split_undeclared, + print_emulator_result, + print_platform_result, +) +from packs.verdicts import DEFAULT_EMULATORS_DIR, Severity, Status yaml = require_yaml() DEFAULT_DB = "database.json" DEFAULT_PLATFORMS_DIR = "platforms" -DEFAULT_BIOS_DIR = "bios" -# The repository's platforms wherever the script runs from, for library calls -# that pass no directory. -_REPO_PLATFORMS = str(REPO_ROOT / "platforms") -DEFAULT_EMULATORS_DIR = "emulators" # Status model: aligned with Batocera BiosStatus (batocera-systems:967-969) -class Status: - OK = "ok" - UNTESTED = "untested" # file present, hash not confirmed: a warning, never --strict - MISSING = "missing" - - -# A declaration whose file is a release asset the cache does not hold yet: -# an online build fetches it, verify reads the database record instead. -RELEASE_ASSET_PENDING = "release_asset_pending" - - -class Severity: - CRITICAL = "critical" # required file missing or bad hash (Recalbox RED) - WARNING = "warning" # optional missing or hash mismatch (Recalbox YELLOW) - INFO = "info" # optional missing on existence-only platform - OK = "ok" # file verified - - -_STATUS_ORDER = {Status.OK: 0, Status.UNTESTED: 1, Status.MISSING: 2} -_SEVERITY_ORDER = { - Severity.OK: 0, - Severity.INFO: 1, - Severity.WARNING: 2, - Severity.CRITICAL: 3, -} - - # Verification functions -def verify_entry_existence( - file_entry: dict, - local_path: str | None, - validation_index: dict[str, dict] | None = None, - db: dict | None = None, - destination: str = "", - owners: dict | None = None, - resolve_status: str = "", - platform_display: str = "", -) -> dict: - """RetroArch verification: path_is_valid(), a file that exists is OK. - The result names the collection file found, as the hash modes do.""" - name = file_entry.get("name", "") - required = file_entry.get("required", True) - if not local_path: - return {"name": name, "status": Status.MISSING, "required": required} - result = {"name": name, "status": Status.OK, "required": required, "path": local_path} - if resolve_status == "hash_mismatch": - # The frontend reads no bytes, so the file stays, and the declared hash - # it contradicts is reported, as the pack does. - result["discrepancy"] = existence_discrepancy( - file_entry, local_path, platform_display - ) - return result - if not validation_index: - return result - if db: - # The pack ships the variant this returns, so a disagreement it - # settles is not reported. - _chosen, disagreement = validated_choice( - file_entry, local_path, db, validation_index, "bios", None, - destination, owners, - ) - else: - check = check_file_validation(local_path, name, validation_index) - disagreement = f"{', '.join(check[1])} says {check[0]}" if check else None - if disagreement: - result["discrepancy"] = f"file present (OK) but {disagreement}" - return result - - -def _verify_zipped_md5( - base: dict, local_path: str, zipped_file: str, md5_list: list[str], -) -> dict: - """The md5 check of an entry naming the ROM inside its ZIP (zipped_file).""" - found_in_zip = False - had_error = False - for md5_candidate in md5_list or [""]: - result = check_inside_zip(local_path, zipped_file, md5_candidate) - if result == Status.OK: - return {**base, "status": Status.OK, "path": local_path} - if result == "error": - had_error = True - elif result != "not_in_zip": - found_in_zip = True - if had_error and not found_in_zip: - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"{local_path} read error", - } - if not found_in_zip: - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"{zipped_file} not found inside ZIP", - } - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"{zipped_file} MD5 mismatch inside ZIP", - } - - -def verify_entry_md5( - file_entry: dict, - local_path: str | None, - resolve_status: str = "", - hash_rule: str = "", -) -> dict: - """MD5 verification -Batocera md5sum + Recalbox multi-hash + Md5Composite. - - Under SIZE_AND_ANY_HASH (RomM) the size and any one declared hash decide. - """ - name = file_entry.get("name", "") - expected_md5 = file_entry.get("md5", "") - zipped_file = file_entry.get("zipped_file") - required = file_entry.get("required", True) - base = {"name": name, "required": required} - - # One parse for verify, the builder and the pack check: Recalbox writes - # md5 in uppercase, and a copy that lowercased only comma lists judged - # a single uppercase value differently from the others. - md5_list = parse_md5_list(expected_md5) - - if not local_path: - return {**base, "status": Status.MISSING} - - if hash_rule == SIZE_AND_ANY_HASH: - if frontend_digest_matches(file_entry, local_path, "md5", hash_rule): - return {**base, "status": Status.OK, "path": local_path} - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": "the declared size and at least one declared hash must match", - } - - if zipped_file: - return _verify_zipped_md5(base, local_path, zipped_file, md5_list) - - if not md5_list: - if resolve_status == "hash_mismatch": - # No md5 to compare does not mean nothing was compared: the entry - # declares a sha1 or a crc32 the local file contradicts, and the - # builder drops it for exactly that. Reporting OK here said the - # collection holds bytes it does not. - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": "declared hash contradicted by the local file", - } - return {**base, "status": Status.OK, "path": local_path} - - if resolve_status == "md5_exact": - return {**base, "status": Status.OK, "path": local_path} - - # The builder's comparison, so the two count the same files as held. - if frontend_digest_matches(file_entry, local_path, "md5"): - return {**base, "status": Status.OK, "path": local_path} - actual_md5 = md5sum(local_path) - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"expected {md5_list[0][:12]}... got {actual_md5[:12]}...", - } - - -def verify_entry_sha1( - file_entry: dict, - local_path: str | None, -) -> dict: - """SHA1 verification -BizHawk firmware hash check.""" - name = file_entry.get("name", "") - expected_sha1 = file_entry.get("sha1", "") - required = file_entry.get("required", True) - base = {"name": name, "required": required} - - if not local_path: - return {**base, "status": Status.MISSING} - - if not expected_sha1: - return {**base, "status": Status.OK, "path": local_path} - - hashes = compute_hashes(local_path) - actual_sha1 = hashes["sha1"].lower() - if actual_sha1 == expected_sha1.lower(): - return {**base, "status": Status.OK, "path": local_path} - - return { - **base, - "status": Status.UNTESTED, - "path": local_path, - "reason": f"expected {expected_sha1[:12]}... got {actual_sha1[:12]}...", - } - - # Severity mapping per platform -def _emulator_severity(status: str, required: bool, hle_fallback: bool) -> str: - """Severity when the emulator's own code is the check. - - A file present but refused by the core's validation, or a different dump - than the one the profile declares, is not a file the core runs with: - read in existence mode it counted OK, and `verify --emulator` announced - 1/1 OK above the line that said the core would refuse it. - """ - if status == Status.UNTESTED: - return Severity.WARNING - return compute_severity(status, required, "existence", hle_fallback) - - -def compute_severity( - status: str, - required: bool, - mode: str, - hle_fallback: bool = False, -) -> str: - """Map (status, required, verification_mode, hle_fallback) -> severity. - - Based on native platform behavior + emulator HLE capability: - - RetroArch (existence): required+missing = warning, optional+missing = info - - Batocera/Recalbox/RetroBat/EmuDeck (md5): hash-based verification - - BizHawk (sha1): same severity rules as md5 - - hle_fallback: core works without this file via HLE -> always INFO when missing - """ - if status == Status.OK: - return Severity.OK - - # HLE fallback: core works without this file regardless of platform requirement - if hle_fallback and status == Status.MISSING: - return Severity.INFO - - if not reads_file_contents(mode): - if status == Status.MISSING: - return Severity.WARNING if required else Severity.INFO - return Severity.OK - - # md5 mode (Batocera, Recalbox, RetroBat, EmuDeck) - if status == Status.MISSING: - return Severity.CRITICAL if required else Severity.WARNING - if status == Status.UNTESTED: - return Severity.WARNING - return Severity.OK - - # Cross-reference: undeclared files used by cores -def _build_expected(file_entry: dict, checks: list[str]) -> dict: - """Extract expected validation values from an emulator profile file entry.""" - expected: dict = {} - if not checks: - return expected - if "size" in checks: - for key in ("size", "min_size", "max_size", "size_multiple"): - if file_entry.get(key) is not None: - expected[key] = file_entry[key] - for hash_type in ("crc32", "md5", "sha1", "sha256"): - if hash_type in checks and file_entry.get(hash_type): - expected[hash_type] = file_entry[hash_type] - adler_val = file_entry.get("known_hash_adler32") or file_entry.get("adler32") - if adler_val: - expected["adler32"] = adler_val - return expected - - -def _in_foreign_tree(db: dict, owners: set[str], sha1: str) -> bool: - """Whether the collection keeps this sha1 in another emulator's tree.""" - return _foreign_tree(db.get("files", {}).get(sha1, {}).get("path", ""), owners) - - -def _name_in_index( - name: str, - by_name: dict, - by_path_suffix: dict | None = None, - data_names: set[str] | None = None, - by_name_lower: dict[str, str] | None = None, - foreign: Callable[[str], bool] | None = None, -) -> bool: - """Check if a name is resolvable in the database indexes or data directories. - - *foreign* tells a copy in another emulator's tree from the sha1 of a - name: matched in another casing, such a copy is not the asker's, as in - resolve_local_file's case-insensitive step. - """ - # Strip trailing slash for directory-type entries (e.g. nestopia/samples/foo/) - name = name.rstrip("/") - if name in by_name: - return True - basename = name.rsplit("/", 1)[-1] if "/" in name else name - if basename != name and basename in by_name: - return True - if by_name_lower: - for key in {name.lower(), basename.lower()}: - if key in by_name_lower and not ( - foreign and all(foreign(s) for s in by_name[by_name_lower[key]]) - ): - return True - if by_path_suffix and name in by_path_suffix: - return True - if data_names: - if name in data_names or name.lower() in data_names: - return True - if basename != name and ( - basename in data_names or basename.lower() in data_names - ): - return True - return False - - -def _candidate_verdict( - file_entry: dict, - fname: str, - is_standalone: bool, - include_all: bool, - declared_names: Mapping[str, list[tuple[int | None, str]]] | set[str], - dest: str = "", - folded_slots: frozenset[str] = frozenset(), - declared_contents: Mapping[str, set[str]] | None = None, -) -> str: - """Whether a profile entry can be a gap, and whether it is settled. - - Three answers. "keep" means it is a candidate. "settled" means something - has answered for it (the platform declares it, or the profile documents - it as unsourceable), so the same requirement reached from another profile - must not be reconsidered. "skip" means it does not apply in this context, - which leaves it open for a profile where it does: the same file can be - libretro-only here and standalone-only there. - """ - if file_entry.get("unsourceable"): - return "settled" - if outside_gap_scope(file_entry, is_standalone): - return "skip" - if not include_all and declaration_settles( - file_entry, fname, declared_names, dest, folded_slots, declared_contents - ): - return "settled" - return "keep" - - -def _identity_of(entry: dict) -> dict: - """The fields that tell a profile's file apart from a same-named one.""" - return { - field: entry.get(field) - for field in PROFILE_IDENTITY_FIELDS - if entry.get(field) not in (None, "", []) - } - - -def _gap_destination(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: - """The destination a gap entry is keyed and reported at.""" - # One destination rule for the dedup key and for the entry: a - # standalone build without standalone_path falls back on path. - # The key used to skip that fallback, so clk's Acorn/basic.rom and - # Electron/basic.rom both keyed as "basic.rom" under Batocera's - # standalone clk and the second was dropped. - # A file the libretro build reads below the save directory is - # placed there, apart from the system directory the platform - # lays out: no declaration of the BIOS tree answers for it. - if is_standalone: - return f.get("standalone_path") or f.get("path") or fname - if save_root: - return f.get("path") or fname - return system_dir_path(f, f.get("path") or fname) - - -def _region_key(f: dict) -> tuple[str, ...]: - raw_regions = f.get("region") or [] - return tuple( - str(value) for value in ( - raw_regions if isinstance(raw_regions, list) else [raw_regions] - ) - ) - - -SetRecord = tuple[tuple, dict, bool, "tuple[dict, dict | None] | None"] - - -@dataclass -class _GapScan: - """What find_undeclared_files reads and gathers while it walks the cores.""" - - config: dict - db: dict - data_names: set[str] | None - include_all: bool - declared_names: Mapping[str, list[tuple[int | None, str]]] - folded_slots: frozenset[str] - declared_contents: Mapping[str, set[str]] - # Whether the builder drops a file whose local copy contradicts its - # declared hash, which decides if such a copy counts as held here. - shipped_on_mismatch: bool - launcher_layer: LauncherLayer - by_name: dict = field(init=False) - by_name_lower: dict[str, str] = field(init=False) - by_path_suffix: dict = field(init=False) - launcher_candidates: list[tuple[str, bool, dict, dict]] = field(default_factory=list) - # Each grouped requirement met, as (set keys, entry, fills, (reported - # entry, the entry it is a claim on)): settled once every core is read. - set_records: list[SetRecord] = field(default_factory=list) - undeclared: list[dict] = field(default_factory=list) - seen_files: set[tuple] = field(default_factory=set) - # Key -> the entry reported for it. A later profile reading the same - # requirement is kept on that entry rather than counted again: a pack - # built without the first profile still has to name the file. - reported: dict[tuple, dict] = field(default_factory=dict) - # Track archives: archive_name -> {in_repo, emulator, files: [...], ...} - archive_entries: dict[tuple, dict] = field(default_factory=dict) - - def __post_init__(self) -> None: - self.by_name = self.db.get("indexes", {}).get("by_name", {}) - self.by_name_lower = {k.lower(): k for k in self.by_name} - self.by_path_suffix = self.db.get("indexes", {}).get("by_path_suffix", {}) - - def scan_file(self, emu_name: str, layout: dict, is_standalone: bool, f: dict) -> None: - """Consider one profile entry of one build as a gap.""" - fname = f.get("name", "") - save_root = read_from_save_dir(f, is_standalone) - dest = _gap_destination(f, fname, is_standalone, save_root) - region_key = _region_key(f) - # Same-name requirements at different paths, for different systems, - # or in distinct variant groups are not interchangeable. - seen_key = ( - fname, - f.get("archive"), - dest, - f.get("system"), - f.get("selection_slot"), - region_key, - # Below the save directory each core is handed a folder - # of its own: two cores reading hiscore.dat there read - # two files. - ("save", core_save_folder(layout)) if save_root - else (f["root"],) if f.get("root") in OUTER_ROOTS - # In the emulator's own folder: no other core reads it. - else ("emulator", emu_name) if f.get("unplaced") else None, - ) - config = self.config - if not fname or unread_on(f, config.get("_key", "")): - return - first = self.reported.get(seen_key) - duplicate = seen_key in self.seen_files - if duplicate and (first is None or first["profile"] == emu_name): - return - outer = save_root or f.get("root") in OUTER_ROOTS - # Nor does it answer for one read below the roms directory. - verdict = _candidate_verdict( - f, fname, is_standalone, self.include_all, - {} if outer else self.declared_names, - dest, self.folded_slots, - None if outer else self.declared_contents, - ) - if verdict == "settled": - self.seen_files.add(seen_key) - if (self.launcher_layer and not f.get("unsourceable") and not outer - and not f.get("unplaced")): - self.launcher_layer.declared_elsewhere(emu_name, is_standalone, f) - # Answered by the platform's own declaration, which its - # report covers: the set it belongs to is spoken for. - self.set_records.append((set_keys((emu_name, is_standalone), f), f, True, None)) - return - if verdict == "skip": - return - - archive = f.get("archive") - self.seen_files.add(seen_key) - - if archive: - self._count_archive_member(emu_name, layout, is_standalone, f, region_key) - return - - in_repo = self._held(emu_name, layout, f, fname, dest) - entry = self._gap_entry(emu_name, layout, f, fname, dest, in_repo, save_root) - if self.launcher_layer and not outer: - # One read outside the BIOS tree is still served where a - # launcher links that very file: RetroDECK links Cemu's - # keys.txt to bios/cemu/keys.txt. - self.launcher_candidates.append((emu_name, is_standalone, f, entry)) - keys = set_keys((emu_name, is_standalone), f) - if duplicate and first is not None: - first.setdefault("other_claims", []).append(entry) - self.set_records.append((keys, f, in_repo, (entry, first))) - return - self.reported[seen_key] = entry - self.undeclared.append(entry) - self.set_records.append((keys, f, in_repo, (entry, None))) - - def _count_archive_member( - self, emu_name: str, layout: dict, is_standalone: bool, f: dict, - region_key: tuple[str, ...], - ) -> None: - archive = f["archive"] - archive_key = ( - archive, - f.get("system_dir"), - f.get("system"), - f.get("selection_slot"), - region_key, - is_standalone, - ) - if archive_key not in self.archive_entries: - in_repo = _name_in_index( - archive, self.by_name, self.by_path_suffix, self.data_names, - self.by_name_lower, - ) - self.archive_entries[archive_key] = { - "profile": emu_name, - "emulator": layout.get("emulator", emu_name), - "systems": entry_system_ids(f, layout), - "system": f.get("system"), - "region": f.get("region"), - "selection_slot": f.get("selection_slot"), - "name": archive, - "archive": archive, - "path": system_dir_path(f, archive), - "required": False, - "hle_fallback": False, - "category": f.get("category", "bios"), - "in_repo": in_repo, - "note": "", - "checks": [], - "source_ref": None, - "expected": {}, - "archive_file_count": 0, - "archive_required_count": 0, - "members": archive_members(archive, layout.get("files", [])), - } - if f.get("system_dir"): - self.archive_entries[archive_key]["system_dir"] = f["system_dir"] - # The archive's own declaration names its sets: an - # archive is a member like a loose file. - own = archive_entry(archive, layout.get("files", [])) - self.archive_entries[archive_key].update(set_fields(own, layout)) - self.set_records.append(( - set_keys((emu_name, is_standalone), own), own, in_repo, - (self.archive_entries[archive_key], None), - )) - entry = self.archive_entries[archive_key] - entry["archive_file_count"] += 1 - if f.get("required", False): - entry["archive_required_count"] += 1 - entry["required"] = True - - def _held(self, emu_name: str, layout: dict, f: dict, fname: str, dest: str) -> bool: - """Whether the collection holds the file as the builder would ship it.""" - # Resolution: name, then path basename - # storage: release names where the bytes are served from, not - # that the collection holds them: resolved like any file. - # Resolved as the asker, as the builder's ExtraResolver does: - # another casing of the name in another emulator's tree is - # not this emulator's file (dosbox-x's et4000.bin and pcem's - # et4000.BIN). - owned = {**f, "source_profile": emu_name} - if self.shipped_on_mismatch and (f.get("md5") or f.get("sha1")): - # The entry states what its content should be and the builder - # drops a copy that contradicts it, so content decides here - # too. A name match would not do: generic names collide across - # systems, and answering yes on one describes a pack that will - # not contain the file. - _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) - return _lp is not None and _st != "hash_mismatch" - in_repo = self._held_by_name(owned, f, fname, dest) - if in_repo and "size" in _parse_validation(f.get("validation")): - # On any platform the core measures what it opens: a - # copy it turns away by its own size check is not - # held for it, the rule the builder's lookup applies - # (packextras.ExtraResolver). The Apple IIGS' 128 KB - # ROM is not Basilisk II's ROM. - _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) - if core_size_refusal( - f, _lp, same_slot_entries(layout.get("files"), fname, dest) - ): - in_repo = False - return in_repo - - def _held_by_name(self, owned: dict, f: dict, fname: str, dest: str) -> bool: - foreign = functools.partial(_in_foreign_tree, self.db, _owner_tokens(owned)) - in_repo = _name_in_index( - fname, self.by_name, self.by_path_suffix, self.data_names, self.by_name_lower, - foreign, - ) - if not in_repo and dest != fname: - path_base = dest.rsplit("/", 1)[-1] - in_repo = _name_in_index( - path_base, self.by_name, self.by_path_suffix, self.data_names, - self.by_name_lower, foreign, - ) - if in_repo and not any( - f.get(h) for h in ("sha1", "md5", "crc32", "sha256") - ): - # A name alone answers nothing when every copy of that - # name fails the size the code checks: the resolver - # rejects them all. NanoBoyAdvance's 16 KB bios.bin met - # only PCem's and QEMU's PC BIOS images of that name. - # The fallback below then decides as for any mismatch. - _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) - if _st == "hash_mismatch": - in_repo = False - if not in_repo: - # Hash fallback: the repo may hold the content under a - # different filename (exos21.rom vs exos21.bin). - # - # A copy contradicting the declared hash counts as held - # only where the builder would ship it. Under existence - # the frontend never opens the file, so the pack carries - # it and reports the divergence. Under a digest mode the - # frontend would reject it, the builder leaves it out, and - # calling it available here would describe a pack that - # does not contain it. - _lp, _st = resolve_local_file(owned, self.db, dest_hint=dest) - in_repo = _st != "not_found" and _lp is not None - if in_repo and _st == "hash_mismatch" and self.shipped_on_mismatch: - in_repo = False - return in_repo - - def _gap_entry( - self, emu_name: str, layout: dict, f: dict, fname: str, dest: str, - in_repo: bool, save_root: bool, - ) -> dict: - checks = _parse_validation(f.get("validation")) - entry = { - "profile": emu_name, - "emulator": layout.get("emulator", emu_name), - "systems": entry_system_ids(f, layout), - "system": f.get("system"), - "region": f.get("region"), - "selection_slot": f.get("selection_slot"), - "name": fname, - "path": dest, - "required": f.get("required", False), - "hle_fallback": f.get("hle_fallback", False), - "bundled": installed_with_emulator(f, self.config.get("_key", "")), - "category": f.get("category", "bios"), - "in_repo": in_repo, - "note": f.get("note", ""), - "checks": sorted(checks) if checks else [], - **set_fields(f, layout), - "source_ref": f.get("source_ref"), - "expected": _build_expected(f, checks), - **_identity_of(f), - "sha1": f.get("sha1"), - "md5": f.get("md5"), - } - if f.get("contents"): - entry["contents"] = f["contents"] - if save_root: - entry["root"] = "save" - folder = core_save_folder(layout) - if folder is not None: - entry["core_folder"] = folder - elif f.get("system_dir"): - entry["system_dir"] = f["system_dir"] - members = with_archive_members(f, layout.get("files", [])).get("members") - if members: - entry["members"] = members - if f.get("layout_path"): - entry["layout_path"] = f["layout_path"] - if f.get("unprefixed"): - entry["unprefixed"] = True - if f.get("unplaced"): - entry["unplaced"] = f["unplaced"] - elif f.get("root") in OUTER_ROOTS: - # Read below the roms directory (ROCKNIX's roms/pico-8) - # or in an emulator folder (RetroBat's emulators/pico8). - entry["root"] = f["root"] - return entry - - -def find_undeclared_files( - config: dict, - emulators_dir: str, - db: dict, - emu_profiles: dict | None = None, - target_cores: set[str] | None = None, - data_names: set[str] | None = None, - include_all: bool = False, - declared_names: Mapping[str, list[tuple[int | None, str]]] | None = None, -) -> list[dict]: - """Find files needed by cores but not declared in platform config. - - declared_names overrides the default enriched declarations from - platform_declarations. Pass the strict ones (YAML names only) when - building packs so alias-only names still get packed. - """ - if declared_names is None: - declared_names = platform_declarations(config, db) - folded_slots = case_folded_slots(config, declared_names) - declared_contents = platform_declared_contents(config, db) - - profiles = ( - emu_profiles - if emu_profiles is not None - else load_emulator_profiles(emulators_dir) - ) - - relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) - standalone_set = platform_standalone_set(config) - # What the platform's own launchers open, matched to the cores it runs: - # the one decision the builder and this report both read. - launcher_layer = LauncherLayer( - config, profiles, relevant, db, declared_destinations(config) - ) - scan = _GapScan( - config, db, data_names, include_all, declared_names, folded_slots, - declared_contents, - hash_mismatch_excludes_file(config.get("verification_mode")), - launcher_layer, - ) - - for emu_name, profile in sorted(profiles.items()): - if profile.get("type") in ("launcher", "alias"): - continue - if emu_name not in relevant: - continue - - # A filename-agnostic profile is served by the scan (packextras), all - # but the entries its layout reads outside the BIOS tree: those are - # named here, or a launcher folder drops them without a word - # (ARMSX2's arcade/proverb.zip once ROCKNIX binds bios/armsx2). - agnostic = profile.get("bios_mode") == "agnostic" - - for layout, is_standalone in platform_layouts(emu_name, profile, standalone_set): - for f in expand_directory_entries( - layout.get("files", []), db, is_standalone - ): - if agnostic and not f.get("unplaced"): - continue - scan.scan_file(emu_name, layout, is_standalone, f) - - undeclared = scan.undeclared - settled: set[int] = set() - if launcher_layer: - added, settled = launcher_layer.settle( - scan.launcher_candidates, lambda report: held_record(report, db) - ) - undeclared = [u for u in undeclared if id(u) not in settled] - undeclared.extend(added) - - undeclared.extend(sorted(scan.archive_entries.values(), key=lambda e: e["name"])) - - return _split_bundled_claims( - _settle_core_sets(undeclared, scan.set_records, settled, profiles) - ) - - -def _split_bundled_claims(undeclared: list[dict]) -> list[dict]: - """A file one emulator installs itself, another reads from the pack. - - The first profile reading a requirement hosts the claims of the others, - and a host installed with its emulator is left out of the pack with all - of them: DraStic brings its own usrcheat.dat, and ROCKNIX's DSPerate, - which reads the same file, lost it wherever DraStic runs too. Built for - a board without DraStic, the pack carried it. - """ - out: list[dict] = [] - for entry in undeclared: - claims = entry.get("other_claims") or [] - rest = [c for c in claims if not c.get("bundled")] - if not entry.get("bundled") or not rest: - out.append(entry) - continue - own = [c for c in claims if c.get("bundled")] - kept = {k: v for k, v in entry.items() if k != "other_claims"} - if own: - kept["other_claims"] = own - promoted = dict(rest[0]) - if rest[1:]: - promoted["other_claims"] = rest[1:] - out += [kept, promoted] - return out - - -def _settle_core_sets( - undeclared: list[dict], - records: list[tuple[tuple, dict, bool, tuple[dict, dict | None] | None]], - launcher_settled: set[int], - profiles: dict[str, dict], -) -> list[dict]: - """The core complement with each set of alternatives settled. - - A member the collection lacks is dropped when another member is held, - declared by the platform or placed by its launcher, and a set nobody - holds keeps one entry, its first member, naming the others. A claim - another profile shares stays: its own core may need that very file. - """ - # Archive units rank first among equals, as the builder orders them. - grouped = sorted( - (r for r in records if r[0]), - key=lambda r: not (r[3] is not None and r[3][0].get("archive")), - ) - if not grouped: - return undeclared - excused, standing = settle_sets([ - (keys, f, fills or (ref is not None and id(ref[0]) in launcher_settled)) - for keys, f, fills, ref in grouped - ], lambda key: set_requirements(profiles.get(key[0][0], {})).get(key[1], True)) - declared_sets = { - key for keys, _f, _fills, ref in grouped if ref is None for key in keys - } - dropped: set[int] = set() - for position, (keys, _f, _fills, ref) in enumerate(grouped): - if ref is None: - continue - entry, host = ref - required_keys = [k for k in keys if k[1] in entry.get("required_groups", ())] - if required_keys and all(k in declared_sets for k in required_keys): - # The platform declares a member of each of its required sets: - # under --required-only that declaration carries them. - entry["set_declared"] = True - if position in standing: - entry["alternatives"] = standing[position].others - entry["required"] = standing[position].required - if position not in excused: - continue - if host is not None: - host["other_claims"] = [c for c in host.get("other_claims", []) if c is not entry] - if not host["other_claims"]: - del host["other_claims"] - else: - dropped.add(id(entry)) - out: list[dict] = [] - for entry in undeclared: - if id(entry) not in dropped: - out.append(entry) - continue - # Another core reading the same requirement still needs it. - claims = entry.get("other_claims") or [] - if claims: - promoted = dict(claims[0]) - if claims[1:]: - promoted["other_claims"] = claims[1:] - out.append(promoted) - return out - - -def find_exclusion_notes( - config: dict, - emulators_dir: str, - emu_profiles: dict | None = None, - target_cores: set[str] | None = None, -) -> list[dict]: - """Document why certain emulator files are intentionally excluded. - - Reports: - - Launchers (BIOS managed by standalone emulator) - - Standalone-only files (not needed in libretro mode) - - Frozen snapshots with files: [] (code doesn't load .info firmware) - - Files covered by data_directories - """ - profiles = ( - emu_profiles - if emu_profiles is not None - else load_emulator_profiles(emulators_dir) - ) - platform_systems = set() - for sys_id in config.get("systems", {}): - platform_systems.add(sys_id) - - relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) - notes = [] - for emu_name, profile in sorted(profiles.items()): - emu_systems = set(profile.get("systems", [])) - # Match by core resolution OR system intersection (documents all potential emulators) - if emu_name not in relevant and not (emu_systems & platform_systems): - continue - - emu_display = profile.get("emulator", emu_name) - - if profile.get("type") == "launcher": - notes.append( - { - "emulator": emu_display, - "reason": "launcher", - "detail": profile.get( - "exclusion_note", "BIOS managed by standalone emulator" - ), - } - ) - continue - - # Profile-level exclusion note (frozen snapshots, etc.) - exclusion_note = profile.get("exclusion_note") - if exclusion_note: - notes.append( - { - "emulator": emu_display, - "reason": "exclusion_note", - "detail": exclusion_note, - } - ) - continue - - # Count standalone-only files, but only report as excluded if the - # platform does NOT use this emulator in standalone mode - standalone_set = platform_standalone_set(config) - is_standalone = runs_standalone(emu_name, profile, standalone_set) - if not is_standalone: - standalone_files = [ - f for f in profile.get("files", []) if f.get("mode") == "standalone" - ] - if standalone_files: - names = [f["name"] for f in standalone_files[:3]] - more = ( - f" +{len(standalone_files) - 3}" - if len(standalone_files) > 3 - else "" - ) - notes.append( - { - "emulator": emu_display, - "reason": "standalone_only", - "detail": f"{len(standalone_files)} files for standalone mode only ({', '.join(names)}{more})", - } - ) - - return notes - - # Platform verification -_UNPLACED_REASONS = { - "outside_bios_folder": "read in a folder the platform keeps outside the BIOS tree", - "no_roms_directory": "read below a roms folder the platform's registry does not name", - "no_emulators_directory": "read in an emulator folder the platform's registry does not describe", - "no_configs_directory": "read below a configs folder the platform's file does not record", - "no_platform_slug": "no platform slug for its system", - "below_platform_folder": "below the folder the platform lists", - "no_save_directory": "read below a save directory the platform keeps in no fixed place", - "no_core_folder": "read below the save directory and the profile names no library_name", - "no_save_system": "read below a save folder per system and no system runs the core there", -} - - -def _mark_unplaced(config: dict, undeclared: list[dict], profiles: dict) -> None: - """What the builder cannot place is not in the pack, held or not.""" - from packextras import unplaceable_extras - - unplaced = unplaceable_extras(config, undeclared, profiles) - for u in undeclared: - if u.get("bundled"): - # Installed with the emulator, so already on the user's machine: - # the pack leaves it out, held or not. - u["in_pack"] = False - u["omitted"] = "installed with its emulator" - continue - reason = unplaced.get( - (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") - ) - if not reason and u.get("root") in OUTER_ROOTS: - # The pack is extracted into the BIOS folder: the installer - # writes this file into the roms or emulator folder, the pack - # cannot. - u["in_pack"] = False - u["omitted"] = f"read below the {u['root']} folder, which only the installer reaches" - continue - if reason: - u["in_pack"] = False - u["omitted"] = _UNPLACED_REASONS[reason] - - -def _storage_verdict(file_entry: dict, emulator_pack: bool) -> dict | None: - """The result a storage tier fixes before any lookup, as the builder sees it. - - A user_provided entry is never taken from the collection: a platform pack - writes its instructions in the slot and counts it filled, an emulator pack - lists it to provide. An external one is fetched from its URL when the pack - is built, never read from bios/. Resolving either by name credited a - same-named file the pack does not carry. - """ - storage = file_entry.get("storage", "embedded") - base = {"name": file_entry.get("name", ""), "required": file_entry.get("required", True)} - if storage == "user_provided": - if emulator_pack: - stated = file_entry.get("unsourceable") - why = ( - stated if isinstance(stated, str) and stated - else file_entry.get("instructions") or "the user provides it" - ) - return {**base, "status": Status.MISSING, "unsourceable": why} - return {**base, "status": Status.OK, "user_provided": True} - if storage == "external": - return {**base, "status": Status.MISSING, "reason": "fetched from its URL when the pack is built"} - return None - - -_HIDDEN_REASONS = { - "case_twin": "a packed file of the same name in another case takes its place", - "path_conflict": "a packed file occupies its directory", -} - - -@dataclass(frozen=True) -class _BuilderPass: - """The arguments the builder's own pass over the core files is run with.""" - - emulators_dir: str - db: dict - emu_profiles: dict | None - target_cores: set[str] | None - region_drops: set[str] | None - report: list[dict] | None - resolver: ExtraResolver | None - placed_kind: dict[str, str] | None - system_ids: list[str] | None - required_only: bool - - -def _mark_hidden( - config: dict, - undeclared: list[dict], - shipped: dict[str, str | None], - builder: _BuilderPass, -) -> set[str]: - """What the builder holds but cannot place beside the files it packed. - - Returns the full destinations the builder fills with a core's file. - ``builder.report`` is the gap report the caller already computed with the - builder's arguments. Without it the builder's pass computes its own. - """ - from packextras import hidden_extras - - placed: set[str] = set() - hidden = hidden_extras( - config, builder.emulators_dir, builder.db, - builder.emu_profiles if builder.emu_profiles is not None - else load_emulator_profiles(builder.emulators_dir), - shipped, builder.target_cores, builder.region_drops, placed, - report=builder.report, resolver=builder.resolver, placed_kind=builder.placed_kind, - system_ids=builder.system_ids, required_only=builder.required_only, - ) - for u in undeclared: - reason = hidden.get( - (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") - ) - if reason and u.get("in_repo") and u.get("in_pack", True): - u["in_pack"] = False - u["omitted"] = _HIDDEN_REASONS[reason] - return placed - - -def _builder_placement( - packed_order: list[tuple[str, str, str | None]], case_insensitive: bool, -) -> tuple[dict[str, str], dict[str, str | None]]: - """The platform files the builder writes, and every path it keeps. - - The builder walks the systems in name order and skips a path that a - written file blocks as a directory, or the reverse: RetroArch declares - SGB1.sfc and SGB1.sfc/program.rom, and only the first is in the pack. - An entry without a destination (EmuDeck's system:md5 whitelist) is - judged but takes no path. Returns (path -> local copy written there, - path -> copy or None for each slot kept, a user_provided or external one - included). - """ - from packpaths import _has_path_conflict, _register_path - - shipped: dict[str, str] = {} - occupied: dict[str, str | None] = {} - seen: set[str] = set() - folded: set[str] = set() - parents: set[str] = set() - for _sys_id, full, local in sorted(packed_order, key=lambda item: item[0]): - # EmuDeck's system:md5 entries name no file: the builder writes none. - if not full or full.endswith("/"): - continue - if ( - full in occupied - or (case_insensitive and full.lower() in folded) - or _has_path_conflict(full, seen, parents) - ): - continue - _register_path(full, seen, parents) - folded.add(full.lower()) - occupied[full] = local - if local is not None: - shipped[full] = local - return shipped, occupied - - -def _dest_key(file_entry: dict, sys_id: str) -> str: - """The path a declaration occupies, as the builder keys its pack.""" - dest = sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) - return dest or f"{sys_id}/{file_entry.get('name', '')}" - - -def _twin_index( - verify_systems: dict, db: dict, base_dest: str, zip_contents: dict, -) -> tuple[dict[str, int], dict[int, tuple[str, dict]]]: - """Which declaration the pack ships at each destination, and every declaration by id.""" - # From the module that defines the rule, not the builder's CLI: importing - # generate_pack made every verify depend on its argparse and manifest code. - from packresolve import preferred_entries as _preferred_entries - - preferred_entries = _preferred_entries( - verify_systems, db, DEFAULT_BIOS_DIR, base_dest, False, - zip_contents, True, - ) - winners = { - id(fe): (sid, fe) - for sid, system in verify_systems.items() - for fe in system.get("files", []) - } - return preferred_entries, winners - - -@dataclass(frozen=True) -class _DeclarationResolver: - """How a platform run resolves its declarations, as the builder does.""" - - db: dict - zip_contents: dict - data_dir_registry: dict | None - slot_overrides: dict[str, str] - mode: str - platform_profiles: dict - # Which declaration the pack ships at each destination, and every - # declaration by id (_twin_index). - preferred_entries: dict[str, int] - winners: dict[int, tuple[str, dict]] - base_dest: str - - -def _resolve_declaration( - file_entry: dict, sys_id: str, resolver: _DeclarationResolver, -) -> tuple[str | None, str, str | None]: - """Resolve a declaration to the file the pack ships at its destination. - - When another declaration holds the destination, that one's file is - returned and the evidence reset: the winner's hash match is not this - declaration's, which is hashed against the shipped file. - """ - base_dest = resolver.base_dest - bare = sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) - preferred = resolver.preferred_entries.get(f"{base_dest}/{bare}" if base_dest else bare) - held_by, winner = (None, file_entry) - if preferred is not None and preferred != id(file_entry): - held_by, winner = resolver.winners[preferred] - local_path, resolve_status = _resolve_for_platform( - winner, held_by or sys_id, resolver.db, resolver.zip_contents, - resolver.data_dir_registry, resolver.slot_overrides, resolver.mode, - resolver.platform_profiles, - ) - return local_path, "" if held_by else resolve_status, held_by - - -def _twin_unmet( - result: dict, - held_by: str | None, - file_entry: dict | None = None, - sys_id: str = "", - destination: str = "", -) -> bool: - """Mark a declaration unmet at a path another declaration holds. - - The path is answered by the winner's file, which the pack counts once. - This declaration's failure is reported, never folded into the - destination's status. The message names the path, both systems and - what this declaration expects: "is not met at the path coco holds" - named neither the path nor the file wanted there. - """ - if held_by is None or result["status"] == Status.OK: - return False - entry = file_entry or {} - expects = next( - (f" ({h} {str(entry[h]).split(',')[0]})" - for h in ("sha1", "md5", "crc32") if entry.get(h)), - "", - ) - owner = sys_id or "this" - result["discrepancy"] = ( - f"{destination or result.get('name', '')} is declared for {owner}" - f" and for {held_by}. The {owner} declaration{expects} is not met at" - f" the path, which holds the {held_by} file" - ) - # Read by reports that list entries: the destination itself is held, and - # a count by destination does not include this one. - result["settled_by"] = held_by - return True - - -def _resolve_for_platform( - file_entry: dict, - sys_id: str, - db: dict, - zip_contents: dict, - data_dir_registry: dict | None, - slot_overrides: dict[str, str], - mode: str, - platform_profiles: dict, -) -> tuple[str | None, str]: - """Resolve one platform entry the way the pack builder does. - - The builder's own resolution (packresolve.resolve_declaration), read from - disk and the large-file cache: verify never downloads. A frontend that - never reads the bytes takes the filename-free core's own image. - """ - from packresolve import pending_release_asset, resolve_declaration, run_is_offline - - override = slot_overrides.get( - sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) - ) - local_path, status = resolve_declaration( - file_entry, db, DEFAULT_BIOS_DIR, zip_contents, data_dir_registry, - override, offline=True, - ) - if status in ("not_found", "hash_mismatch") and not run_is_offline(): - # Not in the cache, and the release holds a copy that answers the - # declaration: an online build fetches and packs it (resolve_file). - asset = pending_release_asset(file_entry, db) - if asset: - return asset, RELEASE_ASSET_PENDING - if status == "not_found" and not reads_file_contents(mode): - found = agnostic_substitute(file_entry, sys_id, db, platform_profiles) - if found: - return found[0], "agnostic_fallback" - return local_path, status - - -@dataclass(frozen=True) -class _PlatformRun: - """The inputs of one verify_platform run, read by each of its stages.""" - - config: dict - db: dict - emulators_dir: str - emu_profiles: dict | None - profiles: dict - target_cores: set[str] | None - data_dir_registry: dict | None - zip_contents: dict - system_filter: list[str] | None - required_only: bool - mode: str - base_dest: str - - def full(self, destination: str) -> str: - return f"{self.base_dest}/{destination}" if self.base_dest else destination - - -@dataclass -class _PlatformTally: - """Each declaration's verdict, and the verdicts aggregated by destination.""" - - run: _PlatformRun - platform: str - resolver: _DeclarationResolver - region_drops: set[str] - validation_index: dict - validation_owners: dict[str, list[tuple[str, str]]] - hle_index: dict[str, bool] - categories: EntryCategories - details: list[dict] = field(default_factory=list) - file_status: dict[str, str] = field(default_factory=dict) - file_required: dict[str, bool] = field(default_factory=dict) - file_severity: dict[str, str] = field(default_factory=dict) - # What each entry is: firmware, a game's data, or a name no core the - # platform runs opens. Only firmware gaps carry a severity. - file_category: dict[str, str] = field(default_factory=dict) - # (system, full destination, local copy) of each declaration the builder - # writes, and None for one whose slot it keeps without a file from the - # collection (user_provided, external). Placed below in the builder's order. - packed_order: list[tuple[str, str, str | None]] = field(default_factory=list) - shipped_keys: set[str] = field(default_factory=set) - results_at: dict[str, list[dict]] = field(default_factory=dict) - - def judge(self, sys_id: str, file_entry: dict) -> None: - """Verify one declaration and add it to its destination's tally.""" - destination = sanitize_pack_path( - file_entry.get("destination", file_entry.get("name", "")) - ) - if self.region_drops and destination in self.region_drops: - return - local_path, resolve_status, held_by = _resolve_declaration( - file_entry, sys_id, self.resolver, - ) - result, local_path = self._verdict( - file_entry, sys_id, local_path, resolve_status, destination, - ) - result["system"] = sys_id - result["hle_fallback"] = self.hle_index.get(file_entry.get("name", ""), False) - result["ground_truth"] = build_ground_truth( - file_entry.get("name", ""), - self.validation_index, - ) - self.details.append(result) - config = self.run.config - mode = self.run.mode - # Occupied only where the builder ships the declaration: a hash - # the frontend refuses is left out, and the destination stays free - # for a core's file the pack does carry. - if ( - local_path - and result["status"] != Status.MISSING - and baseline_verdict( - file_entry, local_path, resolve_status, mode, config.get("hash_rule", "") - )[1] is None - ): - self.packed_order.append((sys_id, self.run.full(destination), local_path)) - self.shipped_keys.add(_dest_key(file_entry, sys_id)) - if _twin_unmet( - result, held_by, file_entry, sys_id, self.run.full(destination), - ): - return - self._aggregate(sys_id, file_entry, destination, result) - - def _verdict( - self, file_entry: dict, sys_id: str, local_path: str | None, - resolve_status: str, destination: str, - ) -> tuple[dict, str | None]: - """The declaration's result, and the local copy the pack writes for it.""" - config = self.run.config - mode = self.run.mode - stored = _storage_verdict(file_entry, emulator_pack=False) - if resolve_status == RELEASE_ASSET_PENDING: - # Counted as an online build counts it, which fetches the - # asset. Under --offline the builder cannot, and neither - # does this report (_resolve_for_platform). - result = { - "name": file_entry.get("name", ""), - "required": file_entry.get("required", True), - "status": Status.OK, - "release_asset": local_path, - "reason": "release asset, fetched when the pack is built", - } - # Written at its path like any held file: keyed to None, it - # stayed out of pack_destinations and step 5 read the pack's - # copy as a file only the pack holds. - self.packed_order.append((sys_id, self.run.full(destination), local_path)) - self.shipped_keys.add(_dest_key(file_entry, sys_id)) - return result, None - if stored is not None: - # The builder keeps the slot: instructions for a user_provided - # file, the download for an external one, whether it arrives - # or not. No core file goes there. - self.packed_order.append((sys_id, self.run.full(destination), None)) - return stored, None - if not reads_file_contents(mode): - return verify_entry_existence( - file_entry, - local_path, - self.validation_index, - self.run.db, - destination, - self.validation_owners, - resolve_status, - config.get("platform", ""), - ), local_path - if digest_algorithm(mode) == "sha1": - return verify_entry_sha1(file_entry, local_path), local_path - result = verify_entry_md5( - file_entry, local_path, resolve_status, config.get("hash_rule", "") - ) - # Emulator-level validation: informational for platform packs. - # Platform verification (MD5) is the authority. Emulator - # mismatches are reported as discrepancies, not failures. - if result["status"] == Status.OK: - _chosen, disagreement = validated_choice( - file_entry, local_path, self.run.db, self.validation_index, "bios", - digest_algorithm(mode), destination, self.validation_owners, - ) - if disagreement: - result["discrepancy"] = f"{self.platform} says OK but {disagreement}" - return result, local_path - - def _aggregate( - self, sys_id: str, file_entry: dict, destination: str, result: dict, - ) -> None: - # Aggregate by destination, keyed as the builder keys its pack. - # A declaration that finds nothing leaves the path to one that - # holds a file: the builder packs that file there, whatever the - # order the two are read in. - dest = _dest_key(file_entry, sys_id) - self.results_at.setdefault(dest, []).append(result) - required = file_entry.get("required", True) - cur = result["status"] - prev = self.file_status.get(dest) - hle = self.hle_index.get(file_entry.get("name", ""), False) - sev = compute_severity(cur, required, self.run.mode, hle) - explained = self.categories.explain(file_entry, destination, sys_id) - category = explained.pop("category") - result["category"] = category - result["category_evidence"] = explained - if cur != Status.MISSING: - # A held entry is firmware for the counts: its category only - # documents it. - category = BIOS - if self.file_category.get(dest, category) == BIOS: - category = BIOS - self.file_category[dest] = category - if prev is not None and (cur == Status.MISSING) != (prev == Status.MISSING): - if cur == Status.MISSING: - return - del self.file_status[dest], self.file_severity[dest] - prev = None - if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get(prev, 0): - self.file_status[dest] = cur - self.file_required[dest] = required - prev_sev = self.file_severity.get(dest) - if prev_sev is None or _SEVERITY_ORDER.get(sev, 0) > _SEVERITY_ORDER.get( - prev_sev, 0 - ): - self.file_severity[dest] = sev - - def settle_groups(self) -> None: - """RetroBat's group: one file of it held is enough, and the others are - reported OPTIONAL (batocera-systems/Program.cs). None held, each stays - required.""" - members: dict[tuple[str, str], list[str]] = {} - for sys_id, system in self.run.config.get("systems", {}).items(): - for file_entry in system.get("files", []): - if file_entry.get("group"): - dest = _dest_key(file_entry, sys_id) - if dest in self.file_status: - members.setdefault((sys_id, file_entry["group"]), []).append(dest) - for dests in members.values(): - if not any(self.file_status[d] == Status.OK for d in dests): - continue - for dest in dests: - if self.file_status[dest] == Status.MISSING: - self.file_required[dest] = False - self.file_severity[dest] = compute_severity( - Status.MISSING, False, self.run.mode - ) - for result in self.results_at.get(dest, []): - result["required"] = False - - def credit_placed(self, placed: set[str]) -> None: - """An existence frontend is satisfied by any file at the path, and the - builder fills a free platform destination with a core's file.""" - for dest, status in self.file_status.items(): - if status == Status.MISSING and self.run.full(dest) in placed: - self.file_status[dest] = Status.OK - self.file_severity[dest] = Severity.OK - for result in self.results_at.get(dest, []): - result["status"] = Status.OK - - def severity_counts(self) -> tuple[dict[str, int], dict[str, list[str]]]: - """Destinations by severity, and the missing ones that are not firmware.""" - counts = { - Severity.OK: 0, - Severity.INFO: 0, - Severity.WARNING: 0, - Severity.CRITICAL: 0, - } - not_firmware: dict[str, list[str]] = {} - for dest, s in self.file_severity.items(): - category = self.file_category.get(dest, BIOS) - if category != BIOS and self.file_status.get(dest) == Status.MISSING: - not_firmware.setdefault(category, []).append(dest) - continue - counts[s] = counts.get(s, 0) + 1 - return counts, not_firmware - - -def _cut_game_data( - config: dict, - emu_profiles: dict | None, - emulators_dir: str, - data_dir_registry: dict | None, - target_cores: set[str] | None, - system_filter: list[str] | None, -) -> tuple[dict, dict, list[str]]: - """The config and profiles of a --no-game-data pack, and what it leaves out.""" - from resolve.gamedata import without_game_data - - if emu_profiles is None: - emu_profiles = load_emulator_profiles(emulators_dir) - cut = without_game_data(config, emu_profiles, data_dir_registry, target_cores) - config, emu_profiles = cut.config, cut.profiles - systems = config.get("systems", {}) - in_scope = set(select_systems(systems, system_filter) if system_filter else systems) - cut.left_out = [ - item for item in cut.left_out - if item.layer == "core" or item.system in in_scope - ] - return config, emu_profiles, cut.report_lines() - - -def _required_declarations(verify_systems: dict) -> dict: - return { - sys_id: { - **system, - "files": [ - fe for fe in system.get("files", []) if fe.get("required") is not False - ], - } - for sys_id, system in verify_systems.items() - } - - -def _region_pass( - run: _PlatformRun, verify_systems: dict, pack_overrides: dict, regions: list[str], -) -> tuple[set[str], list[str], dict[tuple[str, str, str], str]]: - """The destinations a region run withdraws, the groups no file answers, - and the destination of each core extra.""" - from resolve import regions as resolve_regions - - # The builder owns pack composition, so it owns the grouping the region - # pass reads. Grouping the platform files here and the core extras - # there let the two answer differently on one request: the report kept - # every core extra a region run withdraws from the pack. - from packextras import platform_region_groups - - config = run.config - held: set[str] = set() - region_groups, region_extra_dests = platform_region_groups( - config, - verify_systems, - run.emulators_dir, - run.db, - config.get("base_destination", ""), - run.profiles, - target_cores=run.target_cores, - required_only=run.required_only, - held_out=held, - zip_contents=run.zip_contents, - data_registry=run.data_dir_registry, - slot_overrides=pack_overrides, - ) - region_index = resolve_regions.platform_region_index(config, run.profiles, run.target_cores) - region_drops = resolve_regions.resolve_region_drops( - region_groups, region_index, regions, held, - ) - # The pack README names these: no file answers the request, so every - # candidate stays. Reported here too, or verify reads all OK for a - # system that has no BIOS for the region asked. - region_fallbacks = resolve_regions.fallback_groups( - region_groups, region_index, regions - ) - return region_drops, region_fallbacks, region_extra_dests - - -def _platform_gaps( - run: _PlatformRun, - occupied: dict[str, str | None], - region_drops: set[str], - region_extra_dests: dict[tuple[str, str, str], str], - validation_index: dict, - validation_owners: dict[str, list[tuple[str, str]]], -) -> tuple[list[dict], set[str], dict[str, str]]: - """The core files of the pack: the gap report as the builder narrows it, - the destinations it fills, and the category of each.""" - config = run.config - # Cross-reference undeclared files, called exactly as the builder calls - # it: its declarations, not the enriched ones (a core file the platform - # also declares under another name is packed at the core's own path, 21 - # such files in the RetroArch pack), and no names from inside archives - # or data trees (a loose file whose name exists only as a member of - # naomi2.zip was counted "in pack" while the builder shipped nothing). - undeclared = find_undeclared_files( - config, - run.emulators_dir, - run.db, - run.emu_profiles, - target_cores=run.target_cores, - declared_names=platform_declarations(config, run.db, enrich=False), - ) - # The builder's own pass reads the same report: computed once here and - # handed over as it stands now, before the markings below. - report_for_builder = [dict(u) for u in undeclared] - if run.system_filter: - # A system pack carries the extras its systems own. - from packextras import report_owned_by_systems - - undeclared = report_owned_by_systems(undeclared, run.system_filter) - if run.required_only: - undeclared = [u for u in undeclared if u.get("required") is not False] - if region_drops: - undeclared = [ - u - for u in undeclared - if region_extra_dests.get( - (u.get("emulator", ""), u.get("name", ""), u.get("path") or "") - ) - not in region_drops - ] - if run.required_only: - # One member of a required set, as the builder keeps it. - spares = core_file_spares(undeclared) - undeclared = [u for u in undeclared if id(u) not in spares] - _mark_unplaced(config, undeclared, run.profiles) - from packextras import ExtraResolver - - placed_kind: dict[str, str] = {} - placed = _mark_hidden(config, undeclared, occupied, _BuilderPass( - run.emulators_dir, run.db, run.emu_profiles, run.target_cores, region_drops, - report_for_builder, - ExtraResolver( - run.db, DEFAULT_BIOS_DIR, run.zip_contents, run.data_dir_registry, - validation_index, validation_owners, profiles=run.profiles, - pending_assets=True, - ), - placed_kind, - run.system_filter, - run.required_only, - )) - return undeclared, placed, placed_kind - - -def _profile_coverage( - profiles: dict, verify_systems: dict, file_status: dict[str, str], - validation_index: dict, -) -> tuple[int, int]: - """Destinations whose file a core validates, and those a profile names.""" - gt_filenames = set(validation_index) - profiled_names: set[str] = set() - for profile in profiles.values(): - if profile.get("type") in ("launcher", "alias"): - continue - for f in profile.get("files", []): - name = f.get("name", "") - if name: - profiled_names.add(name) - profiled_names.update(f.get("aliases") or []) - dest_to_name: dict[str, str] = {} - for sys_id, system in verify_systems.items(): - for fe in system.get("files", []): - dest_to_name.setdefault(_dest_key(fe, sys_id), fe.get("name", "")) - with_validation = sum( - 1 for dest in file_status if dest_to_name.get(dest, "") in gt_filenames - ) - with_profile = sum( - 1 for dest in file_status if dest_to_name.get(dest, "") in profiled_names - ) - return with_validation, with_profile - - -class PlatformNarrowing(TypedDict, total=False): - """The narrowings of a platform pack verify_platform reports on.""" - - regions: list[str] | None - system_filter: list[str] | None - no_game_data: bool - required_only: bool - - -def verify_platform( - config: dict, - db: dict, - emulators_dir: str = DEFAULT_EMULATORS_DIR, - emu_profiles: dict | None = None, - target_cores: set[str] | None = None, - data_dir_registry: dict | None = None, - **narrowing: Unpack[PlatformNarrowing], -) -> dict: - """Verify all BIOS files for a platform, including cross-reference gaps. - - ``no_game_data`` reports on the pack built with --no-game-data: the - game data cut as the builder cuts it, and named in ``left_out``. - - A region priority list narrows the report to the files a pack built with the - same list would carry, using the same selection function as the builder. - ``system_filter`` does the same for a pack built with --system: the - systems it keeps and the core extras those systems own. - ``required_only`` reports on the pack built with --required-only: the - declarations, trees and core extras marked ``required: false`` are left - out before any of them takes a path, as the builder leaves them out. - """ - unknown = sorted(set(narrowing) - set(PlatformNarrowing.__annotations__)) - if unknown: - raise TypeError(f"verify_platform() got an unexpected keyword argument '{unknown[0]}'") - regions = narrowing.get("regions") - system_filter = narrowing.get("system_filter") - no_game_data = narrowing.get("no_game_data", False) - required_only = narrowing.get("required_only", False) - left_out: list[str] = [] - if no_game_data: - config, emu_profiles, left_out = _cut_game_data( - config, emu_profiles, emulators_dir, data_dir_registry, target_cores, - system_filter, - ) - # Normalized once: a typo in a platform YAML must not verify with one - # mode and be scored with another. - mode = normalize_mode(config.get("verification_mode")) - platform = config.get("platform", "unknown") - - # The builder settles a destination claimed by both layers, and this must read - # the same decision, or the two tools describe different packs. - has_zipped = any( - fe.get("zipped_file") - for sys in config.get("systems", {}).values() - for fe in sys.get("files", []) - ) - zip_contents = build_zip_contents_index(db) if has_zipped else {} - - # Loaded before the slot overrides: a caller passing no profiles (the - # README's coverage) got no override and reported a discrepancy at a slot - # the pack settles. - profiles = ( - emu_profiles - if emu_profiles is not None - else load_emulator_profiles(emulators_dir) - ) - base_dest = config.get("base_destination", "") - pack_overrides = slots.pack_overrides( - config, profiles, db, zip_contents, data_dir_registry, - target_cores=target_cores, - ) - slot_overrides = { - (key[len(base_dest) + 1:] if base_dest and key.startswith(f"{base_dest}/") else key): path - for key, path in pack_overrides.items() - } - - # Build HLE + validation indexes from emulator profiles - # Ground truth comes from the emulators the platform runs. A standalone - # profile that loads a same-named file of its own (ZEsarUX's 48K - # cpc6128.rom against cap32's 32K one) has nothing to say about a - # RetroArch pack, nor does its HLE: dosbox-x's FONT.ROM fallback turned a - # missing required Batocera BIOS into INFO. - plat_cores = resolve_platform_cores(config, profiles) - platform_profiles = {name: profiles[name] for name in plat_cores} - hle_index = { - f.get("name", ""): True - for profile in platform_profiles.values() - for f in profile.get("files", []) - if f.get("hle_fallback") - } - validation_index = _build_validation_index(platform_profiles) - validation_owners = destination_owners(platform_profiles) - - verify_systems = platform_scope_systems(config, profiles, target_cores, system_filter) - if required_only: - verify_systems = _required_declarations(verify_systems) - - categories = EntryCategories(config, profiles, data_dir_registry) - run = _PlatformRun( - config, db, emulators_dir, emu_profiles, profiles, target_cores, - data_dir_registry, zip_contents, system_filter, required_only, mode, base_dest, - ) - - region_drops: set[str] = set() - region_fallbacks: list[str] = [] - region_extra_dests: dict[tuple[str, str, str], str] = {} - if regions: - region_drops, region_fallbacks, region_extra_dests = _region_pass( - run, verify_systems, pack_overrides, regions, - ) - - # A destination two systems declare with two hashes ships one file, the - # one the builder prefers. The other declaration is scored against that - # file, as the frontend will score it after installation: RetroDECK's - # xroar component hashes bios/disk.rom and finds the PC-88 ROM. - preferred_entries, winners = _twin_index( - verify_systems, db, base_dest, zip_contents - ) - tally = _PlatformTally( - run, platform, - _DeclarationResolver( - db, zip_contents, data_dir_registry, slot_overrides, mode, - platform_profiles, preferred_entries, winners, base_dest, - ), - region_drops, validation_index, validation_owners, hle_index, categories, - ) - for sys_id, system in verify_systems.items(): - for file_entry in system.get("files", []): - tally.judge(sys_id, file_entry) - tally.settle_groups() - - shipped, occupied = _builder_placement( - tally.packed_order, bool(config.get("case_insensitive_fs", False)) - ) - undeclared, placed, placed_kind = _platform_gaps( - run, occupied, region_drops, region_extra_dests, validation_index, - validation_owners, - ) - # What the builder places from the cores, one per pack path, by category: - # several entries claim one path (rom.key from three Amiga cores) and the - # builder ships one file there. The category travels on the extra: a copy - # the second pass makes has no gap report entry to look it up by. - packed_extras = {"bios": 0, "game_data": 0} - for category in placed_kind.values(): - packed_extras["game_data" if category == "game_data" else "bios"] += 1 - if not reads_file_contents(mode): - tally.credit_placed(placed) - - counts, not_firmware = tally.severity_counts() - file_status = tally.file_status - - # Held but refused: on a hash platform the builder leaves out a file whose - # declared hash the local copy contradicts. Counted apart, so a coverage - # figure never calls present what the pack does not carry. - excluded = sorted( - dest for dest, status in file_status.items() - if status == Status.UNTESTED and dest not in tally.shipped_keys - ) - - # Count by file status (ok/untested/missing) - status_counts: dict[str, int] = {} - for s in file_status.values(): - status_counts[s] = status_counts.get(s, 0) + 1 - - exclusions = find_exclusion_notes( - config, emulators_dir, emu_profiles, target_cores=target_cores - ) - - with_validation, with_profile = _profile_coverage( - profiles, verify_systems, file_status, validation_index, - ) - total = len(file_status) - - # The paths a pack built from this report holds, as written in the ZIP - # (base_destination stripped, as the builder flattens it). The pipeline - # compares this set with the archive: equal counts can hide one file - # credited here and another written there. - from packpaths import _flat - - pack_destinations = sorted( - {_flat(dest, base_dest, True) for dest in shipped} | { - _flat(dest, base_dest, True) for dest in placed - } - ) - - return { - "platform": platform, - **({"systems": sorted(verify_systems)} if system_filter else {}), - "verification_mode": mode, - "total_files": total, - "pack_destinations": pack_destinations, - "severity_counts": counts, - "status_counts": status_counts, - "missing_not_firmware": {k: sorted(v) for k, v in sorted(not_firmware.items())}, - "excluded_files": excluded, - "packed_extras": packed_extras, - "undeclared_files": undeclared, - # Reported apart, never scored: no severity, count or exit code reads it. - "launcher_reads_not_held": launcher_reads_not_held( - {config.get("_key", platform): config}, db, profiles, data_dir_registry - ), - # Records a config file does not prove: listed, never consumed. - "launcher_unproven": launcher_unproven({config.get("_key", platform): config}, profiles), - "exclusion_notes": exclusions, - "region_fallbacks": sorted(region_fallbacks), - **({"left_out": left_out} if no_game_data else {}), - # Every tree of the registry answers a declaration by its tail, so - # one that was never refreshed leaves its files missing here while - # an online pack build refreshes it and packs them. - "data_dir_notices": sorted( - key for key, entry in (data_dir_registry or {}).items() - if not os.path.isdir(entry.get("local_cache", "")) - ), - "details": tally.details, - "ground_truth_coverage": { - "with_validation": with_validation, - "with_profile": with_profile, - "platform_only": total - with_validation, - "total": total, - "applicable": bool(resolve_platform_cores(config, profiles)), - }, - } - - # Output -def _format_ground_truth_aggregate(ground_truth: list[dict]) -> str: - """Format ground truth as a single aggregated line. - - Example: beetle_psx [md5], pcsx_rearmed [existence] - """ - parts = [] - for gt in ground_truth: - checks_label = "+".join(gt["checks"]) if gt["checks"] else "existence" - parts.append(f"{gt['emulator']} [{checks_label}]") - return ", ".join(parts) - - -def _format_ground_truth_verbose(ground_truth: list[dict]) -> list[str]: - """Format ground truth as one line per core with expected values and source ref. - - Example: handy validates crc32=0d973c9d,size=512 [lynx/rom.h:48-49] - """ - lines = [] - for gt in ground_truth: - checks_label = "+".join(gt["checks"]) if gt["checks"] else "existence" - expected = gt.get("expected", {}) - if expected: - vals = ",".join(f"{k}={v}" for k, v in sorted(expected.items())) - part = f"{gt['emulator']} validates {vals}" - else: - part = f"{gt['emulator']} validates {checks_label}" - if gt.get("source_ref"): - part += f" [{gt['source_ref']}]" - lines.append(part) - return lines - - -def _print_ground_truth(gt: list[dict], verbose: bool) -> None: - """Print ground truth lines for a file entry.""" - if not gt: - return - if verbose: - for line in _format_ground_truth_verbose(gt): - print(f" {line}") - else: - print(f" {_format_ground_truth_aggregate(gt)}") - - -def _discrepancy_keys(details: list[dict]) -> set[str]: - """The DISCREPANCY lines _print_detail_entries prints for these details. - - A file already reported MISSING or UNTESTED on its own ground is not - printed again as a discrepancy, and is not counted as one either. - """ - shown = { - f"{d['system']}/{d['name']}" - for d in details - if d["status"] == Status.MISSING - or (d["status"] == Status.UNTESTED and not d.get("discrepancy")) - } - return { - key - for d in details - if d.get("discrepancy") - and (key := f"{d['system']}/{d['name']}") not in shown - } - - -# A platform entry that is not firmware, as the report names it. -_NOT_FIRMWARE = { - "game_data": "game data", - "unread": "no core the platform runs opens it", -} - - -def category_evidence_text(evidence: dict) -> str: - """One line saying what establishes a missing entry's category.""" - if evidence.get("read_by"): - groups: dict[bool, list[str]] = {True: [], False: []} - for reader in evidence["read_by"]: - refs = [ - f"{e['name']} at {e['source_ref']}" if e.get("source_ref") else e["name"] - for e in reader.get("entries", []) - ] - groups[bool(reader.get("runs_system"))].append( - f"{reader['emulator']} ({', '.join(refs)})" if refs - else f"{reader['emulator']} (by {reader['proof']})" - ) - if not groups[True]: - return "read by " + ", ".join(groups[False]) - text = "read by " + ", ".join(groups[True]) - if groups[False]: - text += ", also named by " + ", ".join(groups[False]) - return text - examined = evidence.get("cores_examined") or [] - cores = f"cores examined: {', '.join(examined)}" if examined else "no core examined" - if evidence.get("unsettled"): - return f"no reader found, not settled: {evidence['unsettled']} ({cores})" - return f"no reader found ({cores})" - - -def _print_category_evidence(detail: dict) -> None: - evidence = detail.get("category_evidence") - if evidence: - print(f" {category_evidence_text(evidence)}") - - -def _print_detail_entries(details: list[dict], seen: set[str], verbose: bool) -> None: - """Print UNTESTED, MISSING, and DISCREPANCY entries from verification details.""" - _print_untested_details(details, seen, verbose) - _print_missing_details(details, seen, verbose) - _print_discrepancy_details(details, seen, verbose) - if verbose: - _print_ok_details(details, seen) - - -def _print_untested_details(details: list[dict], seen: set[str], verbose: bool) -> None: - for d in details: - if d["status"] != Status.UNTESTED: - continue - if d.get("discrepancy"): - # Reported below with the ground for it: a declaration - # unmet at a path another declaration holds. - continue - key = f"{d['system']}/{d['name']}" - if key in seen: - continue - seen.add(key) - req = "required" if d.get("required", True) else "optional" - hle = ", HLE available" if d.get("hle_fallback") else "" - reason = d.get("reason", "") - print(f" UNTESTED ({req}{hle}): {key}: {reason}") - _print_ground_truth(d.get("ground_truth", []), verbose) - - -def _print_missing_details(details: list[dict], seen: set[str], verbose: bool) -> None: - for d in details: - if d["status"] != Status.MISSING: - continue - key = f"{d['system']}/{d['name']}" - if key in seen: - continue - label = _NOT_FIRMWARE.get(d.get("category", BIOS)) - if label: - # Counted on their own line, named on request. - if verbose: - seen.add(key) - print(f" MISSING ({label}): {key}") - _print_category_evidence(d) - continue - seen.add(key) - req = "required" if d.get("required", True) else "optional" - hle = ", HLE available" if d.get("hle_fallback") else "" - print(f" MISSING ({req}{hle}): {key}") - if verbose: - _print_category_evidence(d) - _print_ground_truth(d.get("ground_truth", []), verbose) - - -def _print_discrepancy_details(details: list[dict], seen: set[str], verbose: bool) -> None: - for d in details: - disc = d.get("discrepancy") - if disc: - key = f"{d['system']}/{d['name']}" - if key in seen: - continue - seen.add(key) - print(f" DISCREPANCY: {key}: {disc}") - _print_ground_truth(d.get("ground_truth", []), verbose) - - -def _print_ok_details(details: list[dict], seen: set[str]) -> None: - for d in details: - if d["status"] != Status.OK: - continue - key = f"{d['system']}/{d['name']}" - if key in seen: - continue - seen.add(key) - gt = d.get("ground_truth", []) - if gt: - req = "required" if d.get("required", True) else "optional" - print(f" OK ({req}): {key}") - for line in _format_ground_truth_verbose(gt): - print(f" {line}") - - -def _print_undeclared_entry( - u: dict, prefix: str, verbose: bool, repeated: frozenset[str] = frozenset() -) -> None: - """Print a single undeclared file entry with its validation checks. - - A name in ``repeated`` is read at more than one path, and the line names - the path: two identical lines told no one there were two slots to fill. - """ - name = u["path"] if u["name"] in repeated and u.get("path") else u["name"] - arc_count = u.get("archive_file_count") - if arc_count: - name_label = f"{name} ({arc_count} file{'s' if arc_count != 1 else ''})" - else: - name_label = name - if u.get("alternatives") and not u.get("in_repo"): - name_label += f" (or {', '.join(u['alternatives'])})" - print(f" {prefix}: {u['emulator']} needs {name_label}") - checks = u.get("checks", []) - if checks: - if verbose: - expected = u.get("expected", {}) - if expected: - vals = ",".join(f"{k}={v}" for k, v in sorted(expected.items())) - ref_part = f" [{u['source_ref']}]" if u.get("source_ref") else "" - print(f" validates {vals}{ref_part}") - else: - checks_label = "+".join(checks) - ref_part = f" [{u['source_ref']}]" if u.get("source_ref") else "" - print(f" validates {checks_label}{ref_part}") - else: - # A bare "[size]" under the entry said nothing to a reader. - print(f" validates {'+'.join(checks)}") - - -def _split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], list[dict]]: - """Game data, firmware the pack places, firmware it holds but cannot place. - - Everything that is not game data is firmware the core loads, archives - included: a bios_zip sat in neither list, so a required one that was - missing was never printed. - """ - game_data = [u for u in undeclared if u.get("category", "bios") == "game_data"] - firmware = [u for u in undeclared if u.get("category", "bios") != "game_data"] - unplaced = [u for u in firmware if u["in_repo"] and not u.get("in_pack", True)] - placed = [u for u in firmware if u.get("in_pack", True)] - return game_data, placed, unplaced - - -def _core_required_missing(bios_files: list[dict]) -> list[dict]: - """Core files a core cannot run without, absent from the collection. - - A file bundled with the emulator (DaedalusX64's n64.psh, the shader - library its renderer installs beside the binary) arrives with it: the - collection does not hold it by design, and listing it as missing sent - readers after a file every install already has. - """ - return [ - u - for u in bios_files - if u["required"] and not u["in_repo"] and not u.get("hle_fallback") - and not u.get("bundled") - ] - - -def _repeated_names(entries: list[dict]) -> frozenset[str]: - """Names more than one of ``entries`` carries.""" - counts = Counter(u["name"] for u in entries) - return frozenset(name for name, count in counts.items() if count > 1) - - -def _omission_reasons(entries: list[dict]) -> str: - """Each reason a held file was left out, with its count when several. - - Printing the first entry's reason for the whole count named one cause - for 412 RomM files when 20 carried it. - """ - counts = Counter(u.get("omitted", "not placed") for u in entries) - if len(counts) == 1: - return next(iter(counts)) - ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0])) - return ", ".join(f"{count} {reason}" for reason, count in ranked) - - -def _print_undeclared_section(result: dict, verbose: bool) -> None: - """Print cross-reference section for undeclared files used by cores.""" - undeclared = result.get("undeclared_files", []) - # The pack's core copies can come from no gap entry: recalbox - # --system nec-pc-engine packs six root syscard copies for geargrafx - # with an empty gap report, and returning here hid them. - packed = result.get("packed_extras") - if not undeclared and not (packed and any(packed.values())): - return - - game_data, bios_files, unplaced = _split_undeclared(undeclared) - - # A file installed with its emulator is never collected, firmware or - # game data, required or not: cross_reference counts it apart. The - # firmware already left the pack lists (_mark_unplaced), the game data - # did not, and Abuse's three bundled data files read as missing. - bundled = [u for u in undeclared if not u["in_repo"] and u.get("bundled")] - game_data = [u for u in game_data if u["in_repo"] or not u.get("bundled")] - - req_not_in_repo = _core_required_missing(bios_files) - req_hle_not_in_repo = [ - u - for u in bios_files - if u["required"] and not u["in_repo"] and u.get("hle_fallback") - ] - req_in_repo = [u for u in bios_files if u["required"] and u["in_repo"]] - opt_in_repo = [u for u in bios_files if not u["required"] and u["in_repo"]] - opt_not_in_repo = [u for u in bios_files if not u["required"] and not u["in_repo"]] - # The builder's count, one file per pack path, when the platform pass - # replayed it. Counting entries said 1130 for RetroArch, 48 more than the - # pack holds: rom.key alone was claimed by three Amiga cores. - core_in_pack = ( - packed["bios"] if packed is not None else len(req_in_repo) + len(opt_in_repo) - ) - core_missing_req = len(req_not_in_repo) + len(req_hle_not_in_repo) - core_missing_opt = len(opt_not_in_repo) - - # Required gaps are always named below, the optional ones on request. - listed = "" if verbose or not core_missing_opt else " (--verbose lists them)" - print( - f" Core files: {core_in_pack} in pack, {core_missing_req} required missing, " - f"{core_missing_opt} optional missing{listed}" - ) - # The missing files follow the line that counts them: printed after the - # held-but-not-packed line, they read as files installed with their emulator. - repeated = _repeated_names(req_not_in_repo + req_hle_not_in_repo + opt_not_in_repo) - for u in req_not_in_repo: - _print_undeclared_entry(u, "MISSING (required)", verbose, repeated) - for u in req_hle_not_in_repo: - _print_undeclared_entry(u, "MISSING (required, HLE fallback)", verbose, repeated) - if verbose: - for u in opt_not_in_repo: - _print_undeclared_entry(u, "MISSING (optional)", verbose, repeated) - if bundled: - # The required firmware is named, as a missing one would be. The - # rest (shaders, runtime libraries, engine data) on request. - shown = bundled if verbose else [ - u for u in bundled - if u["required"] and u.get("category", "bios") != "game_data" - ] - named = sorted({u["name"] for u in shown}) - # The required firmware alone read as the whole count: 14 names - # for 154 entries, nothing saying the rest existed. - hidden = len({u["name"] for u in bundled}) - len(named) - more = f"{hidden} more, " if named else "" - items = named + ([f"{more}--verbose lists them"] if hidden else []) - print( - f" Bundled with their emulator, not collected: {len(bundled)}" - + (f" ({', '.join(items)})" if items else "") - ) - if unplaced: - print(f" Core files held but not packed: {len(unplaced)} " - f"({_omission_reasons(unplaced)})") - - if game_data or (packed and packed.get("game_data")): - gd_missing = [u for u in game_data if not u["in_repo"]] - gd_packed = ( - packed["game_data"] if packed is not None - else sum(1 for u in game_data if u["in_repo"] and u.get("in_pack", True)) - ) - gd_unplaced = [u for u in game_data if u["in_repo"] and not u.get("in_pack", True)] - if gd_missing or gd_packed or gd_unplaced: - listed = "" if verbose or not gd_missing else " (--verbose lists them)" - print(f" Game data: {gd_packed} in pack, {len(gd_missing)} missing{listed}") - if verbose: - repeated = _repeated_names(gd_missing) - for u in gd_missing: - _print_undeclared_entry(u, "MISSING (game data)", verbose, repeated) - if gd_unplaced: - print( - f" Game data held but not packed: {len(gd_unplaced)} " - f"({_omission_reasons(gd_unplaced)})" - ) - - -def _print_launcher_unproven(result: dict, verbose: bool) -> None: - """Launcher records resting on a config file the code does not prove.""" - rows = result.get("launcher_unproven") or [] - if not rows: - return - listed = "" if verbose else " (--verbose lists them)" - print(f" Launcher records unproven: {len(rows)}{listed}") - if not verbose: - return - for row in rows: - print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}") - for link in row["missing"]: - print(f" missing {link}") - - -def _print_launcher_reads(result: dict, verbose: bool) -> None: - """Names the platform's launch code reads that the collection lacks.""" - every = result.get("launcher_reads_not_held") or [] - rows = [r for r in every if not r.get("unsourceable")] - unsourceable = [r for r in every if r.get("unsourceable")] - listed = "" if verbose else " (--verbose lists them)" - if rows: - print(f" Launcher reads, not held: {len(rows)}{listed}") - if unsourceable: - print(f" Launcher reads, unsourceable: {len(unsourceable)}{listed}") - if not verbose: - return - for row in unsourceable: - print(f" {row['name']} [{', '.join(row['emulators'])}]: {row['unsourceable']}") - for row in rows: - kinds = ", ".join(sorted({r["kind"] for r in row["readers"]})) - casing = f", held as {row['held_as']}" if row.get("held_as") else "" - print(f" {row['name']} [{', '.join(row['emulators'])}, {kinds}{casing}]") - for reader in row["readers"]: - print(f" {reader['emulator']}: {reader['source_ref']}") - - -def _platform_summary_parts(result: dict) -> list[str]: - """The counts of a platform's first report line, in its mode's terms.""" - mode = result["verification_mode"] - total = result["total_files"] - c = result["severity_counts"] - ok_count = c[Severity.OK] - problems = total - ok_count - - if not reads_file_contents(mode): - parts = [f"{ok_count}/{total} present"] - if problems: - missing = c.get(Severity.WARNING, 0) + c.get(Severity.CRITICAL, 0) - optional_missing = c.get(Severity.INFO, 0) - if missing: - parts.append(f"{missing} missing") - if optional_missing: - parts.append(f"{optional_missing} optional missing") - return parts - sc = result.get("status_counts", {}) - untested = sc.get(Status.UNTESTED, 0) - missing = sc.get(Status.MISSING, 0) - parts = [f"{ok_count}/{total} OK"] - if untested: - parts.append(f"{untested} untested") - if missing: - parts.append(f"{missing} missing") - return parts - - -def _print_release_assets(details: list[dict]) -> None: - fetched = sorted({d["name"] for d in details if d.get("release_asset")}) - if fetched: - # Counted present: an online build downloads them. --offline counts - # them missing, as an offline build leaves them out. - shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") - print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}") - - -def _print_platform_notices(result: dict, verbose: bool) -> None: - """What the counts leave unsaid: uncached trees, cuts, region and category gaps.""" - uncached = result.get("data_dir_notices") or [] - if uncached and result.get("status_counts", {}).get(Status.MISSING): - shown = ", ".join(uncached[:10]) + (f" (+{len(uncached) - 10})" if len(uncached) > 10 else "") - print( - f" Data directories not cached ({len(uncached)}), their files count missing " - f"until refresh_data_dirs.py runs (an online pack build refreshes them): {shown}" - ) - for line in result.get("left_out") or []: - print(f" {line}") - fallbacks = result.get("region_fallbacks") or [] - if fallbacks: - from packreadme import _group_label - - print(f" No BIOS for the requested regions, all kept ({len(fallbacks)}): " - + ", ".join(_group_label(g) for g in fallbacks)) - - not_firmware = result.get("missing_not_firmware") or {} - if not_firmware: - counts = ", ".join( - f"{len(dests)} {_NOT_FIRMWARE[category]}" - for category, dests in not_firmware.items() - ) - listed = "" if verbose else " (--verbose lists them)" - print(f" Missing, not firmware: {counts}{listed}") - - -def _print_platform_coverage(result: dict, verbose: bool) -> None: - # The same notes come back for every platform running these cores and - # filled 985 of the 1114 lines of verify --all: counted, listed on ask. - exclusions = result.get("exclusion_notes", []) - if exclusions and verbose: - print(f" No external files ({len(exclusions)}):") - for ex in exclusions: - print(f" {ex['emulator']}: {ex['detail']} [{ex['reason']}]") - elif exclusions: - print(f" No external files: {len(exclusions)} cores (--verbose lists them)") - - gt_cov = result.get("ground_truth_coverage") - if gt_cov and not gt_cov.get("applicable", True): - # MiSTer declares no core by design: its BiosDB is the answer, and - # the site shows "-" for it rather than a 0% gap. - print(" Ground truth: not applicable, the platform runs no profiled core") - elif gt_cov and gt_cov["total"] > 0: - # Rounded, as the site rounds: truncated, RetroArch read 20% here - # and 21% there for one measure. - pct = round(gt_cov["with_validation"] * 100 / gt_cov["total"]) - print( - f" Ground truth: {gt_cov['with_validation']}/{gt_cov['total']} files have emulator validation ({pct}%)" - ) - no_profile = gt_cov["total"] - gt_cov.get("with_profile", gt_cov["with_validation"]) - if no_profile: - print(f" {no_profile} platform-only (no emulator profile)") - - -def print_platform_result( - result: dict, group: list[str], verbose: bool = False -) -> None: - mode = result["verification_mode"] - label = " / ".join(group) - if result.get("systems"): - label += f" ({', '.join(result['systems'])})" - parts = _platform_summary_parts(result) - print(f"{label}: {', '.join(parts)} [{mode}]") - _print_release_assets(result["details"]) - _print_platform_notices(result, verbose) - - seen_details: set[str] = set() - _print_detail_entries(result["details"], seen_details, verbose) - _print_undeclared_section(result, verbose) - _print_launcher_reads(result, verbose) - _print_launcher_unproven(result, verbose) - _print_platform_coverage(result, verbose) - - # Emulator/system mode verification -def _effective_validation_label(details: list[dict], validation_index: dict) -> str: - """Determine the bracket label for the report. - - Returns the union of all check types used, e.g. [crc32+existence+size]. - """ - all_checks: set[str] = set() - has_files = False - for d in details: - fname = d.get("name", "") - if d.get("note"): - continue # skip informational entries (empty profiles) - has_files = True - entry = validation_index.get(fname) - if entry: - all_checks.update(entry["checks"]) - else: - all_checks.add("existence") - if not has_files: - return "existence" - return "+".join(sorted(all_checks)) - - -def _select_profiles( - profile_names: list[str], - all_profiles: dict, - standalone: bool, -) -> list[tuple[str, dict]]: - """Resolve the named profiles, stopping the run on a bad name.""" - try: - return select_emulator_profiles(profile_names, all_profiles, standalone) - except ProfileSelectionError as exc: - print(f"Error: {exc}", file=sys.stderr) - sys.exit(1) - - -_HASH_CONTRADICTED = "declared hash contradicted by the local file" - -# Reduced in the order generate_emulator_pack chooses, so the -# destination's status is the one the pack reports: a slot it -# fills with a contradicted copy, or counts as refused by the -# core, is not missing because another alternative is absent. -_SLOT_PREFERENCE: tuple[Callable[[tuple], bool], ...] = ( - lambda a: a[0]["status"] == Status.OK, - lambda a: a[0]["status"] == Status.UNTESTED - and a[0].get("reason") == _HASH_CONTRADICTED, - lambda a: a[0]["status"] != Status.MISSING, -) - - -def _emulator_files( - emu_name: str, - profile: dict, - db: dict, - standalone: bool, - all_profiles: dict, - system_ids: list[str] | None, - required_only: bool, - region_drops: set[str], -) -> list[dict]: - """The entries of a profile the emulator pack carries.""" - from packextras import expand_agnostic_entries - from packpaths import _resolve_destination - - files = expand_agnostic_entries( - expand_directory_entries( - deliverable(profile.get("files", []), standalone), - db, - standalone, - ), - emu_name, profile, db, standalone, all_profiles, - ) - if system_ids: - files = [fe for fe in files if entry_serves_systems(fe, profile, system_ids)] - if required_only: - optional_archives = { - fe["archive"] for fe in files - if fe.get("archive") - and archive_is_optional(archive_entry(fe["archive"], files), fe["archive"], files) - } - files = [ - fe for fe in files - if fe.get("archive") not in optional_archives - and (fe.get("archive") or fe.get("required") is not False) - ] - if region_drops: - # Loose files only, as the emulator pack: an archive ships whole, - # and dropping kronos' regional stvbios.zip members rebuilt the - # archive here from 4 of its 14 members and changed its required. - files = [ - fe - for fe in files - if fe.get("archive") - or _resolve_destination(fe, standalone) not in region_drops - ] - return files - - -def _archive_result( - archive: str, required: bool, local_path: str | None, resolve_status: str, -) -> dict: - """The verdict on an archive unit, from its resolution.""" - if local_path and resolve_status == "hash_mismatch": - # Same policy as the loose-file branch below: the name - # matched while the bytes contradict the hash the profile - # declares on the container. Reporting it covered says the - # collection holds an archive it does not. - return { - "name": archive, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": "declared hash contradicted by the local file", - } - if local_path: - result = { - "name": archive, - "status": Status.OK, - "required": required, - "path": local_path, - } - if resolve_status == RELEASE_ASSET_PENDING: - result["release_asset"] = local_path - return result - return { - "name": archive, - "status": Status.MISSING, - "required": required, - } - - -PlacedResult = tuple[str, dict, bool, bool, list[dict]] - - -@dataclass -class _EmulatorPack: - """The emulator pack as verify_emulator retraces it, and its report.""" - - db: dict - standalone: bool - required_only: bool - validation_index: dict - zip_contents: dict - data_registry: dict | None - details: list[dict] = field(default_factory=list) - # Members of a set another member fills, or that the set's first member - # stands for: not missing, and out of every count. - set_members: list[dict] = field(default_factory=list) - file_status: dict[str, str] = field(default_factory=dict) - file_severity: dict[str, str] = field(default_factory=dict) - dest_to_name: dict[str, str] = field(default_factory=dict) - data_dir_notices: list[str] = field(default_factory=list) - # The paths the emulator pack writes a profile file to. A copy whose hash - # the profile contradicts is written too (UNTESTED here, a DISCREPANCY in - # the pack), so the status alone does not say what the pack holds. - packed_dests: set[str] = field(default_factory=set) - # The emulator pack walks profiles in name order and keeps the first - # file at a path, folding case: a later profile's different file there - # (zesarux pentagon.rom after speccy's PENTAGON.ROM) is not in the pack. - sha1_by_path: dict = field(init=False) - # Destination -> (file packed there, its profile, the path as written). - # Archives and data trees take paths too, before and after the loose - # files of their profile, as the pack writes them. - placed: dict[str, tuple[str | None, str, str]] = field(default_factory=dict) - placed_files: set[str] = field(default_factory=set) - placed_parents: set[str] = field(default_factory=set) - content_ids: dict[str, str | None] = field(default_factory=dict) - - def __post_init__(self) -> None: - self.sha1_by_path = { - entry.get("path"): sha1 for sha1, entry in self.db.get("files", {}).items() - } - - def pending(self, entry: dict, local_path: str | None, status: str) -> tuple[str | None, str]: - from packresolve import pending_release_asset, run_is_offline - - # Read from disk and the cache, as _resolve_for_platform does: a - # release asset the cache lacks is fetched by an online build - # (generate_emulator_pack resolves with offline=offline). - if status in ("not_found", "hash_mismatch") and not run_is_offline(): - asset = pending_release_asset(entry, self.db) - if asset: - return asset, RELEASE_ASSET_PENDING - return local_path, status - - def content_id(self, path: str | None) -> str | None: - if not path: - return None - if path not in self.content_ids: - self.content_ids[path] = self.sha1_by_path.get(path) or ( - compute_hashes(path)["sha1"] if os.path.isfile(path) else None - ) - return self.content_ids[path] - - def block(self, dest: str) -> str | None: - from packpaths import placement_block - - return placement_block( - dest, self.placed_files, set(self.placed), self.placed_parents, True - ) - - def occupy(self, dest: str, path: str | None, owner: str) -> None: - from packpaths import _register_path - - if self.block(dest): - return - self.placed[dest.lower()] = (path, owner, dest) - _register_path(dest, self.placed_files, self.placed_parents) - - def occupy_trees(self, emu_name: str, profile: dict) -> None: - """The profile's data trees follow its files in the pack, which - writes them even when the system filter leaves it no file: - bluemsx's Machines/ tree holds msx-emu's coleco.rom path in a - --system colecovision pack.""" - for dd in deliverable(profile.get("data_directories", []), self.standalone): - if self.required_only and dd.get("required") is False: - continue - cache = (self.data_registry or {}).get(dd.get("ref", ""), {}).get("local_cache", "") - if not cache or not os.path.isdir(cache): - continue - dd_dest = dd.get("destination", "") - structure = profile.get("pack_structure") - prefix = ( - structure.get("standalone" if self.standalone else "libretro", "") - if structure else "" - ) - if prefix: - dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix - for root, _dirs, names in os.walk(cache): - for fname in names: - src = os.path.join(root, fname) - rel = os.path.relpath(src, cache).replace(os.sep, "/") - self.occupy(f"{dd_dest}/{rel}" if dd_dest else rel, src, emu_name) - - def note_data_dirs(self, profile: dict) -> None: - # Check data directories (only notice if not cached) - for dd in deliverable( - profile.get("data_directories", []), self.standalone - ): - if self.required_only and dd.get("required") is False: - continue - ref = dd.get("ref", "") - if not ref: - continue - if self.data_registry and ref in self.data_registry: - cache_path = self.data_registry[ref].get("local_cache", "") - if cache_path and os.path.isdir(cache_path): - continue # cached, no notice needed - self.data_dir_notices.append(ref) - - def verify_profile( - self, emu_name: str, profile: dict, files: list[dict], spares: set[str], - ) -> None: - """Verify one profile's entries and add them to the report.""" - self.note_data_dirs(profile) - - if not files: - self.details.append( - { - "name": f"({emu_name})", - "status": Status.OK, - "required": False, - "system": "", - "note": f"No files needed for {profile.get('emulator', emu_name)}", - "ground_truth": [], - } - ) - self.occupy_trees(emu_name, profile) - return - - # Each destination's outcome, settled by set once the profile is - # read: an archive unit is a member like a loose file (Kronos reads - # kronos/stvbios.zip, else stvbios.zip). - placed_results = self._archive_results(emu_name, profile, files, spares) - self._place_loose(emu_name, self._loose_results(emu_name, files), placed_results) - self._settle(emu_name, profile, placed_results) - self.occupy_trees(emu_name, profile) - - def _archive_results( - self, emu_name: str, profile: dict, files: list[dict], spares: set[str], - ) -> list[PlacedResult]: - # Verify archives as units (e.g., neogeo.zip, aes.zip) - from packpaths import _archive_destination - from packresolve import resolve_file - - placed_results: list[PlacedResult] = [] - seen_archives: set[str] = set() - for file_entry in files: - archive = file_entry.get("archive") - if not archive or archive in seen_archives: - continue - seen_archives.add(archive) - own_entry = archive_entry(archive, files) - # Where the pack puts it: an archive_prefix or pack_structure - # moves it, and a loose same-named entry is another file. - dest = _archive_destination( - archive, profile.get("archive_prefix", ""), - profile.get("pack_structure"), self.standalone, - ) - if dest in spares: - continue - local_path, resolve_status = self.pending(own_entry, *resolve_file( - own_entry, - self.db, - DEFAULT_BIOS_DIR, - self.zip_contents, - data_dir_registry=self.data_registry, - offline=True, - )) - required = any( - f.get("archive") == archive and f.get("required", True) - for f in files - ) - result = _archive_result(archive, required, local_path, resolve_status) - result["system"] = file_entry.get("system", "") - result["hle_fallback"] = False - result["ground_truth"] = build_ground_truth(archive, self.validation_index) - result["destination"] = dest - block = self.block(dest) - if block and local_path and result["status"] != Status.MISSING: - other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", "")) - if block == "path_conflict" or self.content_id(local_path) != self.content_id(other_path): - # The pack serves the other profile's file here: this - # archive is not in it, whatever this profile resolves. - result["status"] = Status.MISSING - result["reason"] = ( - "a packed file occupies its directory" if block == "path_conflict" - else f"the pack holds {owner}'s {other_dest} at this path" - ) - elif local_path: - self.occupy(dest, local_path, emu_name) - self.packed_dests.add(dest) - placed_results.append((dest, result, required, False, [own_entry])) - return placed_results - - def _loose_results( - self, emu_name: str, files: list[dict], - ) -> dict[str, list[tuple[dict, bool, bool, dict]]]: - from packpaths import _resolve_destination - from packresolve import resolve_file - - # Results of this emulator, by destination. Several entries of one - # profile on one destination are the releases the code accepts - # there (a shareware and a retail HOG, each GRP in a size table): - # holding one of them fills the slot, and the others are not gaps. - emu_results: dict[str, list[tuple[dict, bool, bool, dict]]] = {} - - for file_entry in files: - # Skip archive members (verified as archive units above) - if file_entry.get("archive"): - continue - - dest_hint = file_entry.get("path", "") - # The emulator pack's resolution, release assets included. - local_path, resolve_status = self.pending(file_entry, *resolve_file( - {**with_archive_members(file_entry, files), "source_profile": emu_name}, - self.db, - DEFAULT_BIOS_DIR, - self.zip_contents, - dest_hint=dest_hint, - data_dir_registry=self.data_registry, - offline=True, - )) - if resolve_status in ("not_found", "user_provided", "external"): - local_path = None - name = file_entry.get("name", "") - required = file_entry.get("required", True) - hle = file_entry.get("hle_fallback", False) - - result = self._loose_result( - file_entry, name, required, local_path, resolve_status, emu_name, - ) - result["system"] = file_entry.get("system", "") - result["hle_fallback"] = hle - result["ground_truth"] = build_ground_truth(name, self.validation_index) - # The slot the emulator pack places this entry in: standalone_path - # under --standalone, the sanitised path. - dest = _resolve_destination(file_entry, self.standalone) or name - emu_results.setdefault(dest, []).append((result, required, hle, file_entry)) - return emu_results - - def _loose_result( - self, file_entry: dict, name: str, required: bool, local_path: str | None, - resolve_status: str, emu_name: str, - ) -> dict: - """The verdict on a loose profile entry, from its resolution.""" - stored = _storage_verdict(file_entry, emulator_pack=True) - if stored is not None: - return stored - if resolve_status == RELEASE_ASSET_PENDING: - return { - "name": name, - "status": Status.OK, - "required": required, - "path": local_path, - "release_asset": local_path, - "reason": "release asset, fetched when the pack is built", - } - if not local_path: - result = {"name": name, "status": Status.MISSING, "required": required} - # An entry the profile documents as unsourceable is absent by - # design: a per-user key, a slot the user fills, a dump nobody - # has made. Counting it beside a file somebody could still - # find invites the wrong repair: dropping the flag, or - # chasing a vendor's whole install tree. - unsourceable = file_entry.get("unsourceable") - if unsourceable: - result["unsourceable"] = ( - unsourceable if isinstance(unsourceable, str) else "" - ) - return result - # Apply emulator validation - # Judged by this emulator's own entries, as it runs its check, - # through the selection the emulator pack makes. - chosen, disagreement = validated_choice( - file_entry, local_path, self.db, self.validation_index, DEFAULT_BIOS_DIR, - None, emulators={emu_name}, - ) - if disagreement: - return { - "name": name, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": disagreement.split(" says ", 1)[-1], - } - if chosen != local_path: - return { - "name": name, - "status": Status.OK, - "required": required, - "path": chosen, - } - if resolve_status == "hash_mismatch": - # Nothing in validation: caught it, but the name matched - # while the bytes contradict the hash the profile - # declares. That is a different file wearing the right - # name (config.ini and ROM collide across systems), so - # calling it covered reports the collection as holding - # something it does not. Validation runs first because it - # names the specific field that disagrees. - return { - "name": name, - "status": Status.UNTESTED, - "required": required, - "path": local_path, - "reason": "declared hash contradicted by the local file", - } - return { - "name": name, - "status": Status.OK, - "required": required, - "path": local_path, - } - - def _place_loose( - self, emu_name: str, - emu_results: dict[str, list[tuple[dict, bool, bool, dict]]], - placed_results: list[PlacedResult], - ) -> None: - for dest, alternatives in emu_results.items(): - # What the emulator pack places here: an accepted file, else a - # file whose hash the profile contradicts. A refused copy is held - # but never packed. - slot_entries = [a[3] for a in alternatives] - kept = _preferred_alternatives(alternatives) - packed = next( - (a[0].get("path") for a in kept - if a[0]["status"] == Status.OK and a[0].get("path")), - None, - ) or next( - (a[0].get("path") for a in kept - if a[0]["status"] == Status.UNTESTED - and a[0].get("reason") == _HASH_CONTRADICTED and a[0].get("path")), - None, - ) - held = packed or next( - (a[0].get("path") for a in kept - if a[0]["status"] != Status.MISSING and a[0].get("path")), - None, - ) - block = self.block(dest) - block_reason = "" - if block and held is not None: - block_reason = self._block_reason(dest, block, held) - elif not block and packed is not None: - self.occupy(dest, packed, emu_name) - self.packed_dests.add(dest) - for result, required, hle, _file_entry in kept: - if block_reason and result["status"] != Status.MISSING: - result["status"] = Status.MISSING - result["reason"] = block_reason - result["destination"] = dest - placed_results.append((dest, result, required, hle, slot_entries)) - - def _block_reason(self, dest: str, block: str, held: str) -> str: - other_path, owner, other_dest = self.placed.get(dest.lower(), (None, "", "")) - same = self.content_id(held) is not None and self.content_id(held) == self.content_id( - other_path - ) - if block == "path_conflict": - return "a packed file occupies its directory" - if block == "case_twin": - return ( - f"packed only as {other_dest}, from {owner}" - if same - else f"the pack holds {owner}'s {other_dest} at this path" - ) - if not same: - return f"the pack holds {owner}'s {other_dest} at this path" - return "" - - def _settle(self, emu_name: str, profile: dict, placed_results: list[PlacedResult]) -> None: - # A set the code takes one member of is one need: once a member is - # in the pack the others are not missing, and a set nobody holds is - # one gap under its first member. Settled per profile, before the - # destinations of several profiles are merged. - excused, standing = settle_sets([ - ( - slot_set_keys(emu_name, entries), - entries[0], - result["status"] == Status.OK - or (result["status"] == Status.UNTESTED - and result.get("reason") == _HASH_CONTRADICTED), - ) - for _dest, result, _required, _hle, entries in placed_results - ], lambda key: set_requirements(profile).get(key[1], True)) - for position, (dest, result, required, hle, _fe) in enumerate(placed_results): - if position in excused and result["status"] == Status.MISSING: - self.set_members.append(result) - continue - if position in standing: - result["alternatives"] = standing[position].others - result["required"] = required = standing[position].required - self.details.append(result) - - # Aggregate by destination (path if available, else name) - self.dest_to_name[dest] = result["name"] - cur = result["status"] - prev = self.file_status.get(dest) - if prev is None or _STATUS_ORDER.get(cur, 0) > _STATUS_ORDER.get( - prev, 0 - ): - self.file_status[dest] = cur - sev = _emulator_severity(cur, required, hle) - prev_sev = self.file_severity.get(dest) - if prev_sev is None or _SEVERITY_ORDER.get( - sev, 0 - ) > _SEVERITY_ORDER.get(prev_sev, 0): - self.file_severity[dest] = sev - - -def _preferred_alternatives( - alternatives: list[tuple[dict, bool, bool, dict]], -) -> list[tuple[dict, bool, bool, dict]]: - """The one alternative the emulator pack places at a destination.""" - if len(alternatives) > 1: - for keep in _SLOT_PREFERENCE: - chosen = [a for a in alternatives if keep(a)] - if chosen: - return chosen[:1] - return alternatives - - -def verify_emulator( - profile_names: list[str], - emulators_dir: str, - db: dict, - standalone: bool = False, - regions: list[str] | None = None, - platforms_dir: str = _REPO_PLATFORMS, - system_ids: list[str] | None = None, - required_only: bool = False, -) -> dict: - """Verify files for specific emulator profiles. - - A region priority list narrows the report the same way a pack built with the - same list would be narrowed, through the emulator pack's own drop set. - `system_ids` keeps the entries of those systems, as the system pack does. - `required_only` reports on the pack built with --required-only: a loose - file or tree marked ``required: false`` is left out, and an archive when - it and every member it carries are optional, as the builder leaves them. - """ - from packpaths import _resolve_destination - - # Also load aliases for redirect messages - all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) - - selected = _select_profiles(profile_names, all_profiles, standalone) - # The member index only answers a zipped_file entry, and decompressing - # every archive took 23 of the 24 seconds of a run that had none. - zip_contents = ( - build_zip_contents_index(db) - if any(f.get("zipped_file") for _name, profile in selected - for f in profile.get("files") or []) - else {} - ) - - # Build validation index from selected profiles only - selected_profiles = dict(selected) - validation_index = _build_validation_index(selected_profiles) - data_registry = load_data_dir_registry(platforms_dir) - - pack = _EmulatorPack( - db, standalone, required_only, validation_index, zip_contents, data_registry, - ) - - # The emulator pack withdraws these, and the report withdraws the same. - region_drops: set[str] = set() - if regions: - from packextras import emulator_region_drops - - region_drops = emulator_region_drops( - selected, standalone, regions, required_only, db=db, - zip_contents=zip_contents, data_registry=data_registry, - ) - - for emu_name, profile in sorted(selected): - files = _emulator_files( - emu_name, profile, db, standalone, all_profiles, system_ids, - required_only, region_drops, - ) - spares: set[str] = set() - if required_only: - from packextras import emulator_required_spares - - spares = emulator_required_spares( - emu_name, profile, files, standalone, region_drops, db, - validation_index, zip_contents, data_registry=data_registry, - ) - files = [ - fe for fe in files - if fe.get("archive") or _resolve_destination(fe, standalone) not in spares - ] - pack.verify_profile(emu_name, profile, files, spares) - - counts = { - Severity.OK: 0, - Severity.INFO: 0, - Severity.WARNING: 0, - Severity.CRITICAL: 0, - } - for s in pack.file_severity.values(): - counts[s] = counts.get(s, 0) + 1 - status_counts: dict[str, int] = {} - for s in pack.file_status.values(): - status_counts[s] = status_counts.get(s, 0) + 1 - - label = _effective_validation_label(pack.details, validation_index) - - gt_filenames = set(validation_index) - total = len(pack.file_status) - with_validation = sum( - 1 for dest in pack.file_status if pack.dest_to_name.get(dest, "") in gt_filenames - ) - - return { - "emulators": [n for n, _ in selected], - "verification_mode": label, - "total_files": total, - # The paths the emulator pack fills with the profile's files, for the - # pipeline's comparison with the pack built in memory. - "pack_destinations": sorted(pack.packed_dests), - "severity_counts": counts, - "status_counts": status_counts, - "details": pack.details, - "set_members": pack.set_members, - "data_dir_notices": sorted(set(pack.data_dir_notices)), - "ground_truth_coverage": { - "with_validation": with_validation, - "platform_only": total - with_validation, - "total": total, - }, - } - - -def verify_system( - system_ids: list[str], - emulators_dir: str, - db: dict, - standalone: bool = False, - regions: list[str] | None = None, - platforms_dir: str = _REPO_PLATFORMS, - required_only: bool = False, -) -> dict: - """Verify files for all emulators supporting given system IDs.""" - profiles = load_emulator_profiles(emulators_dir) - matching = profiles_for_systems(profiles, system_ids, standalone) - - if not matching: - all_systems: set[str] = set() - for p in profiles.values(): - all_systems.update(p.get("systems", [])) - if standalone: - print( - f"No standalone emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - else: - print( - f"No emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - # --list-systems merges spellings that differ in case or separator: - # the hint counted 579 spellings for the 532 lines it prints. - print(suggest_names(system_ids, sorted(all_systems), "--list-systems", - listed=len(system_index(profiles))), - file=sys.stderr) - sys.exit(1) - - return verify_emulator( - matching, emulators_dir, db, standalone, regions=regions, - platforms_dir=platforms_dir, system_ids=system_ids, required_only=required_only, - ) - - -def _emulator_summary_parts(result: dict) -> list[str]: - total = result["total_files"] - ok_count = result["severity_counts"][Severity.OK] - sc = result.get("status_counts", {}) - untested = sc.get(Status.UNTESTED, 0) - missing = sc.get(Status.MISSING, 0) - # Counted by slot, as missing is: xash3d's thirteen unsourceable - # pak0.pak and liblist.gam were three names and ten "missing". - missing_slots: dict[str, bool] = {} - for d in result["details"]: - if d["status"] == Status.MISSING: - slot = d.get("destination") or d["name"] - missing_slots[slot] = missing_slots.get(slot, True) and "unsourceable" in d - unsourceable = sum(missing_slots.values()) - parts = [f"{ok_count}/{total} OK"] - if untested: - parts.append(f"{untested} untested") - if missing - unsourceable > 0: - parts.append(f"{missing - unsourceable} missing") - if unsourceable: - parts.append(f"{unsourceable} unsourceable") - return parts - - -def _print_emulator_ground_truth(gt: list[dict], verbose: bool) -> None: - if gt: - if verbose: - for line in _format_ground_truth_verbose(gt): - print(f" {line}") - else: - print(f" {_format_ground_truth_aggregate(gt)}") - - -def _print_emulator_problems(details: list[dict], seen: set[str], verbose: bool) -> None: - """The UNTESTED, MISSING and UNSOURCEABLE lines of an emulator report.""" - for d in details: - if d["status"] == Status.UNTESTED: - if d["name"] in seen: - continue - seen.add(d["name"]) - req = "required" if d.get("required", True) else "optional" - hle = ", HLE available" if d.get("hle_fallback") else "" - reason = d.get("reason", "") - print(f" UNTESTED ({req}{hle}): {d['name']}: {reason}") - _print_emulator_ground_truth(d.get("ground_truth", []), verbose) - for d in details: - if d["status"] == Status.MISSING and "unsourceable" not in d: - if d["name"] in seen: - continue - seen.add(d["name"]) - req = "required" if d.get("required", True) else "optional" - hle = ", HLE available" if d.get("hle_fallback") else "" - others = d.get("alternatives") - either = f" (or {', '.join(others)})" if others else "" - print(f" MISSING ({req}{hle}): {d['name']}{either}") - _print_emulator_ground_truth(d.get("ground_truth", []), verbose) - for d in details: - if d["status"] == Status.MISSING and "unsourceable" in d: - if d["name"] in seen: - continue - seen.add(d["name"]) - why = d.get("unsourceable") or "documented as unobtainable" - print(f" UNSOURCEABLE: {d['name']}: {why}") - - -def _print_emulator_ok(details: list[dict], seen: set[str]) -> None: - for d in details: - if d["status"] == Status.OK: - if d["name"] in seen: - continue - seen.add(d["name"]) - gt = d.get("ground_truth", []) - if gt: - req = "required" if d.get("required", True) else "optional" - print(f" OK ({req}): {d['name']}") - for line in _format_ground_truth_verbose(gt): - print(f" {line}") - - -def print_emulator_result(result: dict, verbose: bool = False) -> None: - """Print verification result for emulator/system mode.""" - label = " + ".join(result["emulators"]) - mode = result["verification_mode"] - parts = _emulator_summary_parts(result) - print(f"{label}: {', '.join(parts)} [{mode}]") - fetched = sorted({d["name"] for d in result["details"] if d.get("release_asset")}) - if fetched: - shown = ", ".join(fetched[:10]) + (f" (+{len(fetched) - 10})" if len(fetched) > 10 else "") - print(f" Release assets fetched when the pack is built ({len(fetched)}): {shown}") - - seen: set[str] = set() - _print_emulator_problems(result["details"], seen, verbose) - - for d in result["details"]: - if d.get("note"): - print(f" {d['note']}") - - if verbose: - _print_emulator_ok(result["details"], seen) - - for ref in result.get("data_dir_notices", []): - print( - f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)" - ) - - gt_cov = result.get("ground_truth_coverage") - if gt_cov and gt_cov["total"] > 0: - pct = round(gt_cov["with_validation"] * 100 / gt_cov["total"]) - print( - f" Ground truth: {gt_cov['with_validation']}/{gt_cov['total']} files have emulator validation ({pct}%)" - ) - if gt_cov["platform_only"]: - print(f" {gt_cov['platform_only']} without declared validation") - - def _refuse_listing_narrowings( args: argparse.Namespace, parser: argparse.ArgumentParser ) -> None: @@ -3746,7 +498,7 @@ def _main(held: contextlib.ExitStack) -> None: if args.platform: require_platform(args.platform, args.platforms_dir) if args.offline: - import packresolve + from resolve import packfiles as packresolve packresolve.set_offline(True) @@ -3760,7 +512,7 @@ def _main(held: contextlib.ExitStack) -> None: system_mode = _check_mode(args, parser) platform_systems = _platform_system_filter(args, parser) # The trees stay put while names resolve against them and files are read. - from refresh_data_dirs import hold_data_dirs + from packs.datadirs import hold_data_dirs hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) diff --git a/tests/test_agnostic_scan.py b/tests/test_agnostic_scan.py index aa47a605b..3636f39ee 100644 --- a/tests/test_agnostic_scan.py +++ b/tests/test_agnostic_scan.py @@ -22,7 +22,7 @@ from pathlib import Path from model.profiles import load_emulator_profiles, _emulator_profiles_cache from resolve.localfile import resolve_local_file import generate_pack as builder -import packextras +from packs import extras as packextras SIZE = 1024 diff --git a/tests/test_agnostic_scan_mode.py b/tests/test_agnostic_scan_mode.py index 1a0c9e6aa..153af40be 100644 --- a/tests/test_agnostic_scan_mode.py +++ b/tests/test_agnostic_scan_mode.py @@ -27,7 +27,7 @@ class ScanFollowsTheBuild(unittest.TestCase): 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 + from packs.extras import _collect_emulator_extras profiles = load_emulator_profiles("emulators") entry = next( diff --git a/tests/test_agnostic_scope.py b/tests/test_agnostic_scope.py index af86883a2..35fcce727 100644 --- a/tests/test_agnostic_scope.py +++ b/tests/test_agnostic_scope.py @@ -22,7 +22,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class AgnosticScan(unittest.TestCase): def test_only_the_bios_directory_seeds_and_finds_keep_its_folder(self): - from packextras import _agnostic_scan_extras + from packs.extras import _agnostic_scan_extras with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() @@ -61,7 +61,7 @@ class AgnosticScan(unittest.TestCase): folder where another profile of the system resolves a hashed dump of that shape is the evidence, that folder only. """ - from packextras import _agnostic_scan_extras + from packs.extras import _agnostic_scan_extras with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() @@ -125,7 +125,7 @@ class OneContentTwoPaths(unittest.TestCase): "files": [{"name": "ps2_scph50006.bin", "standalone_path": "bios/ps2_scph50006.bin"}]} def _copies(self, entries): - from generate_pack import _profile_copies + from packs.standalone import _profile_copies return _profile_copies({"duckstation": self.DUCK}, list(entries), [], entries) diff --git a/tests/test_archive_choice.py b/tests/test_archive_choice.py index 9da6ffd74..e64257198 100644 --- a/tests/test_archive_choice.py +++ b/tests/test_archive_choice.py @@ -86,7 +86,7 @@ class IntegrityChecksEveryMember(unittest.TestCase): def test_a_missing_member_is_an_error_when_the_repository_holds_it(self): import yaml - import packverify + from packs import integrity as packverify roms = {f"r{i}.bin": bytes([i]) * 32 for i in range(3)} with tempfile.TemporaryDirectory() as tmp: @@ -173,7 +173,7 @@ class TheArchiveHoldingTheCoreMembers(unittest.TestCase): self.assertTrue(path.endswith("bios/neocdz.zip")) def test_the_extras_carry_the_members(self): - from packextras import _report_extra + from packs.extras import _report_extra members = [{"crc32": "5a86cff2", "required": True}] extra = _report_extra( @@ -444,7 +444,7 @@ class AnArchiveRankedByWhatItHolds(unittest.TestCase): "bios/MAME/hod2bios.zip") def test_every_claim_path_carries_the_layout(self): - from packextras import _report_extra + from packs.extras import _report_extra contents = [{"name": "epr-21329.ic27", "size": 16}] extra = _report_extra({"name": "hod2bios.zip", "contents": contents}, @@ -470,8 +470,8 @@ class ALooseEntryNamingItsArchive(unittest.TestCase): import yaml from model.profiles import _emulator_profiles_cache - from generate_pack import generate_emulator_pack - from verify import verify_emulator + from packs.emulatorpack import generate_emulator_pack + from packs.emulatorcheck import verify_emulator _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) diff --git a/tests/test_artifact_lock.py b/tests/test_artifact_lock.py index bbb7d6d14..b93eab002 100644 --- a/tests/test_artifact_lock.py +++ b/tests/test_artifact_lock.py @@ -143,7 +143,7 @@ class PackLockCliTest(unittest.TestCase): """The refresh waits for every run holding a data tree, and a pipeline holds them all for its whole run: probed after the refresh, a second build sat silent for hours instead of being refused.""" - from refresh_data_dirs import cache_lock + from packs.datadirs import cache_lock platforms = Path(self.dir) / "platforms" platforms.mkdir() diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index f905c5557..01b1954e3 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -216,14 +216,15 @@ class ScratchFilesGetThePlainMode(unittest.TestCase): def test_packs_and_their_manifest(self): import zipfile - import generate_pack + from packs import archive + from packs import finalize pack = self.dir / "Pack.zip" - with generate_pack._writing_pack(str(pack)) as zf: + with archive._writing_pack(str(pack)) as zf: zf.writestr("a.bin", b"x") self.assertEqual(self._mode(pack), 0o644) os.chmod(pack, 0o600) - generate_pack.inject_manifest(str(pack), {"files": []}) + finalize.inject_manifest(str(pack), {"files": []}) self.assertEqual(self._mode(pack), 0o644) with zipfile.ZipFile(pack) as zf: self.assertIn("manifest.json", zf.namelist()) diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 87cc362f0..b631bf100 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -28,15 +28,13 @@ try: except ImportError: jsonschema = None import install +from packs import verdicts from scripts import pipeline from scripts.resolve import regionaudit, regions 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, - verify_pack_against_platform, -) +from scripts.generate_pack import _emulator_region_group, verify_pack_against_platform +from scripts.packs.targets import generate_target_manifests HAS_JSONSCHEMA = jsonschema is not None ROOT = Path(__file__).resolve().parent.parent @@ -625,7 +623,7 @@ class APackIsSwappedInWhole(unittest.TestCase): def test_a_failed_build_keeps_the_previous_pack(self): import zipfile - from generate_pack import _writing_pack + from packs.archive import _writing_pack directory = self._dir() pack = directory / "Pack.zip" @@ -641,7 +639,7 @@ class APackIsSwappedInWhole(unittest.TestCase): def test_a_finished_build_replaces_it(self): import zipfile - from generate_pack import _writing_pack + from packs.archive import _writing_pack directory = self._dir() pack = directory / "Pack.zip" @@ -705,7 +703,7 @@ class StandaloneCopiesNameTheirSource(unittest.TestCase): switch/prod.keys).""" def _placed(self, copies, dests): - from generate_pack import _placed_copies + from packs.standalone import _placed_copies return _placed_copies(copies, dests) @@ -758,7 +756,7 @@ class StandaloneCopiesComeFromTheProfiles(unittest.TestCase): } def _copies(self, profiles, dests, declared=()): - from generate_pack import _profile_copies + from packs.standalone import _profile_copies return _profile_copies(profiles, dests, list(declared)) @@ -823,7 +821,7 @@ class ADamagedArchiveIsNotPacked(unittest.TestCase): def test_the_rebuild_refusal_reaches_the_run(self): import zipfile - from generate_pack import DamagedArchiveError, _add_zip_to_pack + from packs.archive import DamagedArchiveError, _add_zip_to_pack with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: source = Path(directory) / "set.zip" @@ -849,7 +847,7 @@ class APackedArchiveKeepsItsBytes(unittest.TestCase): import hashlib import zipfile - from generate_pack import _add_zip_to_pack + from packs.archive import _add_zip_to_pack with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: source = Path(directory) / "set.zip" @@ -870,7 +868,7 @@ class PackReadmesSayWhatTheInstallerDoes(unittest.TestCase): RetroArch README offered only `| sh`, which Windows cannot run.""" def _guide(self, platform: str) -> str: - from packreadme import _build_readme + from packs.readme import _build_readme registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) install = registry["platforms"][platform].get("install") or {} @@ -1447,7 +1445,7 @@ class OneBaselineVerdict(unittest.TestCase): without d32.rom is one the builder left out on purpose.""" import hashlib - from scripts.packverify import _intentional_hash_exclusion + from scripts.packs.integrity import _intentional_hash_exclusion entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""} with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: @@ -1518,7 +1516,7 @@ class OneBaselineVerdict(unittest.TestCase): self.assertTrue(digest_verdict(plain, 0, lambda: {"md5": raw}, "md5")) def test_a_release_asset_keeps_its_answer(self): - from scripts.packresolve import apply_override + from scripts.resolve.packfiles import apply_override self.assertEqual( apply_override("bios/x.bin", "/cache/big.bin", "release_asset"), @@ -1563,8 +1561,8 @@ class OneBaselineVerdict(unittest.TestCase): def test_verify_finds_the_cached_release_asset(self): # verify imports the scripts directory's modules by their bare names. - import packresolve - from scripts.verify import _resolve_for_platform + from resolve import packfiles as packresolve + from scripts.packs.coverage import _resolve_for_platform with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: cached = Path(directory) / "BIG.PUP" @@ -1856,7 +1854,7 @@ class RegionRegressions(unittest.TestCase): under none of its four systems: emulator mode grouped them and dropped pac-n1.bin for --region us, platform mode isolated each and kept it.""" - from packextras import extra_region_groups + from packs.extras import extra_region_groups profile = {"systems": ["nec-pc-engine", "nec-pc-engine-cd", "nec-supergrafx", "pioneer-laseractive"]} @@ -2012,26 +2010,21 @@ class NoMd5IsNotNothingChecked(unittest.TestCase): sha256 and no md5. """ - def setUp(self): - import verify - - self.verify = verify - def _entry(self): return {"name": "dsifirmware.bin", "sha256": "b" * 64} def test_a_contradicted_sha256_is_not_reported_ok(self): - result = self.verify.verify_entry_md5( + result = verdicts.verify_entry_md5( self._entry(), "bios/whatever.bin", "hash_mismatch" ) - self.assertNotEqual(result["status"], self.verify.Status.OK) + self.assertNotEqual(result["status"], verdicts.Status.OK) self.assertIn("contradicted", result.get("reason", "")) def test_a_clean_resolution_is_still_ok(self): - result = self.verify.verify_entry_md5( + result = verdicts.verify_entry_md5( self._entry(), "bios/whatever.bin", "sha256_exact" ) - self.assertEqual(result["status"], self.verify.Status.OK) + self.assertEqual(result["status"], verdicts.Status.OK) class InstallerBoundaryRegressions(unittest.TestCase): @@ -2147,7 +2140,7 @@ class InstallerBoundaryRegressions(unittest.TestCase): in the pack's manifest.json, which install.py reads with the pack alone. The pack schema refused both keys, and each is checked under its own contract.""" - import generate_pack + from packs import scope import validate_schemas install_list = json.loads((ROOT / "install" / "romm.json").read_text(encoding="utf-8")) @@ -2159,8 +2152,8 @@ class InstallerBoundaryRegressions(unittest.TestCase): "summary": {"total_files": 0, "verified": 0, "untracked": 0, "errors": 0}, "errors": [], } - generate_pack.annotate_pack_systems( - document, generate_pack.pack_systems(install_list, targets)) + scope.annotate_pack_systems( + document, scope.pack_systems(install_list, targets)) self.assertIn("install_list", document) self.assertIn("targets", document) with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: @@ -2641,7 +2634,7 @@ class ReleaseAssetCriterion(unittest.TestCase): return directory def test_a_large_committed_file_is_served_by_the_repository(self): - from scripts import generate_pack + from scripts.packs import manifestentry with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = self._repo(directory, "bios/elsewhere.bin") @@ -2649,44 +2642,44 @@ class ReleaseAssetCriterion(unittest.TestCase): big.parent.mkdir() with big.open("wb") as handle: handle.truncate(60_000_000) - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() try: - self.assertFalse(generate_pack._is_release_asset(str(big), root)) + self.assertFalse(manifestentry._is_release_asset(str(big), root)) finally: - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() def test_the_manifest_names_the_asset_as_github_serves_it(self): # GitHub publishes a space as a dot. The site linked the dotted # name while the manifest gave install.py the spaced one, a 404. - from scripts import generate_pack + from scripts.packs import manifestentry with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = self._repo(directory, "bios/MAME/MAME 0.174 Arcade XML.dat") target = Path(root, "bios", "MAME", "MAME 0.174 Arcade XML.dat") target.parent.mkdir(parents=True) target.write_bytes(b"x") - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() try: self.assertEqual( - generate_pack._release_asset_name(str(target), root), + manifestentry._release_asset_name(str(target), root), "MAME.0.174.Arcade.XML.dat", ) finally: - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() def test_a_gitignored_file_is_served_by_the_release_whatever_its_size(self): - from scripts import generate_pack + from scripts.packs import manifestentry with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: root = self._repo(directory, "bios/small.zip") small = Path(root, "bios", "small.zip") small.parent.mkdir() small.write_bytes(b"PK") - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() try: - self.assertTrue(generate_pack._is_release_asset(str(small), root)) + self.assertTrue(manifestentry._is_release_asset(str(small), root)) finally: - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() class ReleaseAssetsMatchTheCollection(unittest.TestCase): @@ -3355,7 +3348,7 @@ class APackNameFitsAFileName(unittest.TestCase): before writing anything, while verify --system snes reported.""" def test_a_long_selection_is_bounded_and_told_apart(self): - from scripts.generate_pack import MAX_PACK_NAME_BYTES, _bounded_pack_name + from scripts.packs.naming import MAX_PACK_NAME_BYTES, _bounded_pack_name names = [f"Emulator_Number_{i}" for i in range(23)] long_name = _bounded_pack_name(names, names, "_BIOS_Pack.zip") @@ -3367,7 +3360,7 @@ class APackNameFitsAFileName(unittest.TestCase): def test_a_long_system_list_is_bounded(self): """Thirty systems joined made a 261-byte platform pack name.""" - from scripts.generate_pack import MAX_SYSTEM_TAG_BYTES, _system_tag + from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, _system_tag systems = [f"vendor-console-number-{i}" for i in range(30)] tag = _system_tag(systems) @@ -3378,7 +3371,7 @@ class APackNameFitsAFileName(unittest.TestCase): def test_two_systems_never_name_one_system(self): """sega-dreamcast,arcade and sega-dreamcast-arcade both wrote RetroArch_..._Dreamcast_Arcade.zip, and the second replaced the first.""" - from scripts.generate_pack import _system_tag + from scripts.packs.naming import _system_tag pairs = [ (["sega-dreamcast", "arcade"], ["sega-dreamcast-arcade"]), @@ -3420,7 +3413,7 @@ class ARegionDroppedExtraBlocksNothing(unittest.TestCase): def test_the_report_skips_what_the_region_pass_drops(self): from unittest import mock - from scripts import packextras + from scripts.packs import extras as packextras with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: other = Path(directory) / "FOO.ROM" @@ -3503,7 +3496,7 @@ class AnotherEmulatorsTreeProvesNothing(unittest.TestCase): self.assertTrue(patches.endswith("PlayStation 2/patches.zip")) def test_no_desktop_retroarch_pack_serves_armsx2s_tree(self): - from scripts import slots + from scripts.packs import slots from scripts.model.registry import load_data_dir_registry from scripts.model.database import load_database from scripts.model.profiles import load_emulator_profiles @@ -3531,7 +3524,7 @@ class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase): def test_the_content_naming_claim_is_placed_first(self): from unittest import mock - from scripts import packextras + from scripts.packs import extras as packextras undeclared = [ {"profile": "hypseus", "emulator": "hypseus", "name": "db.txt", @@ -3540,7 +3533,7 @@ class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase): "path": "db.txt", "in_repo": True, "systems": ["b"], "sha1": "a" * 40}, ] config = {"systems": {}, "base_destination": "bios"} - with mock.patch("verify.find_undeclared_files", return_value=undeclared), \ + with mock.patch("packs.gaps.find_undeclared_files", return_value=undeclared), \ mock.patch.object(packextras, "resolve_platform_cores", return_value=set()) as cores: extras = packextras._collect_emulator_extras( @@ -3673,7 +3666,7 @@ class APackNoteBesideItsSlotIsANote(unittest.TestCase): a pack holding games/keen6/INSTRUCTIONS_egagraph.ck6.txt.""" def test_a_nested_note_is_not_hashed_against_the_collection(self): - from scripts.packverify import verify_pack + from scripts.packs.integrity import verify_pack with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: path = Path(directory) / "Pack.zip" @@ -4037,7 +4030,7 @@ class AnAcceptedVersionIsNoCoreDiscrepancy(unittest.TestCase): "source_path": "NWINTER.GRP", "source_profile": "eduke32"} def test_a_sibling_version_matches(self): - from scripts.generate_pack import _matches_an_alternative + from scripts.packs.platformpack import _matches_an_alternative with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: held = Path(tmp) / "NWINTER.GRP" @@ -4048,7 +4041,7 @@ class AnAcceptedVersionIsNoCoreDiscrepancy(unittest.TestCase): self._extra(), str(held), {"eduke32": profile})) def test_a_copy_no_entry_declares_still_disagrees(self): - from scripts.generate_pack import _matches_an_alternative + from scripts.packs.platformpack import _matches_an_alternative with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: held = Path(tmp) / "NWINTER.GRP" @@ -4310,7 +4303,7 @@ class ASameNamedMemberIsNotTheFile(unittest.TestCase): while verify --emulator said missing.""" def test_a_declared_hash_decides_a_member_or_data_hit(self): - from scripts import cross_reference as xr + from scripts.packs import crossref tmp = Path(tempfile.mkdtemp(dir=TMP_ROOT)) self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True)) @@ -4319,16 +4312,16 @@ class ASameNamedMemberIsNotTheFile(unittest.TestCase): (tmp / "bios").mkdir() with zipfile.ZipFile(tmp / "bios" / "extras.zip", "w") as zf: zf.writestr("files/other.ttf", b"MEMBER FONT") - names = xr._build_supplemental_index(str(tmp / "data"), str(tmp / "bios")) - locations = xr._supplemental_locations(str(tmp / "data"), str(tmp / "bios")) - with mock.patch.object(xr, "_supplemental_locations", lambda: locations): + names = crossref._build_supplemental_index(str(tmp / "data"), str(tmp / "bios")) + locations = crossref._supplemental_locations(str(tmp / "data"), str(tmp / "bios")) + with mock.patch.object(crossref, "_supplemental_locations", lambda: locations): for fname, data in (("font.ttf", b"DATA FONT"), ("other.ttf", b"MEMBER FONT")): with self.subTest(name=fname): held = {"name": fname, "sha1": hashlib.sha1(data).hexdigest()} other = {"name": fname, "sha1": "0" * 40} - self.assertTrue(xr._data_hit(fname, None, held, names)) - self.assertFalse(xr._data_hit(fname, None, other, names)) - self.assertTrue(xr._data_hit(fname, None, {"name": fname}, names)) + self.assertTrue(crossref._data_hit(fname, None, held, names)) + self.assertFalse(crossref._data_hit(fname, None, other, names)) + self.assertTrue(crossref._data_hit(fname, None, {"name": fname}, names)) class AnEmptyTargetIsNotEveryCore(unittest.TestCase): @@ -4337,7 +4330,7 @@ class AnEmptyTargetIsNotEveryCore(unittest.TestCase): def test_the_published_list_is_the_builder_reading(self): from scripts.model.targets import load_target_config - from scripts.generate_pack import generate_target_manifests + from scripts.packs.targets import generate_target_manifests tmp = Path(tempfile.mkdtemp(dir=TMP_ROOT)) self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True)) @@ -4386,7 +4379,7 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase): def test_a_holder_makes_the_refresh_lock_wait(self): import fcntl - from scripts import refresh_data_dirs + from scripts.packs import datadirs cache = self.tmp / "bluemsx" cache.mkdir() @@ -4402,7 +4395,7 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase): return True with contextlib.ExitStack() as held: - refresh_data_dirs.hold_data_dirs(held, {"bluemsx": {"local_cache": str(cache)}}) + datadirs.hold_data_dirs(held, {"bluemsx": {"local_cache": str(cache)}}) self.assertFalse(exclusive_free()) self.assertTrue(exclusive_free()) @@ -4411,12 +4404,12 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase): missing for verify and present for the packs of the same run.""" import fcntl - from scripts import refresh_data_dirs + from scripts.packs import datadirs cache = self.tmp / "absent" lock = cache.with_name(f".{cache.name}.lock") with contextlib.ExitStack() as held: - refresh_data_dirs.hold_data_dirs(held, {"absent": {"local_cache": str(cache)}}) + datadirs.hold_data_dirs(held, {"absent": {"local_cache": str(cache)}}) self.assertFalse(cache.exists()) with open(lock, "a") as handle, self.assertRaises(BlockingIOError): fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -4442,15 +4435,15 @@ class EachRootReadsItsOwnRegistry(unittest.TestCase): was asked: a second tree got the first tree's .gitignore.""" def test_two_roots_in_one_process(self): - from scripts import generate_pack + from scripts.packs import manifestentry with tempfile.TemporaryDirectory(dir=TMP_ROOT) as a, \ tempfile.TemporaryDirectory(dir=TMP_ROOT) as b: Path(a, ".gitignore").write_text("bios/one.bin\n") Path(b, ".gitignore").write_text("bios/two.bin\n") - self.assertTrue(generate_pack._is_release_asset(str(Path(a, "bios/one.bin")), a)) - self.assertFalse(generate_pack._is_release_asset(str(Path(b, "bios/one.bin")), b)) - self.assertTrue(generate_pack._is_release_asset(str(Path(b, "bios/two.bin")), b)) + self.assertTrue(manifestentry._is_release_asset(str(Path(a, "bios/one.bin")), a)) + self.assertFalse(manifestentry._is_release_asset(str(Path(b, "bios/one.bin")), b)) + self.assertTrue(manifestentry._is_release_asset(str(Path(b, "bios/two.bin")), b)) def test_one_parser_reads_the_registry(self): for module in ("generate_pack.py", "generate_db.py"): @@ -4485,7 +4478,7 @@ class EveryReadmeNamesItsFolder(unittest.TestCase): /storage/system, the folder the registry and the installer use.""" def test_the_registry_folder_is_in_the_guide(self): - from scripts.packreadme import _build_readme + from scripts.packs.readme import _build_readme registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) for name, entry in registry["platforms"].items(): @@ -4650,7 +4643,8 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase): def test_the_targets_are_verify_verdicts(self): from scripts import auto_fetch - import verify as verify_mod + from packs import coverage as packs_coverage + from packs import verdicts config = {"verification_mode": "md5", "systems": {"s": {"files": [ {"name": "ok.bin", "md5": "1" * 32}, @@ -4659,9 +4653,9 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase): ]}}} result = { "details": [ - {"system": "s", "name": "ok.bin", "status": verify_mod.Status.OK}, - {"system": "s", "name": "gone.bin", "status": verify_mod.Status.MISSING}, - {"system": "s", "name": "bad.bin", "status": verify_mod.Status.UNTESTED}, + {"system": "s", "name": "ok.bin", "status": verdicts.Status.OK}, + {"system": "s", "name": "gone.bin", "status": verdicts.Status.MISSING}, + {"system": "s", "name": "bad.bin", "status": verdicts.Status.UNTESTED}, ], "undeclared_files": [ {"name": "diabdat.mpq", "in_repo": False, "required": True, @@ -4674,7 +4668,7 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase): "bundled": True, "emulator": "ZEsarUX"}, ], } - with mock.patch.object(verify_mod, "verify_platform", lambda c, d: result): + with mock.patch.object(packs_coverage, "verify_platform", lambda c, d: result): names = [m["name"] for m in auto_fetch.find_missing(config, {})] self.assertEqual(names, ["gone.bin", "bad.bin", "diabdat.mpq"]) @@ -4733,14 +4727,14 @@ class TheToolsPageSaysWhatDedupDoes(unittest.TestCase): named 2 of the 11 directories dedup leaves alone.""" def test_every_protected_tree_is_named(self): - from scripts import dedup + from scripts.model import nodedup line = next( row for row in (ROOT / "wiki" / "tools.md").read_text().splitlines() if row.startswith("| `dedup.py`") ) self.assertNotIn(".variants", line) - for name in dedup.NODEDUP_DIRS: + for name in nodedup.NODEDUP_DIRS: self.assertIn(name, line) @@ -4842,7 +4836,7 @@ class AFileToSourceIsAFileNotAName(unittest.TestCase): def test_rows_are_keyed_by_name_and_hash(self): source = (ROOT / "scripts" / "generate_site.py").read_text() self.assertIn('key = (g["name"], g.get("identity") or f"emulator:{emu_name}")', source) - from scripts.cross_reference import _first_hash + from scripts.packs.crossref import _first_hash self.assertEqual(_first_hash({"md5": ["AB", "cd"]}), "md5:ab") self.assertEqual(_first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40) @@ -4946,6 +4940,7 @@ class AManifestHashesAFileOnce(unittest.TestCase): def test_verified_hashes_are_reused(self): from scripts import generate_pack + from scripts.packs import manifestentry with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: path = Path(tmp, "a.bin") @@ -4960,8 +4955,8 @@ class AManifestHashesAFileOnce(unittest.TestCase): return real(file_path, algorithms) with mock.patch.object(generate_pack, "compute_hashes", counting): - first = generate_pack._stable_hashes(str(path), db) - second = generate_pack._stable_hashes(str(path), db) + first = manifestentry._stable_hashes(str(path), db) + second = manifestentry._stable_hashes(str(path), db) self.assertEqual(first, second) self.assertEqual(len(calls), 1) self.assertEqual(calls[0], frozenset({"sha1", "sha256"})) @@ -4999,7 +4994,7 @@ class CompanionsComeFromADirectoryIndex(unittest.TestCase): """_companions walked the whole database per scanned image.""" def test_same_answer_one_walk(self): - from scripts import packextras + from scripts.packs import extras as packextras files_db = { "a": {"path": "bios/Sony/PS2/ps2.bin", "name": "ps2.bin"}, @@ -5090,7 +5085,7 @@ class ATreeNobodyHoldsIsMissingNotAnAsset(unittest.TestCase): def test_directory_entries_never_reach_the_asset_store(self): from scripts.model import largefiles - from scripts import packresolve + from scripts.resolve import packfiles as packresolve db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_crc32": {}, "by_path_suffix": {}}} @@ -5302,9 +5297,10 @@ class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase): def test_counts_carry_platforms_and_core_misses(self): import verify + from packs import verdicts clean = {"severity_counts": {}, "undeclared_files": []} - warned = {"severity_counts": {verify.Severity.WARNING: 1}, "undeclared_files": []} + warned = {"severity_counts": {verdicts.Severity.WARNING: 1}, "undeclared_files": []} core_miss = { "severity_counts": {}, "undeclared_files": [{ @@ -5372,10 +5368,11 @@ class BundledFilesAreNotToSource(unittest.TestCase): def test_verify_does_not_count_it_missing(self): import verify + from packs import report as packs_report entry = {"name": "n64.psh", "required": True, "in_repo": False, "category": "bios", "in_pack": True, "bundled": True} - self.assertEqual(verify._core_required_missing([entry]), []) + self.assertEqual(packs_report._core_required_missing([entry]), []) summary = verify._overall_summary( [({"severity_counts": {}, "undeclared_files": [entry]}, ["ROCKNIX"])] ) @@ -5394,12 +5391,12 @@ class BundledFilesAreNotToSource(unittest.TestCase): def test_a_held_bundled_file_is_not_packed(self): """A file installed with the emulator is already on the user's machine, so the pack leaves it out even when the collection holds it.""" - import verify + from packs import coverage as packs_coverage entry = {"name": "n64.psh", "required": True, "in_repo": True, "emulator": "daedalusx64", "category": "bios", "bundled": True} - with mock.patch("packextras.unplaceable_extras", return_value={}): - verify._mark_unplaced({}, [entry], {}) + with mock.patch("packs.extras.unplaceable_extras", return_value={}): + packs_coverage._mark_unplaced({}, [entry], {}) self.assertFalse(entry["in_pack"]) self.assertIn("installed with its emulator", entry["omitted"]) @@ -5540,10 +5537,11 @@ class GapsPageCountsOneWay(unittest.TestCase): self.assertEqual(_declared_destination(config, detail), "bios/quasi88/N88_KNJ1.ROM") def test_verify_marks_the_settled_entry(self): - import verify + from packs import coverage as packs_coverage + from packs import verdicts - result = {"name": "cdibios.zip", "status": verify.Status.UNTESTED} - self.assertTrue(verify._twin_unmet(result, "arcade")) + result = {"name": "cdibios.zip", "status": verdicts.Status.UNTESTED} + self.assertTrue(packs_coverage._twin_unmet(result, "arcade")) self.assertEqual(result["settled_by"], "arcade") @@ -5914,7 +5912,7 @@ class ZippedFileMd5IsParsedOnce(unittest.TestCase): import zipfile as zf_mod from scripts.resolve.validation import inner_rom_check - from scripts.verify import verify_entry_md5 + from scripts.packs.verdicts import verify_entry_md5 with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: archive = Path(directory, "x.zip") @@ -5942,7 +5940,7 @@ class AHashListIsReadOneWay(unittest.TestCase): profile_sync looked the whole string up and called it missing.""" def test_every_reader_splits_the_list(self): - from scripts.cross_reference import _declared_content + from scripts.packs.crossref import _declared_content from scripts.core.hashing import parse_hash_list from scripts.profiling.citations import entry_hashes @@ -6015,7 +6013,7 @@ class RommNeoGeoFoldersGetTheirBios(unittest.TestCase): # into neogeoaes/, and FBNeo's CPS3 sets already sat in colecovision/: # a system the platform lacks has no folder, and a mirror-only # folder attracts no system-less file. - from scripts.packextras import _slug_for + from scripts.packs.extras import _slug_for config_systems = {"arcade", "snk-neogeo-aes", "nintendo-ds"} sys_to_slug = {"arcade": "arcade", "snk-neogeo-aes": "neogeoaes", @@ -6226,7 +6224,8 @@ class TheGroundTruthFooterSaysWhatItCounts(unittest.TestCase): import io as _io from contextlib import redirect_stdout - from scripts.verify import Severity, print_platform_result + from scripts.packs.verdicts import Severity + from scripts.packs.report import print_platform_result out = _io.StringIO() counts = {Severity.OK: 1, Severity.INFO: 0, Severity.WARNING: 0, Severity.CRITICAL: 0} @@ -6275,7 +6274,7 @@ class StrictFailsOnMissingOnly(unittest.TestCase): def test_the_contract(self): from scripts import verify as verify_mod - from scripts.verify import Severity + from scripts.packs.verdicts import Severity verify_mod._exit_if_strict(True, [{"severity_counts": {Severity.WARNING: 2}}]) with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()): @@ -6615,7 +6614,7 @@ class ThePackCheckAppliesTheFrontendRule(unittest.TestCase): import hashlib import zipfile - from scripts.packverify import _check_member_hash + from scripts.packs.integrity import _check_member_hash payload = b"revision B" entry = { @@ -6846,7 +6845,7 @@ class DocsDescribeTheRegistriesTheyName(unittest.TestCase): self.assertEqual(offenders, []) def test_the_dedup_list_is_named_whole_or_by_its_constant(self): - from dedup import NODEDUP_DIRS + from model.nodedup import NODEDUP_DIRS tools = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") line = next(entry for entry in tools.splitlines() if "NODEDUP_DIRS" in entry) # Compared as list items: `mame` was missing while the substring @@ -7100,7 +7099,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase): keypad when absent (FreeIntv src/libretro.c:294-296, 350-369).""" def _members(self, required_only: bool) -> list[str]: - from scripts import generate_pack as gp + from scripts.packs import datatrees with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: for key in ("needed", "optional"): @@ -7120,7 +7119,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase): } return [ dest - for _src, dest in gp._data_directory_members( + for _src, dest in datatrees._data_directory_members( systems, registry, "retroarch", "", False, set(), set(), set(), required_only=required_only, ) @@ -7213,12 +7212,12 @@ class PlatformSystemTypoGetsTheClosestNames(unittest.TestCase): systems of the alphabet, 3do to coleco-colecovision.""" def test_the_hint_names_the_close_systems(self): - from scripts import generate_pack as gp + from scripts.packs import platformpack out = io.StringIO() with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp, \ contextlib.redirect_stdout(out): - result = gp.generate_pack( + result = platformpack.generate_pack( "retroarch", str(ROOT / "platforms"), {"files": {}, "indexes": {}}, str(ROOT / "bios"), tmp, emulators_dir=str(ROOT / "emulators"), system_filter=["sony-playstaton"], offline=True, @@ -7236,7 +7235,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase): found in input".""" def test_digests_are_read_by_length(self): - from scripts.packresolve import parse_hash_input + from scripts.resolve.packfiles import parse_hash_input sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" self.assertEqual(parse_hash_input(f"0x1A2B3C4D,{sha256}"), [ @@ -7245,7 +7244,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase): self.assertEqual(parse_hash_input("a" * 29), [("md5", "a" * 29)]) def test_anything_else_is_refused_with_the_formats(self): - from scripts.packresolve import parse_hash_file, parse_hash_input + from scripts.resolve.packfiles import parse_hash_file, parse_hash_input for raw in ("1234567890ab", "zz", "490f666e1afb15b7362b406ed1cea246,zz"): with self.subTest(raw=raw), self.assertRaises(ValueError) as ctx: @@ -7259,7 +7258,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase): self.assertIn("line 3 (b.bin)", str(ctx.exception)) def test_a_sha256_finds_its_file(self): - from scripts.packresolve import sha1_for_hash + from scripts.resolve.packfiles import sha1_for_hash db = json.loads((ROOT / "database.json").read_text(encoding="utf-8")) sha1, entry = next( @@ -7463,7 +7462,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase): return response def test_offline_never_reaches_the_network(self): - import packresolve + from resolve import packfiles as packresolve with tempfile.TemporaryDirectory() as tmp, \ mock.patch.object(packresolve.urllib.request, "urlopen") as urlopen, \ @@ -7473,7 +7472,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase): urlopen.assert_not_called() def test_the_run_switch_is_inherited(self): - import packresolve + from resolve import packfiles as packresolve saved = packresolve._OFFLINE packresolve.set_offline(True) @@ -7487,7 +7486,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase): packresolve.set_offline(saved) def test_a_verified_body_lands_and_a_wrong_one_is_removed(self): - import packresolve + from resolve import packfiles as packresolve with tempfile.TemporaryDirectory() as tmp: target = Path(tmp) / "x" @@ -7868,7 +7867,7 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase): claims with it.""" def test_a_host_its_emulator_installs_leaves_the_others_in_the_pack(self): - from verify import _split_bundled_claims + from packs.gaps import _split_bundled_claims dsperate = {"profile": "dsperate", "name": "usrcheat.dat", "in_repo": True} drastic = {"profile": "drastic", "name": "usrcheat.dat", "bundled": True, @@ -7883,14 +7882,14 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase): def test_a_held_file_out_of_reach_names_every_core_reading_it(self): """harm1.wad is a release asset: a checkout without it omits the file, and the omission named gzdoom alone where lzdoom reads it too.""" - from generate_pack import _claim_cores + from packs.manifestentry import _claim_cores extra = {"source_profile": "gzdoom", "other_claims": [ {"source_profile": "uzdoom"}, {"source_profile": "lzdoom"}]} self.assertEqual(_claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"]) def test_a_missing_file_names_every_core_reading_it(self): - from generate_pack import _record_absent + from packs.manifestentry import _record_absent omitted: dict[str, dict] = {} diff --git a/tests/test_batocera_md5_list.py b/tests/test_batocera_md5_list.py index b7a005345..5029aa290 100644 --- a/tests/test_batocera_md5_list.py +++ b/tests/test_batocera_md5_list.py @@ -31,7 +31,7 @@ from scraper.batocera_scraper import ( requirements_from_systems, ) from siteexports import describe_change -from verify import Status, verify_entry_md5 +from packs.verdicts import Status, verify_entry_md5 REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_bios_companions.py b/tests/test_bios_companions.py index 73486ca37..324f41732 100644 --- a/tests/test_bios_companions.py +++ b/tests/test_bios_companions.py @@ -15,7 +15,7 @@ import unittest from pathlib import Path import yaml -from packextras import _companion_extensions, _companions +from packs.extras import _companion_extensions, _companions REPO_ROOT = Path(__file__).resolve().parents[1] @@ -66,7 +66,7 @@ class Companions(unittest.TestCase): import os import tempfile - from packextras import _agnostic_scan_extras + from packs.extras import _agnostic_scan_extras profile = { "emulator": "PCSX2", "bios_mode": "agnostic", "files": [ @@ -117,7 +117,7 @@ class Companions(unittest.TestCase): import os import tempfile - from packextras import _agnostic_scan_extras + from packs.extras import _agnostic_scan_extras def profile(name: str, ext: str) -> dict: return {"emulator": name, "bios_mode": "agnostic", "files": [ diff --git a/tests/test_cache_independent_counts.py b/tests/test_cache_independent_counts.py index 0f89237c9..d5086d66c 100644 --- a/tests/test_cache_independent_counts.py +++ b/tests/test_cache_independent_counts.py @@ -25,7 +25,7 @@ class DeclaredFilesResolveWithoutDataCaches(unittest.TestCase): 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 + from resolve.packfiles import resolve_declaration platforms_dir = REPO_ROOT / "platforms" registry = load_data_dir_registry(str(platforms_dir)) diff --git a/tests/test_case_insensitive_platforms.py b/tests/test_case_insensitive_platforms.py index d71960080..fb98502e8 100644 --- a/tests/test_case_insensitive_platforms.py +++ b/tests/test_case_insensitive_platforms.py @@ -18,6 +18,8 @@ import unittest from pathlib import Path import yaml +from packs import archive +from packs import platformpack from model.platforms import load_platform_config @@ -45,9 +47,6 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): from model.platforms import _platform_config_cache from model.profiles import _emulator_profiles_cache import generate_db - import generate_pack - - self.gp = generate_pack tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -88,18 +87,18 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): }}})) _platform_config_cache.clear() texts: dict[str, str] = {} - real = self.gp._write_generated_member + real = archive._write_generated_member def capture(zf, arcname, text): texts[arcname] = text return real(zf, arcname, text) - self.gp._write_generated_member = capture + archive._write_generated_member = capture self.addCleanup(setattr, self.gp, "_write_generated_member", real) with contextlib.redirect_stdout(io.StringIO()): - self.gp.generate_pack( + platformpack.generate_pack( "p", "platforms", self.db, "bios", "", emulators_dir="emulators", - offline=True, record=self.gp.PackRecord(), + offline=True, record=archive.PackRecord(), ) return texts["README.txt"] diff --git a/tests/test_content_checks.py b/tests/test_content_checks.py index a049b1215..94bb29b83 100644 --- a/tests/test_content_checks.py +++ b/tests/test_content_checks.py @@ -23,7 +23,7 @@ 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 packs import extras as packextras from core.romdir import romdir_accepts, walk from resolve.validation import _build_validation_index, check_file_validation diff --git a/tests/test_contributing_text.py b/tests/test_contributing_text.py index d585e9e3f..6d22efbd5 100644 --- a/tests/test_contributing_text.py +++ b/tests/test_contributing_text.py @@ -100,13 +100,13 @@ class BeforeOpeningAPullRequest(unittest.TestCase): def test_a_file_too_large_for_git_has_a_route(self): """The guide sent any file over 25 MB through a clone, which GitHub refuses past 100 MB, and only a maintainer can write to the release.""" - import validate_pr + from resolve import review text = generate_readme.generate_contributing() section = text.split("## What happens next", 1)[1].split("\n## ", 1)[0] - self.assertEqual(validate_pr.MAX_FILE_SIZE, 100 * 1024 * 1024) + self.assertEqual(review.MAX_FILE_SIZE, 100 * 1024 * 1024) self.assertIn("100 MB", section) - self.assertIn(f"]({validate_pr.LARGE_FILE_ISSUE_URL})", section) + self.assertIn(f"]({review.LARGE_FILE_ISSUE_URL})", section) def test_it_installs_what_the_checks_need_and_no_site_package(self): """The site is built by Node from website/package-lock.json: a pip @@ -177,7 +177,7 @@ class OneFileThroughTheBrowser(unittest.TestCase): import os import tempfile - import validate_pr + from resolve import review scratch = REPO_ROOT / "tmp" / "tests" scratch.mkdir(parents=True, exist_ok=True) @@ -191,7 +191,7 @@ class OneFileThroughTheBrowser(unittest.TestCase): cwd = os.getcwd() os.chdir(directory) try: - result = validate_pr.validate_file("bios/boot.rom", None, hashes) + result = review.validate_file("bios/boot.rom", None, hashes) finally: os.chdir(cwd) self.assertTrue(result.passed) diff --git a/tests/test_core_data_trees.py b/tests/test_core_data_trees.py index 7cf96e29b..b56071e90 100644 --- a/tests/test_core_data_trees.py +++ b/tests/test_core_data_trees.py @@ -22,7 +22,9 @@ 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 packs import archive +from packs import datatrees +from packs import platformpack from resolve.validation import deliverable, read_from_system_dir REPO_ROOT = Path(__file__).resolve().parent.parent @@ -67,7 +69,7 @@ CONFIG = { class CoreDataTreesTest(unittest.TestCase): def trees(self, platform: str = "plat", registry: dict | None = None) -> list[dict]: - return builder.core_data_trees( + return datatrees.core_data_trees( CONFIG, PROFILES, platform, REGISTRY if registry is None else registry ) @@ -96,17 +98,17 @@ class CoreDataTreesTest(unittest.TestCase): twin = {**PROFILES["demo"], "emulator": "Twin", "cores": ["twin"]} profiles = {**PROFILES, "twin": twin} config = {**CONFIG, "cores": ["demo", "solo", "twin"]} - trees = builder.core_data_trees(config, profiles, "plat", REGISTRY) + trees = datatrees.core_data_trees(config, profiles, "plat", REGISTRY) shared = [t for t in trees if t["ref"] == "shared"] self.assertEqual(len(shared), 1) self.assertEqual(shared[0]["readers"], ["demo", "twin"]) - self.assertEqual(builder.tree_readers({}, trees)["shared"], ["demo", "twin"]) + self.assertEqual(datatrees.tree_readers({}, trees)["shared"], ["demo", "twin"]) def test_a_tree_a_system_declares_names_no_core(self) -> None: trees = self.trees() declared = {"demo-system": {"data_directories": [{"ref": "shared"}]}} - self.assertNotIn("shared", builder.tree_readers(declared, trees)) - self.assertIn("shared", builder.tree_readers({}, trees)) + self.assertNotIn("shared", datatrees.tree_readers(declared, trees)) + self.assertIn("shared", datatrees.tree_readers({}, trees)) def test_tree_below_the_declared_bios_folder(self) -> None: config = { @@ -114,13 +116,13 @@ class CoreDataTreesTest(unittest.TestCase): "base_destination": "", "systems": {"demo-system": {"files": [{"name": "a.bin", "destination": "bios/a.bin"}]}}, } - trees = builder.core_data_trees(config, PROFILES, "plat", REGISTRY) + trees = datatrees.core_data_trees(config, PROFILES, "plat", REGISTRY) self.assertEqual( [t["destination"] for t in trees if t["ref"] == "shared"], ["bios/Demo/Sys"] ) def test_no_registry_no_tree(self) -> None: - self.assertEqual(builder.core_data_trees(CONFIG, PROFILES, "plat", None), []) + self.assertEqual(datatrees.core_data_trees(CONFIG, PROFILES, "plat", None), []) class EveryReaderHasTheTreeOrAReason(unittest.TestCase): @@ -170,10 +172,10 @@ class AmberelecCarriesTheMachines(unittest.TestCase): 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) + trees = datatrees.core_data_trees(config, profiles, "amberelec", registry) refs: dict = {} members = dict( - (full, src) for src, full in builder._data_directory_members( + (full, src) for src, full in datatrees._data_directory_members( config.get("systems", {}), registry, "amberelec", config.get("base_destination", ""), False, set(), set(), set(), refs_out=refs, core_trees=trees, @@ -200,10 +202,10 @@ class TheCountLineKeepsTreesOutOfTheBaseline(unittest.TestCase): os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) db = load_database("database.json") - record = builder.PackRecord() + record = archive.PackRecord() out = io.StringIO() with contextlib.redirect_stdout(out): - builder.generate_pack( + platformpack.generate_pack( "myminui", "platforms", db, "bios", "tmp", offline=True, record=record, data_registry=load_data_dir_registry("platforms"), ) diff --git a/tests/test_core_file_fills_declaration.py b/tests/test_core_file_fills_declaration.py index 397c54efa..836c402d3 100644 --- a/tests/test_core_file_fills_declaration.py +++ b/tests/test_core_file_fills_declaration.py @@ -25,8 +25,8 @@ import yaml 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 +from packs.platformpack import generate_pack +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parents[1] @@ -151,6 +151,8 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): def test_the_pack_records_it_and_main_exits_non_zero(self): import generate_pack as gp + from packs import datatrees + from packs import platformpack root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) @@ -166,18 +168,18 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): })) db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {}, "by_path_suffix": {}}} - gp._MISSING_DATA_DIRS.clear() - self.addCleanup(gp._MISSING_DATA_DIRS.clear) + datatrees._MISSING_DATA_DIRS.clear() + self.addCleanup(datatrees._MISSING_DATA_DIRS.clear) with redirect_stdout(io.StringIO()): - gp.generate_pack( + platformpack.generate_pack( "fakeplat", str(root / "platforms"), db, str(root / "bios"), str(root / "out"), emulators_dir=str(root / "emulators"), data_registry={"assets": {"local_cache": str(root / "absent")}}, offline=True, ) - self.assertEqual(gp._MISSING_DATA_DIRS, {"assets"}) + self.assertEqual(datatrees._MISSING_DATA_DIRS, {"assets"}) # main() starts each run with no notices, so the run itself records it. - with mock.patch.object(gp, "_main", lambda held: gp._MISSING_DATA_DIRS.add("assets")), \ + with mock.patch.object(gp, "_main", lambda held: datatrees._MISSING_DATA_DIRS.add("assets")), \ contextlib.redirect_stderr(io.StringIO()), \ self.assertRaises(SystemExit) as stop: gp.main() @@ -191,7 +193,7 @@ class AFileNobodyHoldsIsAnOmission(unittest.TestCase): showed no notice and said everything was verified.""" def test_the_manifest_names_it(self): - from generate_pack import generate_manifest + from packs.manifest import generate_manifest _emulator_profiles_cache.clear() root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) @@ -232,7 +234,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase): no archive member names, shipped nothing.""" def test_verify_reads_undeclared_files_as_the_builder_does(self): - import cross_reference + from packs import crossref _emulator_profiles_cache.clear() root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) @@ -252,7 +254,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase): db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {}, "by_path_suffix": {}}} config = load_platform_config("fakeplat", str(root / "platforms")) - with mock.patch.object(cross_reference, "_build_supplemental_index", + with mock.patch.object(crossref, "_build_supplemental_index", lambda *a, **k: {"315-6146.bin"}): result = verify_platform(config, db, str(root / "emulators")) self.assertEqual( diff --git a/tests/test_core_size_refusal.py b/tests/test_core_size_refusal.py index 120508b1c..0413c2e84 100644 --- a/tests/test_core_size_refusal.py +++ b/tests/test_core_size_refusal.py @@ -24,9 +24,11 @@ import yaml 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 packs import manifest as packs_manifest +from packs import platformpack from resolve.validation import core_size_refusal -from verify import find_undeclared_files, verify_platform +from packs.gaps import find_undeclared_files +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent @@ -104,7 +106,7 @@ class _Collection(unittest.TestCase): return next(u for u in undeclared if u["profile"] == profile) def _pack_members(self) -> set[str]: - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "exist", "platforms", self.db, "bios", "out", emulators_dir="emulators", emu_profiles=self.profiles, offline=True, ) @@ -112,7 +114,7 @@ class _Collection(unittest.TestCase): return set(zf.namelist()) def _manifest(self) -> dict: - return builder.generate_manifest( + return packs_manifest.generate_manifest( "exist", "platforms", self.db, "bios", "platforms/_registry.yml", emulators_dir="emulators", emu_profiles=self.profiles, offline=True, ) diff --git a/tests/test_cross_reference_sources.py b/tests/test_cross_reference_sources.py index 3bfaee437..90e7c9de6 100644 --- a/tests/test_cross_reference_sources.py +++ b/tests/test_cross_reference_sources.py @@ -15,12 +15,8 @@ import tempfile import unittest from pathlib import Path -from cross_reference import ( - _build_supplemental_index, - cross_reference, - entry_source, - print_report, -) +from packs.crossref import _build_supplemental_index, cross_reference, entry_source +from cross_reference import print_report REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_declared_names.py b/tests/test_declared_names.py index 070223b30..2579b4104 100644 --- a/tests/test_declared_names.py +++ b/tests/test_declared_names.py @@ -13,11 +13,7 @@ import tests import unittest from pathlib import Path -from cross_reference import ( - cross_reference, - declared_names, - load_platform_files, -) +from packs.crossref import cross_reference, declared_names, load_platform_files REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_dedup.py b/tests/test_dedup.py index 04f4d84af..52f3d8447 100644 --- a/tests/test_dedup.py +++ b/tests/test_dedup.py @@ -19,6 +19,7 @@ import unittest from pathlib import Path import dedup +from model import nodedup class _Bios(unittest.TestCase): @@ -286,9 +287,9 @@ class PathPriority(unittest.TestCase): self.assertLess(primary, variant) def test_protected_directories_are_recognised(self): - self.assertTrue(dedup._in_nodedup_dir("bios/RPG Maker/x/font.png")) - self.assertTrue(dedup._in_nodedup_dir("bios/ScummVM/x/monkey.tbl")) - self.assertFalse(dedup._in_nodedup_dir("bios/Sony/PlayStation/scph.bin")) + self.assertTrue(nodedup._in_nodedup_dir("bios/RPG Maker/x/font.png")) + self.assertTrue(nodedup._in_nodedup_dir("bios/ScummVM/x/monkey.tbl")) + self.assertFalse(nodedup._in_nodedup_dir("bios/Sony/PlayStation/scph.bin")) class TheNoDedupListIsPinned(unittest.TestCase): @@ -298,7 +299,7 @@ class TheNoDedupListIsPinned(unittest.TestCase): three machines again, with the suite green.""" def test_every_tree_read_by_path_stays_undeduplicated(self): - from scripts.dedup import NODEDUP_DIRS + from scripts.model.nodedup import NODEDUP_DIRS expected = { "RPG Maker", "ScummVM", "tzdata", "c64-emu", "PinMAME", "BBK", diff --git a/tests/test_deterministic_zip.py b/tests/test_deterministic_zip.py index b6d3cf5bd..417f60f08 100644 --- a/tests/test_deterministic_zip.py +++ b/tests/test_deterministic_zip.py @@ -227,7 +227,7 @@ class TestPackDeterminism(unittest.TestCase): self._tmp.cleanup() def _build(self, out_name: str) -> Path: - from scripts.generate_pack import generate_pack + from scripts.packs.platformpack import generate_pack out = self.tmp / out_name out.mkdir() @@ -294,7 +294,7 @@ class TestPackDeterminism(unittest.TestCase): self.assertEqual(info.date_time, _FIXED_DATE_TIME) def _build_emulator(self, out_name: str) -> Path: - from scripts.generate_pack import generate_emulator_pack + from scripts.packs.emulatorpack import generate_emulator_pack out = self.tmp / out_name out.mkdir() @@ -383,7 +383,8 @@ class TestPackDeterminism(unittest.TestCase): ) def test_injected_manifest_is_pinned_to_the_database(self): - from scripts.generate_pack import inject_manifest, verify_pack + from scripts.packs.finalize import inject_manifest + from scripts.generate_pack import verify_pack pack = self._build("out1") ok, manifest = verify_pack(str(pack), self.db) @@ -406,7 +407,8 @@ class ManifestInjectionIsAtomic(unittest.TestCase): import tempfile from unittest import mock - from scripts import generate_pack as gp + from scripts.packs import archive as packs_archive + from scripts.packs import finalize with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[1] / "tmp") as d: pack = Path(d) / "Pack.zip" @@ -420,9 +422,9 @@ class ManifestInjectionIsAtomic(unittest.TestCase): zf.fp.flush() raise KeyboardInterrupt - with mock.patch.object(gp, "_write_generated_member", die), \ + with mock.patch.object(packs_archive, "_write_generated_member", die), \ self.assertRaises(KeyboardInterrupt): - gp.inject_manifest(str(pack), {"files": ["x"] * 2000}) + finalize.inject_manifest(str(pack), {"files": ["x"] * 2000}) self.assertEqual(pack.read_bytes(), before) self.assertEqual( [p.name for p in Path(d).iterdir()], ["Pack.zip"], @@ -436,7 +438,7 @@ class PackMemberCompression(unittest.TestCase): the packs' size.""" def _pack(self, tmp: Path, name: str) -> Path: - from scripts.generate_pack import _add_pack_member + from scripts.packs.archive import _add_pack_member source = tmp / "member" source.write_bytes(b"\x00" * 4096) diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index 9e081cae0..c01a5b3ac 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -28,8 +28,12 @@ except ImportError: 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 +from packs import emulatorpack +from packs import manifest as packs_manifest +from packs import platformpack +from packs import emulatorcheck +from packs import gaps as packs_gaps +from packs import verdicts HAS_JSONSCHEMA = jsonschema is not None REPO_ROOT = Path(__file__).resolve().parent.parent @@ -158,7 +162,7 @@ class DirectoryMembers(DirectoryFixture): class CrossReferenceReadsADirectory(DirectoryFixture): def _report(self, body: str = PROFILE) -> list[dict]: profiles = self._profiles(body) - return verify.find_undeclared_files( + return packs_gaps.find_undeclared_files( PLATFORM, str(self.emulators), self._db(), profiles ) @@ -199,7 +203,7 @@ class GapReportReadsADirectory(DirectoryFixture): listed as a file to source.""" def test_a_held_hidden_directory_is_held(self): - from cross_reference import entry_source + from packs.crossref import entry_source self._add("Engine/cdogs/data/.wolf3d/N3D.cdogscpn/campaign.json", b"campaign") db = self._db() @@ -223,7 +227,7 @@ class PackCarriesADirectory(DirectoryFixture): profiles = self._profiles() out = self.root / "dist" out.mkdir() - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "demo", str(self.platforms), self._db(), str(self.bios), str(out), emulators_dir=str(self.emulators), emu_profiles=profiles, offline=True, @@ -238,7 +242,7 @@ class PackCarriesADirectory(DirectoryFixture): def test_the_install_manifest_lists_the_tree(self): profiles = self._profiles() - manifest = builder.generate_manifest( + manifest = packs_manifest.generate_manifest( "demo", str(self.platforms), self._db(), str(self.bios), str(self.platforms / "_registry.yml"), emulators_dir=str(self.emulators), emu_profiles=profiles, @@ -251,9 +255,9 @@ class PackCarriesADirectory(DirectoryFixture): def test_the_gap_report_is_computed_once_per_build(self): """The region grouping and phase 2 each ran find_undeclared_files with the same arguments: 30 reports for 15 manifests.""" - import verify + from packs import gaps as packs_gaps - real = verify.find_undeclared_files + real = packs_gaps.find_undeclared_files calls: list[int] = [] def counted(*a, **kw): @@ -263,15 +267,15 @@ class PackCarriesADirectory(DirectoryFixture): profiles = self._profiles() out = self.root / "counted" out.mkdir() - with mock.patch.object(verify, "find_undeclared_files", counted): - builder.generate_manifest( + with mock.patch.object(packs_gaps, "find_undeclared_files", counted): + packs_manifest.generate_manifest( "demo", str(self.platforms), self._db(), str(self.bios), str(self.platforms / "_registry.yml"), emulators_dir=str(self.emulators), emu_profiles=profiles, offline=True, ) self.assertEqual(len(calls), 1) - builder.generate_pack( + platformpack.generate_pack( "demo", str(self.platforms), self._db(), str(self.bios), str(out), emulators_dir=str(self.emulators), emu_profiles=profiles, offline=True, regions=["north-america"], @@ -282,7 +286,7 @@ class PackCarriesADirectory(DirectoryFixture): self._profiles() out = self.root / "emu" out.mkdir() - zip_path = builder.generate_emulator_pack( + zip_path = emulatorpack.generate_emulator_pack( ["demo"], str(self.emulators), self._db(), str(self.bios), str(out), offline=True, ) @@ -292,17 +296,17 @@ class PackCarriesADirectory(DirectoryFixture): def test_verify_counts_what_the_emulator_pack_ships(self): self._profiles() - result = verify.verify_emulator(["demo"], str(self.emulators), self._db()) + result = emulatorcheck.verify_emulator(["demo"], str(self.emulators), self._db()) held = { detail["name"] for detail in result["details"] - if detail["status"] == verify.Status.OK + if detail["status"] == verdicts.Status.OK } self.assertEqual(held, self.EXPECTED) missing = [ detail["name"] for detail in result["details"] - if detail["status"] == verify.Status.MISSING + if detail["status"] == verdicts.Status.MISSING ] self.assertEqual(missing, ["Fonts"]) diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index eee225085..78e540247 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -59,7 +59,7 @@ class TestSkeletonReadsTheResultShape(unittest.TestCase): copied from it stopped on KeyError: 0 before any assertion.""" def test_every_key_it_reads_is_one_verify_platform_returns(self): - from verify import verify_platform + from packs.coverage import verify_platform result = verify_platform( {"platform": "x", "verification_mode": "existence", "systems": {}}, @@ -425,7 +425,7 @@ class RecalboxSeverity(unittest.TestCase): code never reads, and called a missing optional file GREEN.""" def test_the_verify_column_is_what_compute_severity_returns(self): - from verify import Status, compute_severity + from packs.verdicts import Status, compute_severity section = _section(_page("verification-modes.md"), "Mandatory levels (Recalbox)") rows = _table_rows(section) @@ -475,9 +475,9 @@ class ValidationIndexScope(unittest.TestCase): pass it only the profiles the platform resolves.""" def test_page_names_the_scope_the_code_uses(self): - import verify + from packs import coverage - source = inspect.getsource(verify.verify_platform) + source = inspect.getsource(coverage.verify_platform) self.assertRegex(source, r"plat_cores = resolve_platform_cores\(config, profiles\)") self.assertIn("_build_validation_index(platform_profiles)", source) section = _section(_page("verification-modes.md"), "Validation index") @@ -1751,7 +1751,7 @@ class ArchitectureStatesTheArbitration(unittest.TestCase): checks the content: RetroBat's ATARIOSB.ROM.""" def test_the_page_says_what_arbitrate_decides(self): - import slots + from packs import slots page = (WIKI / "architecture.md").read_text(encoding="utf-8") self.assertNotIn("the profile takes precedence for pack generation", page) @@ -1840,7 +1840,7 @@ class ClaimRuleNamesTheSizeProof(unittest.TestCase): platform file of another size since 2b535525e.""" def test_the_page_states_what_slots_counts(self): - import slots + from packs import slots self.assertIn(slots.SIZE_EXACT, slots.PROVEN_STATUSES) page = " ".join((ROOT / "wiki" / "architecture.md").read_text(encoding="utf-8").split()) diff --git a/tests/test_download.py b/tests/test_download.py index c084ffcb4..a830664d6 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -30,7 +30,7 @@ import unittest import zipfile from pathlib import Path -import split_pack +from packs import parts as packs_parts REPO_ROOT = Path(__file__).resolve().parent.parent _spec = importlib.util.spec_from_file_location( @@ -322,7 +322,7 @@ class ReleaseServer: self.names: list[str] = [] if zip_parts: # One byte under the whole archive: the last member no longer fits. - parts = split_pack.split_pack(archive, limit=len(raw) - 1) + parts = packs_parts.split_pack(archive, limit=len(raw) - 1) self.names = [part.name for part in parts] sums = "".join( f"{hashlib.sha256(part.read_bytes()).hexdigest()} {part.name}\n" @@ -455,7 +455,7 @@ class DownloaderCase(unittest.TestCase): leftovers = sorted( p.name for p in searched if ("_BIOS_Pack" in p.name or p.name.startswith(".")) - and not split_pack.is_marker(p.name) + and not packs_parts.is_marker(p.name) ) self.assertEqual(leftovers, [], "download staging left behind") diff --git a/tests/test_e2e.py b/tests/test_e2e.py index ca06a6b8b..bf88691ff 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -43,14 +43,10 @@ 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 ( - Severity, - Status, - find_exclusion_notes, - find_undeclared_files, - verify_emulator, - verify_platform, -) +from packs.verdicts import Severity, Status +from packs.gaps import find_exclusion_notes, find_undeclared_files +from packs.emulatorcheck import verify_emulator +from packs.coverage import verify_platform try: import jsonschema @@ -1047,7 +1043,7 @@ class TestE2E(unittest.TestCase): def test_45_hle_fallback_downgrades_severity(self): """Missing file with hle_fallback=true ->INFO severity, not CRITICAL.""" - from verify import Severity, compute_severity + from packs.verdicts import Severity, compute_severity # required + missing + NO HLE = CRITICAL sev = compute_severity("missing", True, "md5", hle_fallback=False) @@ -2172,7 +2168,7 @@ class TestE2E(unittest.TestCase): def test_120_format_ground_truth_aggregate(self): """Aggregate format: one line with all cores.""" - from verify import _format_ground_truth_aggregate + from packs.report import _format_ground_truth_aggregate gt = [ { @@ -2196,7 +2192,7 @@ class TestE2E(unittest.TestCase): def test_121_format_ground_truth_verbose(self): """Verbose format: one line per core with expected values and source ref.""" - from verify import _format_ground_truth_verbose + from packs.report import _format_ground_truth_verbose gt = [ { @@ -2215,7 +2211,7 @@ class TestE2E(unittest.TestCase): def test_122_format_ground_truth_verbose_no_source_ref(self): """Verbose format omits bracket when source_ref is None.""" - from verify import _format_ground_truth_verbose + from packs.report import _format_ground_truth_verbose gt = [ { @@ -5011,7 +5007,7 @@ struct BurnDriver BurnDrvneogeo = { def test_200_find_undeclared_include_all(self): """include_all=True returns ALL core files, including declared ones.""" - from verify import find_undeclared_files + from packs.gaps import find_undeclared_files config = self._load_config("test_existence") profiles = load_emulator_profiles(self.emulators_dir) @@ -5768,7 +5764,7 @@ struct BurnDriver BurnDrvneogeo = { def test_226_cross_reference_platform_filter(self): """--platform restricts declarations to that platform alone.""" - from cross_reference import load_platform_files + from packs.crossref import load_platform_files with tempfile.TemporaryDirectory() as tmpdir: plat_dir = os.path.join(tmpdir, "platforms") @@ -6072,7 +6068,7 @@ struct BurnDriver BurnDrvneogeo = { def test_verify_platform_region_matches_the_pack(self): from model.platforms import load_platform_config - from verify import verify_platform + from packs.coverage import verify_platform self._create_region_fixtures() profiles = self._region_profiles() @@ -6097,7 +6093,7 @@ struct BurnDriver BurnDrvneogeo = { def test_verify_emulator_region_matches_the_pack(self): from generate_pack import generate_emulator_pack - from verify import verify_emulator + from packs.emulatorcheck import verify_emulator self._create_region_fixtures() with open( @@ -6320,7 +6316,7 @@ struct BurnDriver BurnDrvneogeo = { """ import inspect - import packverify + from packs import integrity as packverify from generate_pack import _narrows_contents, _narrowings source = inspect.getsource(packverify.verify_pack_against_platform) @@ -6500,7 +6496,7 @@ struct BurnDriver BurnDrvneogeo = { --region compared nothing.""" import hashlib - from packextras import platform_region_groups + from packs.extras import platform_region_groups files, by_name = {}, {} for name in ("core_us.bin", "core_jp.bin"): @@ -6538,7 +6534,7 @@ struct BurnDriver BurnDrvneogeo = { --region us pack kept the declared Japanese BIOS.""" import hashlib - from packextras import platform_region_groups + from packs.extras import platform_region_groups files, by_name = {}, {} for name in ("bios_U.sms", "bios_J.sms"): @@ -6722,7 +6718,7 @@ struct BurnDriver BurnDrvneogeo = { } def _gap_source(self, entry: dict, db: dict) -> str: - from cross_reference import cross_reference + from packs.crossref import cross_reference report = cross_reference( {"gapemu": {"emulator": "GapEmu", "systems": ["s"], "files": [entry]}}, @@ -6934,7 +6930,7 @@ class OneOfASearchList(unittest.TestCase): ) def test_gap_report_counts_the_set_once(self): - import cross_reference + from packs import crossref index = { "by_name": self.db["indexes"]["by_name"], @@ -6943,7 +6939,7 @@ class OneOfASearchList(unittest.TestCase): "data_names": set(), "all_declared": set(), "db_files": self.db["files"], } report: dict = {} - cross_reference._cross_reference_profile("seq", self.profile, {}, report, index) + crossref._cross_reference_profile("seq", self.profile, {}, report, index) gaps = {g["name"]: g for g in report["seq"]["gap_details"]} self.assertEqual(sorted(gaps), ["none_a.bin", "plain.bin", "second.bin", "third.bin"]) self.assertEqual(gaps["none_a.bin"]["alternatives"], ["none_b.bin"]) diff --git a/tests/test_emulator_pack_counts.py b/tests/test_emulator_pack_counts.py index 590bbc960..949d676d2 100644 --- a/tests/test_emulator_pack_counts.py +++ b/tests/test_emulator_pack_counts.py @@ -81,8 +81,8 @@ class APlaceholderIsAnsweredByEvidence(unittest.TestCase): import yaml from model.profiles import _emulator_profiles_cache - from generate_pack import generate_emulator_pack - from verify import verify_emulator + from packs.emulatorpack import generate_emulator_pack + from packs.emulatorcheck import verify_emulator _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) diff --git a/tests/test_entry_categories.py b/tests/test_entry_categories.py index b3df55d1b..d53816938 100644 --- a/tests/test_entry_categories.py +++ b/tests/test_entry_categories.py @@ -10,7 +10,9 @@ import tests import unittest -import verify +from packs import coverage +from packs import report +from packs import verdicts from resolve.categories import BIOS, GAME_DATA, UNREAD, EntryCategories, ProofIndex, ReadEvidence PROFILES = { @@ -108,7 +110,7 @@ class Evidence(unittest.TestCase): "emulator": "devilutionx", "proof": "name", "runs_system": True, "entries": [{"name": "diabdat.mpq", "source_ref": "Source/init.cpp:120", "by": "name"}]}]) - self.assertEqual(verify.category_evidence_text(found), + self.assertEqual(report.category_evidence_text(found), "read by devilutionx (diabdat.mpq at Source/init.cpp:120)") def test_unread_names_the_cores_examined(self): @@ -123,7 +125,7 @@ class Evidence(unittest.TestCase): cats = EntryCategories(_config(["bluemsx", "devilutionx", "other"], []), profiles) found = cats.explain({"name": "diabdat.mpq"}, "ports/diablo/diabdat.mpq", "diablo") self.assertEqual([r["emulator"] for r in found["read_by"]], ["devilutionx", "other"]) - self.assertEqual(verify.category_evidence_text(found), + self.assertEqual(report.category_evidence_text(found), "read by devilutionx (diabdat.mpq at Source/init.cpp:120), " "also named by other (diabdat.mpq)") @@ -134,7 +136,7 @@ class Evidence(unittest.TestCase): {"name": "hardwareconfig.xml"}, "bios/Machines/MSX/hardwareconfig.xml", "microsoft-msx") self.assertEqual(found, {"category": UNREAD, "cores_examined": ["bluemsx"]}) - self.assertEqual(verify.category_evidence_text(found), + self.assertEqual(report.category_evidence_text(found), "no reader found (cores examined: bluemsx)") def test_an_unsettled_entry_says_why(self): @@ -143,7 +145,7 @@ class Evidence(unittest.TestCase): "bios/Machines/MSX/hardwareconfig.xml", "microsoft-msx") self.assertEqual(found["category"], BIOS) self.assertIn("mystery", found["unsettled"]) - self.assertIn("not settled", verify.category_evidence_text(found)) + self.assertIn("not settled", report.category_evidence_text(found)) class StrictCountsFirmwareOnly(unittest.TestCase): @@ -156,13 +158,13 @@ class StrictCountsFirmwareOnly(unittest.TestCase): ], system="microsoft-msx") db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {}, "by_path_suffix": {}}} - result = verify.verify_platform(config, db, emu_profiles=PROFILES) - self.assertEqual(result["severity_counts"][verify.Severity.CRITICAL], 1) + result = coverage.verify_platform(config, db, emu_profiles=PROFILES) + self.assertEqual(result["severity_counts"][verdicts.Severity.CRITICAL], 1) self.assertEqual(result["missing_not_firmware"], { "game_data": ["ports/diablo/diabdat.mpq"], "unread": ["bios/Machines/MSX/hardwareconfig.xml"], }) - self.assertEqual(result["status_counts"][verify.Status.MISSING], 3) + self.assertEqual(result["status_counts"][verdicts.Status.MISSING], 3) evidence = {d["name"]: d.get("category_evidence") for d in result["details"]} self.assertEqual(evidence["hardwareconfig.xml"]["cores_examined"], ["bluemsx"]) self.assertEqual(evidence["diabdat.mpq"]["read_by"][0]["emulator"], "devilutionx") diff --git a/tests/test_extra_identity.py b/tests/test_extra_identity.py index 8087b3ac6..d15071b98 100644 --- a/tests/test_extra_identity.py +++ b/tests/test_extra_identity.py @@ -14,8 +14,8 @@ import unittest from pathlib import Path from model.profiles import PROFILE_IDENTITY_FIELDS -from packextras import _collect_emulator_extras -from verify import find_undeclared_files +from packs.extras import _collect_emulator_extras +from packs.gaps import find_undeclared_files REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_file_consumers.py b/tests/test_file_consumers.py index 42b49bfd7..266f1d52f 100644 --- a/tests/test_file_consumers.py +++ b/tests/test_file_consumers.py @@ -15,7 +15,7 @@ import tempfile import unittest from pathlib import Path -from cross_reference import FileConsumers, entry_target +from packs.crossref import FileConsumers, entry_target from generate_site import generate_system_page REPO_ROOT = Path(__file__).resolve().parent.parent @@ -90,7 +90,7 @@ class PlatformReadersResolveAsThePack(unittest.TestCase): the one its manifest installs.""" def test_the_declared_file_is_the_one_the_pack_ships(self): - from packresolve import resolve_declaration + from resolve.packfiles import resolve_declaration first, first_entry = _collected("bios/Arcade/MAME/hash/apfm1000.xml", b"one") other, other_entry = _collected("bios/Other/mame/hash/apfm1000.xml", b"two") diff --git a/tests/test_finalize_pack_names.py b/tests/test_finalize_pack_names.py index 901a2b597..b37bcff40 100644 --- a/tests/test_finalize_pack_names.py +++ b/tests/test_finalize_pack_names.py @@ -16,7 +16,7 @@ import unittest import zipfile from pathlib import Path -from generate_pack import verify_and_finalize_packs +from packs.finalize import verify_and_finalize_packs REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_foreign_tree_names.py b/tests/test_foreign_tree_names.py index 48b50ff6d..396b991ce 100644 --- a/tests/test_foreign_tree_names.py +++ b/tests/test_foreign_tree_names.py @@ -199,7 +199,7 @@ class TheGapReportAsksAsTheEmulator(unittest.TestCase): self.entry = {"name": "et4000.bin", "required": True} def _source(self, owner: str) -> str | None: - from cross_reference import entry_source + from packs.crossref import entry_source by_name = self.db["indexes"]["by_name"] index = { @@ -218,7 +218,7 @@ class TheGapReportAsksAsTheEmulator(unittest.TestCase): self.assertEqual(self._source("pcem"), "bios") def test_core_files_follow_the_resolver(self): - from verify import find_undeclared_files + from packs.gaps import find_undeclared_files profiles = {"dosbox-x": { "emulator": "DOSBox-X", "type": "libretro", "systems": ["dos"], diff --git a/tests/test_frontend_digest.py b/tests/test_frontend_digest.py index 024de7007..e0ecf4cb8 100644 --- a/tests/test_frontend_digest.py +++ b/tests/test_frontend_digest.py @@ -20,8 +20,9 @@ from pathlib import Path import yaml from model.platforms import load_platform_config -from generate_pack import generate_manifest, generate_pack -from verify import verify_platform +from packs.manifest import generate_manifest +from packs.platformpack import generate_pack +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_game_data_homonyms.py b/tests/test_game_data_homonyms.py index c5bb64d57..d0557e7a3 100644 --- a/tests/test_game_data_homonyms.py +++ b/tests/test_game_data_homonyms.py @@ -224,7 +224,7 @@ class SecondPassKeepsIdentity(unittest.TestCase): """ def test_flag_and_hashes_reach_the_alternative_destination(self): - from packextras import _collect_emulator_extras + from packs.extras import _collect_emulator_extras sha = "a" * 40 md5 = "b" * 32 @@ -266,7 +266,7 @@ class ReleaseAssetIsNotANameMatch(unittest.TestCase): def test_an_unsourceable_entry_without_hash_never_reaches_the_asset_store(self): from unittest import mock - import packresolve + from resolve import packfiles as packresolve entry = {"name": "pak0.pk3", "unsourceable": "retail"} db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_path_suffix": {}}} @@ -287,7 +287,7 @@ class ReleaseAssetAnswersEveryDeclaredHash(unittest.TestCase): import tempfile from unittest import mock - import packresolve + from resolve import packfiles as packresolve db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_path_suffix": {}}} with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/test_gap_settlement.py b/tests/test_gap_settlement.py index 0df3f4e5e..b263fef0b 100644 --- a/tests/test_gap_settlement.py +++ b/tests/test_gap_settlement.py @@ -12,7 +12,7 @@ import tests import unittest from pathlib import Path -from cross_reference import cross_reference +from packs.crossref import cross_reference from resolve.validation import case_folded_slots, declaration_settles REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_hidden_extras.py b/tests/test_hidden_extras.py index aa9c8c7c0..6a1bad0af 100644 --- a/tests/test_hidden_extras.py +++ b/tests/test_hidden_extras.py @@ -15,7 +15,7 @@ import os import unittest from pathlib import Path -from packpaths import placement_block +from packs.paths import placement_block REPO_ROOT = Path(__file__).resolve().parents[1] @@ -88,7 +88,7 @@ class TheReportSaysSo(unittest.TestCase): try: from model.database import load_database from model.profiles import load_emulator_profiles - from verify import verify_platform + from packs.coverage import verify_platform from model.platforms import load_platform_config db = load_database("database.json") @@ -152,7 +152,8 @@ class TheGapReportIsComputedOnce(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) try: - import verify + from packs import coverage + from packs import gaps from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -161,9 +162,9 @@ class TheGapReportIsComputedOnce(unittest.TestCase): profiles = load_emulator_profiles("emulators") config = load_platform_config("emudeck", "platforms") with mock.patch.object( - verify, "find_undeclared_files", wraps=verify.find_undeclared_files + gaps, "find_undeclared_files", wraps=gaps.find_undeclared_files ) as counted: - verify.verify_platform(config, db, "emulators", profiles) + coverage.verify_platform(config, db, "emulators", profiles) finally: os.chdir(previous) self.assertEqual(counted.call_count, 1) @@ -177,7 +178,7 @@ class TheReplayResolvesAsTheBuilder(unittest.TestCase): def test_an_unresolved_extra_blocks_nothing(self): from unittest import mock - import packextras + from packs import extras as packextras extras = [ {"destination": "box.bin/inner.rom", "name": "inner.rom", diff --git a/tests/test_install.py b/tests/test_install.py index f6279cd2a..4721fc9a6 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -4471,9 +4471,10 @@ class DataDirectoriesAreInstalled(unittest.TestCase): manifest = json.loads((REPO_ROOT / "install" / "retroarch.json").read_text()) dirs = manifest.get("data_directories") or [] files = sum(len(d["files"]) for d in dirs) - import generate_pack + from packs import archive as packs_archive + from packs import datatrees - written = generate_pack.PACK_DOCUMENTS + generate_pack.pack_markers( + written = packs_archive.PACK_DOCUMENTS + datatrees.pack_markers( "retroarch", None, str(REPO_ROOT / "platforms")) self.assertEqual(written, ("README.txt", "manifest.json", ".nomedia")) self.assertEqual( @@ -7728,13 +7729,13 @@ class TheListVersionIsComparedWithTheSystems(unittest.TestCase): """A handheld without network installs from the pack: its manifest.json records the list's version, which generate_pack takes from the install list built with the same choices.""" - import generate_pack + from packs import scope data = b"bios" install_list = {"version": "43.1", "files": [ {"dest": "a.bin", "sha1": hashlib.sha1(data).hexdigest(), "size": 4}]} pack_list = {"files": [{"path": "a.bin", "sha1": hashlib.sha1(data).hexdigest(), "size": 4}]} - generate_pack.annotate_pack_systems(pack_list, generate_pack.pack_systems(install_list)) + scope.annotate_pack_systems(pack_list, scope.pack_systems(install_list)) self.assertEqual(pack_list["list_version"], "43.1") pack = Path(_tempdir(self)) / "Batocera_43.1_BIOS_Pack.zip" with zipfile.ZipFile(pack, "w") as archive: diff --git a/tests/test_install_cores.py b/tests/test_install_cores.py index ed817300f..bd98bf51b 100644 --- a/tests/test_install_cores.py +++ b/tests/test_install_cores.py @@ -265,14 +265,14 @@ class TheBuildersOrder(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): self.skipTest("database.json is not built") - import generate_pack as gp + from packs import manifest as packs_manifest 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")) def manifest(cores): - return gp.generate_manifest( + return packs_manifest.generate_manifest( "retropie", str(REPO_ROOT / "platforms"), db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"), emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=profiles, @@ -366,14 +366,14 @@ class APlatformOmissionKeepsItsClaim(unittest.TestCase): self.assertEqual(omitted, []) def test_the_generator_files_the_core_behind_the_platform(self): - import generate_pack as gp + from packs import manifestentry held = {"cores": None} - self.assertTrue(gp._claim_platform_omission(held, "melonds")) - self.assertTrue(gp._claim_platform_omission(held, "melonds")) + self.assertTrue(manifestentry._claim_platform_omission(held, "melonds")) + self.assertTrue(manifestentry._claim_platform_omission(held, "melonds")) self.assertEqual(held["alternatives"], [{"cores": ["melonds"]}]) - self.assertFalse(gp._claim_platform_omission({"cores": ["x"]}, "melonds")) - self.assertFalse(gp._claim_platform_omission(None, "melonds")) + self.assertFalse(manifestentry._claim_platform_omission({"cores": ["x"]}, "melonds")) + self.assertFalse(manifestentry._claim_platform_omission(None, "melonds")) def test_the_boundary_takes_only_core_names(self): manifest = {"manifest_version": 2, "platform": "retroarch", "files": [], diff --git a/tests/test_install_experience.py b/tests/test_install_experience.py index ebe4d69c6..d58d24faf 100644 --- a/tests/test_install_experience.py +++ b/tests/test_install_experience.py @@ -197,7 +197,7 @@ class ProgramsAreMarked(unittest.TestCase): the git mode cannot, hundreds of MAME archives carrying an execute bit.""" def test_header_decides(self): - import generate_pack + from packs import manifestentry with tempfile.TemporaryDirectory() as tmp: for data, expected in ((b"\x7fELF\x02", True), (b"#!/bin/sh\n", True), @@ -205,7 +205,7 @@ class ProgramsAreMarked(unittest.TestCase): path = Path(tmp) / "f" path.write_bytes(data) with self.subTest(head=data): - self.assertEqual(generate_pack._is_program(str(path)), expected) + self.assertEqual(manifestentry._is_program(str(path)), expected) def test_retrodeck_launchers_are_executable(self): manifest = json.loads((REPO_ROOT / "install" / "retrodeck.json").read_text()) @@ -224,24 +224,24 @@ class ManifestHashesMatchTheScan(unittest.TestCase): file holds, the same wrong value in two runs.""" def test_a_contradicted_hash_is_refused(self): - import generate_pack + from packs import manifestentry with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "nand.bin" path.write_bytes(b"real") real = hashlib.sha1(b"real").hexdigest() good = {"files": {real: {"path": str(path)}}} - self.assertEqual(generate_pack._stable_hashes(str(path), good)["sha1"], real) + self.assertEqual(manifestentry._stable_hashes(str(path), good)["sha1"], real) bad = {"files": {"0" * 40: {"path": str(path)}}} with self.assertRaises(RuntimeError): - generate_pack._stable_hashes(str(path), bad) - self.assertEqual(generate_pack._stable_hashes(str(path), {"files": {}})["sha1"], real) + manifestentry._stable_hashes(str(path), bad) + self.assertEqual(manifestentry._stable_hashes(str(path), {"files": {}})["sha1"], real) def test_a_wrong_first_reading_is_read_again_from_disk(self): """The retries went through the hash cache and got the first, wrong value back: one read of the file, then a refusal a second read would have avoided.""" - import generate_pack + from packs import manifestentry from core import hashing real_compute = hashing._compute_hashes @@ -260,7 +260,7 @@ class ManifestHashesMatchTheScan(unittest.TestCase): real = hashlib.sha1(b"flaky").hexdigest() db = {"files": {real: {"path": str(path)}}} with mock.patch.object(hashing, "_compute_hashes", flaky): - self.assertEqual(generate_pack._stable_hashes(str(path), db)["sha1"], real) + self.assertEqual(manifestentry._stable_hashes(str(path), db)["sha1"], real) self.assertEqual(len(reads), 2) def test_the_cache_is_keyed_by_what_was_checked(self): diff --git a/tests/test_install_expert.py b/tests/test_install_expert.py index d7dceb756..fc3a54ca6 100644 --- a/tests/test_install_expert.py +++ b/tests/test_install_expert.py @@ -22,6 +22,10 @@ import subprocess import sys import tempfile import unittest +from packs import archive +from packs import emulatorpack +from packs import manifest as packs_manifest +from packs import platformpack from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent @@ -48,13 +52,10 @@ class RealListParity(unittest.TestCase): if sys.version_info < BUILDER_FLOOR: # 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 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( lambda plat: load_platform_config(plat, str(REPO_ROOT / "platforms"))) cls.db = json.loads(db_path.read_text(encoding="utf-8")) @@ -72,7 +73,7 @@ class RealListParity(unittest.TestCase): if plat not in self.manifests: self.layouts[plat] = {} with contextlib.redirect_stdout(io.StringIO()): - self.manifests[plat] = self.gp.generate_install_list( + self.manifests[plat] = packs_manifest.generate_install_list( plat, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"), emulators_dir=str(REPO_ROOT / "emulators"), @@ -86,10 +87,10 @@ class RealListParity(unittest.TestCase): trees apart (data_directories), and a cache copy at a destination the list serves from the collection is no choice of either option.""" base = self.config(plat).get("base_destination", "") - record = self.gp.PackRecord() + record = archive.PackRecord() with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): - self.gp.generate_pack( + platformpack.generate_pack( plat, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "tmp"), emulators_dir=str(REPO_ROOT / "emulators"), zip_contents=self.zip_contents, emu_profiles=self.profiles, @@ -185,10 +186,10 @@ class RealListParity(unittest.TestCase): self.assertEqual(sorted(layouts), full.get("standalone_builds", [])) for profile in sorted(layouts): with self.subTest(platform=plat, emulator=profile): - record = self.gp.PackRecord() + record = archive.PackRecord() with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): - self.gp.generate_emulator_pack( + emulatorpack.generate_emulator_pack( [profile], str(REPO_ROOT / "emulators"), self.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "tmp"), standalone=True, zip_contents=self.zip_contents, @@ -268,7 +269,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase): def test_random_slots_against_the_builder(self): import random - import manifestselect + from packs import manifestselect from resolve import slot as slot_mod rng = random.Random(7) @@ -303,7 +304,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase): does (slot.lookup_slot per member), whatever cores the board runs.""" import random - import manifestselect + from packs import manifestselect from resolve import slot as slot_mod rng = random.Random(11) diff --git a/tests/test_install_offline.py b/tests/test_install_offline.py index ef73adbcb..4ad692eea 100644 --- a/tests/test_install_offline.py +++ b/tests/test_install_offline.py @@ -28,7 +28,7 @@ import zipfile from pathlib import Path import install -import split_pack +from packs import parts as packs_parts from tests.test_install_selection import FakeRepository REPO_ROOT = Path(__file__).resolve().parent.parent @@ -342,7 +342,7 @@ class SplitParts(Scratch): downloads = self.root / "downloads" downloads.mkdir() pack = _pack(downloads, "RetroArch_v1_BIOS_Pack.zip", BIG) - parts = split_pack.split_pack(pack, limit=pack.stat().st_size // 3) + parts = packs_parts.split_pack(pack, limit=pack.stat().st_size // 3) self.assertGreater(len(parts), 2) return parts @@ -432,16 +432,17 @@ class ABoardWithoutTheNetwork(Scratch): if p.is_file()} def test_the_builder_writes_both_into_the_pack_list(self): - import generate_pack + from packs import scope + from packs import targets install_list = manifest() board_file = REPO_ROOT / "platforms" / "targets" / "batocera.yml" - boards = generate_pack.target_list(board_file) + boards = targets.target_list(board_file) self.assertEqual(boards, json.loads( (REPO_ROOT / "install" / "targets" / "batocera.json").read_text())) pack_list = {"files": []} - generate_pack.annotate_pack_systems( - pack_list, generate_pack.pack_systems(install_list, boards)) + scope.annotate_pack_systems( + pack_list, scope.pack_systems(install_list, boards)) self.assertEqual(pack_list["install_list"], install_list) self.assertEqual(pack_list["targets"], boards) diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 4c8a19fb4..10b54d237 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -27,6 +27,10 @@ import sys import tempfile import threading import unittest +from packs import archive +from packs import manifest as packs_manifest +from packs import platformpack +from packs import coverage from unittest import mock from pathlib import Path @@ -813,17 +817,14 @@ class InstallMatchesThePack(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - import generate_pack as gp from model.profiles import load_emulator_profiles - - cls.gp = gp cls.db = json.loads(db_path.read_text(encoding="utf-8")) cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) cls.full = cls._manifest(None) @classmethod def _manifest(cls, regions): - return cls.gp.generate_manifest( + return packs_manifest.generate_manifest( cls.PLATFORM, str(REPO_ROOT / "platforms"), cls.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"), emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=cls.profiles, @@ -866,17 +867,15 @@ class InstallMatchesASystemPack(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - import generate_pack as gp + from packs import manifest as packs_manifest 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")) cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) cls.base = load_platform_config( cls.PLATFORM, str(REPO_ROOT / "platforms") ).get("base_destination", "") - cls.full = gp.generate_manifest( + cls.full = packs_manifest.generate_manifest( cls.PLATFORM, str(REPO_ROOT / "platforms"), cls.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"), emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=cls.profiles, @@ -887,7 +886,7 @@ class InstallMatchesASystemPack(unittest.TestCase): import zipfile with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out: - zip_path = self.gp.generate_pack( + zip_path = platformpack.generate_pack( self.PLATFORM, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"), out, emulators_dir=str(REPO_ROOT / "emulators"), @@ -927,7 +926,7 @@ class DataTreesFollowTheSystemsTheyServe(InstallMatchesASystemPack): # The trees come from the registry the manifest reads by itself. with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out: - zip_path = self.gp.generate_pack( + zip_path = platformpack.generate_pack( self.PLATFORM, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"), out, emulators_dir=str(REPO_ROOT / "emulators"), @@ -998,17 +997,14 @@ class InstallMatchesATargetManifest(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - import generate_pack as gp 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) cls.db = json.loads(db_path.read_text(encoding="utf-8")) cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) def _manifest(self, platform, target_cores=None, target=None): - return self.gp.generate_manifest( + return packs_manifest.generate_manifest( platform, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"), emulators_dir=str(REPO_ROOT / "emulators"), emu_profiles=self.profiles, @@ -1056,9 +1052,6 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): from model.platforms import _platform_config_cache from model.profiles import _emulator_profiles_cache import generate_db - import generate_pack - - self.gp = generate_pack tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -1106,7 +1099,7 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): - return self.gp.generate_manifest( + return packs_manifest.generate_manifest( "p", "platforms", self.db, "bios", "platforms/_registry.yml", emulators_dir="emulators", emu_profiles=self.profiles, regions=regions, offline=True, @@ -1140,9 +1133,6 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): from model.platforms import _platform_config_cache from model.profiles import _emulator_profiles_cache import generate_db - import generate_pack - - self.gp = generate_pack tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -1192,7 +1182,7 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): - return self.gp.generate_manifest( + return packs_manifest.generate_manifest( "p", "platforms", self.db, "bios", "platforms/_registry.yml", emulators_dir="emulators", emu_profiles=self.profiles, regions=regions, offline=True, @@ -1226,9 +1216,6 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): from model.platforms import _platform_config_cache from model.profiles import _emulator_profiles_cache import generate_db - import generate_pack - - self.gp = generate_pack tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -1284,15 +1271,15 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): self.profiles = profiles.load_emulator_profiles("emulators") def _manifest(self, regions): - return self.gp.generate_manifest( + return packs_manifest.generate_manifest( "p", "platforms", self.db, "bios", "platforms/_registry.yml", emulators_dir="emulators", emu_profiles=self.profiles, regions=regions, offline=True, ) def _pack(self, regions): - record = self.gp.PackRecord() - self.gp.generate_pack( + record = archive.PackRecord() + platformpack.generate_pack( "p", "platforms", self.db, "bios", "", emulators_dir="emulators", emu_profiles=self.profiles, regions=regions, offline=True, record=record, ) @@ -1301,7 +1288,7 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): def test_the_slot_choices_are_computed_once(self): """pack_overrides recomputed the choices the manifest had just computed with the same arguments: 8% of a manifest run.""" - import slots + from packs import slots real = slots.slot_choices with mock.patch.object(slots, "slot_choices", side_effect=real) as counted: @@ -1383,7 +1370,7 @@ class ThePlatformsOwnSystemNamesAreAccepted(unittest.TestCase): source) def test_every_listed_system_gets_the_title_the_site_prints(self): - from generate_pack import system_titles + from packs.scope import system_titles files = [{"dest": "a.bin", "systems": ["sony-playstation", "nintendo-gba"]}] omitted = [{"dest": "b.bin", "systems": ["3do"]}] @@ -1431,12 +1418,10 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - import generate_pack as gp import pipeline - import verify from model.profiles import load_emulator_profiles - cls.gp, cls.pipeline, cls.verify = gp, pipeline, verify + cls.pipeline = pipeline cls.db = json.loads(db_path.read_text(encoding="utf-8")) cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -1447,7 +1432,7 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out, \ contextlib.redirect_stdout(io.StringIO()): - zip_path = self.gp.generate_pack( + zip_path = platformpack.generate_pack( platform, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"), out, emulators_dir=str(REPO_ROOT / "emulators"), @@ -1469,7 +1454,7 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): self.assertEqual(chosen, resolve_system_arg(system_id, systems, config)) self.assertEqual(chosen, [system_id]) - report = self.verify.verify_platform( + report = coverage.verify_platform( config, self.db, str(REPO_ROOT / "emulators"), self.profiles, system_filter=chosen, ) @@ -1485,7 +1470,7 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): self.assertTrue(written) self.assertEqual(credited, written) - manifest = self.gp.generate_manifest( + manifest = packs_manifest.generate_manifest( platform, str(REPO_ROOT / "platforms"), self.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "platforms" / "_registry.yml"), diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 2d5db7320..3a27a0df1 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -41,6 +41,8 @@ from pathlib import Path, PurePosixPath, PureWindowsPath from unittest import mock import install +from packs import archive as packs_archive +from packs import emulatorpack from tests.test_install_app import make_card from tests.test_install_selection import FakeRepository, _QuietHandler from tests.netguard import module_guard @@ -7617,11 +7619,11 @@ class _CardFixtures: if sys.version_info < BUILDER_FLOOR: # generate_pack.py's context managers need Python 3.9. return listing, None, {} - import generate_pack + from packs import scope pack_list = {"files": [{"path": dest, "sha1": entry["sha1"], "size": entry["size"]} for dest, entry in zip(payloads, files)]} - generate_pack.annotate_pack_systems(pack_list, generate_pack.pack_systems(install_list)) + scope.annotate_pack_systems(pack_list, scope.pack_systems(install_list)) name = {"minui": "MinUI", "misterfpga": "MiSTer_FPGA"}[plat] pack = self.root / f"{name}_v1_BIOS_Pack.zip" with zipfile.ZipFile(pack, "w") as archive: @@ -9246,14 +9248,14 @@ class PacksWordingAndDocs(unittest.TestCase): @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "generate_pack.py's context managers need Python 3.9") def test_a_pack_records_the_systems_of_its_files(self): - import generate_pack + from packs import scope install_list = {"files": [{"dest": "a.bin", "systems": ["3do"]}, {"dest": "b/c.bin", "systems": []}], "system_titles": {"3do": "3DO Interactive Multiplayer"}, "system_names": {"3do": ["3do"]}} manifest = {"files": [{"path": "a.bin"}, {"path": "b/c.bin"}, {"path": "README.md"}]} - generate_pack.annotate_pack_systems(manifest, generate_pack.pack_systems(install_list)) + scope.annotate_pack_systems(manifest, scope.pack_systems(install_list)) self.assertEqual([entry.get("systems") for entry in manifest["files"]], [["3do"], [], None]) self.assertEqual(manifest["system_titles"], {"3do": "3DO Interactive Multiplayer"}) @@ -16164,18 +16166,15 @@ class EmulatorChoiceMatchesTheEmulatorPack(unittest.TestCase): if sys.version_info < BUILDER_FLOOR: # 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 core.ziptools import build_zip_contents_index - - cls.gp = gp cls.db = json.loads(db_path.read_text(encoding="utf-8")) cls.zip_contents = build_zip_contents_index(cls.db) cls.by_path = {entry["path"]: sha1 for sha1, entry in cls.db["files"].items()} def pack(self, emulator: str) -> dict[str, str]: - record = self.gp.PackRecord() + record = packs_archive.PackRecord() with contextlib.redirect_stdout(io.StringIO()): - self.gp.generate_emulator_pack( + emulatorpack.generate_emulator_pack( [emulator], str(REPO_ROOT / "emulators"), self.db, str(REPO_ROOT / "bios"), str(REPO_ROOT / "tmp"), zip_contents=self.zip_contents, offline=True, record=record) diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index 3c0275425..63771575b 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -553,21 +553,21 @@ class ReleaseAssetNames(unittest.TestCase): self.assertEqual(name, os.path.basename(registered_path)) def test_manifest_checker_and_fetcher_agree_on_a_path(self): - import generate_pack + from packs import manifestentry expected = largefiles.asset_names(self.REGISTERED) gitignore = "\n".join(["tmp/", *self.REGISTERED]) + "\n" with tempfile.TemporaryDirectory() as root: Path(root, ".gitignore").write_text(gitignore, encoding="utf-8") - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() try: manifest = { - p: generate_pack._release_asset_name(os.path.join(root, p), root) + p: manifestentry._release_asset_name(os.path.join(root, p), root) for p in self.REGISTERED } finally: - generate_pack._registered.cache_clear() + manifestentry._registered.cache_clear() self.assertEqual(manifest, expected) sizes = {self.ET: 228138631, self.RTCW: 122757192, self.PUP: 10} diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index 9eaf71dd0..76fdd58ba 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -28,15 +28,12 @@ from unittest import mock import yaml import verify +from packs import coverage +from packs import report as packs_report 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, - launcher_file_names, - launcher_reads_not_held, - print_launcher_reads, -) +from cross_reference import LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, print_launcher_reads +from packs.crossref import launcher_file_names, launcher_reads_not_held ROOT = Path(__file__).resolve().parent.parent @@ -287,11 +284,11 @@ class LauncherGapTest(unittest.TestCase): def test_verify_counts_and_exit_code_are_unchanged(self) -> None: """A launcher name is reported, not judged: nothing else moves.""" - with_rows = verify.verify_platform( + with_rows = coverage.verify_platform( self.config, self.db, self.emulators_dir, self.profiles, data_dir_registry={} ) with mock.patch.object(verify, "launcher_reads_not_held", return_value=[]): - without = verify.verify_platform( + without = coverage.verify_platform( self.config, self.db, self.emulators_dir, self.profiles, data_dir_registry={}, ) @@ -313,13 +310,13 @@ class LauncherGapTest(unittest.TestCase): exit_code(without)) def test_verify_prints_a_count_and_lists_on_verbose(self) -> None: - result = verify.verify_platform( + result = coverage.verify_platform( self.config, self.db, self.emulators_dir, self.profiles, data_dir_registry={} ) for verbose, expected in ((False, "(--verbose lists them)"), (True, "absent.bin")): out = io.StringIO() with contextlib.redirect_stdout(out): - verify.print_platform_result(result, ["GapTest"], verbose=verbose) + packs_report.print_platform_result(result, ["GapTest"], verbose=verbose) self.assertIn("Launcher reads, not held: 3", out.getvalue()) self.assertIn(expected, out.getvalue()) diff --git a/tests/test_launcher_layer.py b/tests/test_launcher_layer.py index 5d2da4ac8..53bbc9ecc 100644 --- a/tests/test_launcher_layer.py +++ b/tests/test_launcher_layer.py @@ -428,7 +428,7 @@ class LauncherLayerTest(unittest.TestCase): """cross_reference --platform batocera listed duckstation's scph1002a.bin as packed while the PAL slot was filled by the launcher's scph5502.bin, which verify and the builder both knew.""" - from cross_reference import cross_reference, declared_names, load_platform_files + from packs.crossref import cross_reference, declared_names, load_platform_files from resolve.launchers import declared_destinations selected = ["launchertest"] @@ -453,7 +453,7 @@ class LauncherLayerTest(unittest.TestCase): def test_one_decision_for_verify_and_pack(self) -> None: """The layer is applied once, in the report both sides read.""" import generate_pack - import packextras + from packs import extras as packextras import verify self.assertIn("LauncherLayer(", inspect.getsource(verify.find_undeclared_files)) diff --git a/tests/test_launcher_placement.py b/tests/test_launcher_placement.py index 6da19ac88..77d1aa38f 100644 --- a/tests/test_launcher_placement.py +++ b/tests/test_launcher_placement.py @@ -26,8 +26,9 @@ import yaml 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 +from packs.manifest import generate_manifest +from packs.platformpack import generate_pack +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_layers.py b/tests/test_layers.py index 11f6cda26..35853444d 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -19,35 +19,35 @@ from pathlib import Path SCRIPTS = Path(__file__).resolve().parent.parent / "scripts" -PACKAGE_LAYERS = {"core": 0, "model": 1, "resolve": 2, "scraper": 3, "exporter": 3, "profiling": 3} +PACKAGE_LAYERS = {"core": 0, "model": 1, "resolve": 2, "packs": 3, "scraper": 3, "exporter": 3, "profiling": 3} LIBRARY_LAYER = 3 COMMAND_LAYER = 4 # The other domain packages a domain package may import. A package listed # here imports no sibling outside its set. SIBLING_IMPORTS: dict[str, frozenset[str]] = { + "packs": frozenset(), "profiling": frozenset(), } # Top-level modules other modules of scripts/ import: library code that a # later wave moves into a package. NOT_YET_PACKAGED = frozenset({ - "archive_build", "autorun", "build_port", "campaign", "campaign_profiles", - "campaign_rules", "check_buildbot_system", "check_release_assets", "commit_rules", "core_probe", - "cross_reference", "dedup", "derivations", "generate_event_schema", - "generate_pack", "generate_readme", "generate_site", "manifestselect", "measurement_records", - "packextras", "packpaths", "packreadme", "packresolve", "packverify", "pin_installer", - "pr_checks", "provenance_report", "refresh_data_dirs", - "release_record", "romfolders", "romset_recipes", "siteagents", "sitebootstrap", - "sitecollection", "sitediagrams", "siteentries", "siteexports", "siteguides", "sitehandheld", - "siteinputs", "sitemarkup", "sitemeasurements", "siterender", "sitesources", "sitestarlight", - "sitesteps", "sitewanted", "sitewrite", "slots", "split_pack", "validate_pr", "verify", + "archive_build", "autorun", "build_port", "campaign", "campaign_profiles", "campaign_rules", + "check_buildbot_system", "check_release_assets", "commit_rules", "core_probe", "derivations", + "generate_event_schema", "generate_readme", "generate_site", "measurement_records", + "pin_installer", "pr_checks", "provenance_report", "release_record", "romfolders", + "romset_recipes", "siteagents", "sitebootstrap", "sitecollection", "sitediagrams", + "siteentries", "siteexports", "siteguides", "sitehandheld", "siteinputs", "sitemarkup", + "sitemeasurements", "siterender", "sitesources", "sitestarlight", "sitesteps", "sitewanted", + "sitewrite", }) # Imports from a package module to a top-level module, left for the wave that # packages the top-level side. PENDING_TOP_LEVEL_IMPORTS = frozenset({ - ("exporter.doubled", "slots"), + ("packs.readme", "siteguides"), + ("packs.scope", "siterender"), }) diff --git a/tests/test_libretro_layout.py b/tests/test_libretro_layout.py index 787111e08..ff11d1f1a 100644 --- a/tests/test_libretro_layout.py +++ b/tests/test_libretro_layout.py @@ -15,7 +15,7 @@ import os import unittest from pathlib import Path -from packpaths import _resolve_destination +from packs.paths import _resolve_destination from resolve.validation import outside_gap_scope, read_from_save_dir, read_from_system_dir REPO_ROOT = Path(__file__).resolve().parents[1] @@ -63,7 +63,7 @@ class RetroArchCarriesDolphinWhereItReads(unittest.TestCase): 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 + from packs.extras import _collect_emulator_extras config = load_platform_config("retroarch") extras = _collect_emulator_extras( diff --git a/tests/test_maker_folder_names.py b/tests/test_maker_folder_names.py index 7d15f6fb7..fa5806c4c 100644 --- a/tests/test_maker_folder_names.py +++ b/tests/test_maker_folder_names.py @@ -36,7 +36,7 @@ from resolve.ownership import BUCKET_FOLDERS, names_manufacturer import generate_db import generate_pack as builder import generate_site -from verify import verify_platform +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_mame_devices.py b/tests/test_mame_devices.py index a5959a403..9ff399d26 100644 --- a/tests/test_mame_devices.py +++ b/tests/test_mame_devices.py @@ -626,8 +626,8 @@ class APickReadsTheEntrySystems(unittest.TestCase): self.assertTrue(entry_serves_systems({}, profile, ["snk-neogeo-mvs"])) def test_the_gap_report_and_the_extras_carry_them(self): - from packextras import _collect_emulator_extras, _extra_system_ids - from verify import find_undeclared_files + from packs.extras import _collect_emulator_extras, _extra_system_ids + from packs.gaps import find_undeclared_files profile = { "emulator": "MAME", "type": "libretro", "systems": self.SYSTEMS, diff --git a/tests/test_manifest_entry.py b/tests/test_manifest_entry.py index f35740427..5dd03ca99 100644 --- a/tests/test_manifest_entry.py +++ b/tests/test_manifest_entry.py @@ -18,7 +18,9 @@ from pathlib import Path from unittest import mock import generate_pack as gp -from manifestselect import SelectionIndex +from packs import manifestcores +from packs import manifestentry +from packs.manifestselect import SelectionIndex REPO_ROOT = Path(__file__).resolve().parent.parent @@ -44,9 +46,9 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase): # Every case hashes the file anew through its own compute_hashes: a # result another test verified for the same path and scan is a valid # cache hit, and it skipped the miscompute this class simulates. - saved = dict(gp._STABLE_HASHES) - gp._STABLE_HASHES.clear() - self.addCleanup(gp._STABLE_HASHES.update, saved) + saved = dict(manifestentry._STABLE_HASHES) + manifestentry._STABLE_HASHES.clear() + self.addCleanup(manifestentry._STABLE_HASHES.update, saved) def _run_core_entries(self, hashes: dict) -> tuple[list, dict, list]: name = Path(self.record["path"]).name @@ -64,7 +66,7 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase): omitted[full_dest] = reason with mock.patch.object(gp, "compute_hashes", return_value=hashes): - gp._manifest_core_entries( + manifestcores._manifest_core_entries( [extra], {}, self.db, str(REPO_ROOT / "bios"), "", str(REPO_ROOT), {}, True, region_drops=set(), case_insensitive=False, seen_destinations=set(), @@ -76,7 +78,7 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase): def test_a_copy_the_database_lacks_is_omitted(self): """A copy the scan never indexed has no repo path: an omission.""" - with mock.patch.object(gp, "_db_sha1_by_path", return_value={}): + with mock.patch.object(manifestentry, "_db_sha1_by_path", return_value={}): files, omitted, pack_only = self._run_core_entries( {"sha1": "0" * 40, "sha256": "0" * 64} ) diff --git a/tests/test_md5_pack_context.py b/tests/test_md5_pack_context.py index 9c08836b4..2392a415a 100644 --- a/tests/test_md5_pack_context.py +++ b/tests/test_md5_pack_context.py @@ -77,7 +77,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): from model.profiles import _emulator_profiles_cache import generate_db - import generate_pack as gp + from packs import emulatorpack with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as directory: root = Path(directory) @@ -101,11 +101,11 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): })) _emulator_profiles_cache.clear() try: - emulator_pack = gp.generate_emulator_pack( + emulator_pack = emulatorpack.generate_emulator_pack( ["triforce"], str(root / "emulators"), db, str(root / "bios"), str(out), offline=True, ) - system_pack = gp.generate_system_pack( + system_pack = emulatorpack.generate_system_pack( ["sega-triforce"], str(root / "emulators"), db, str(root / "bios"), str(out), offline=True, ) diff --git a/tests/test_minui_platform.py b/tests/test_minui_platform.py index 8248ae9f0..5fdc06f6f 100644 --- a/tests/test_minui_platform.py +++ b/tests/test_minui_platform.py @@ -262,7 +262,7 @@ class PackPlacesCoreFilesUnderTheTag(unittest.TestCase): }} def _pack(self) -> dict[str, bytes]: - from generate_pack import generate_pack + from packs.platformpack import generate_pack output = os.path.join(self.root, "dist") os.makedirs(output) @@ -310,8 +310,8 @@ class PackPlacesCoreFilesUnderTheTag(unittest.TestCase): self.assertEqual(len(groups), 2) def test_the_report_and_the_manifest_agree_with_the_pack(self): - from generate_pack import generate_manifest - from verify import verify_platform + from packs.manifest import generate_manifest + from packs.coverage import verify_platform packed = set(self._pack()) config = load_platform_config("test_minui", self.platforms) diff --git a/tests/test_native_mode.py b/tests/test_native_mode.py index 80a423470..40ba24892 100644 --- a/tests/test_native_mode.py +++ b/tests/test_native_mode.py @@ -84,7 +84,7 @@ class BothConsumersAgree(unittest.TestCase): def test_builder_and_verifier_share_one_predicate(self): from generate_pack import _intentional_hash_exclusion - from verify import compute_severity + from packs.verdicts import compute_severity self.assertTrue(callable(compute_severity)) @@ -100,7 +100,7 @@ class BothConsumersAgree(unittest.TestCase): ) def test_severity_uses_the_shared_predicate(self): - from verify import Severity, Status, compute_severity + from packs.verdicts import Severity, Status, compute_severity # Existence mode: a missing required file is a warning, not critical. self.assertEqual( @@ -146,12 +146,13 @@ class ThePolicyIsSpeltInOnePlace(unittest.TestCase): def test_an_unknown_mode_verifies_the_way_it_is_scored(self): """A typo in a platform YAML must not verify one way and score another.""" - import verify + from packs import coverage + from packs import verdicts self.assertFalse(nativemode.reads_file_contents("sha256")) self.assertEqual( - verify.compute_severity(verify.Status.MISSING, True, "sha256"), - verify.Severity.WARNING, + verdicts.compute_severity(verdicts.Status.MISSING, True, "sha256"), + verdicts.Severity.WARNING, ) config = { "platform": "Typo", @@ -159,7 +160,7 @@ class ThePolicyIsSpeltInOnePlace(unittest.TestCase): "systems": {}, "cores": [], } - result = verify.verify_platform( + result = coverage.verify_platform( config, {"files": {}, "indexes": {}}, emu_profiles={}, ) self.assertEqual(result["verification_mode"], nativemode.DEFAULT_MODE) @@ -220,7 +221,7 @@ class GapAnalysisAgreesWithTheBuilder(unittest.TestCase): def _in_repo(self, mode: str) -> bool: from model.profiles import _emulator_profiles_cache, load_emulator_profiles - from verify import find_undeclared_files + from packs.gaps import find_undeclared_files tmp, root, db = self._fixture() try: @@ -273,7 +274,7 @@ class CandidateVerdict(unittest.TestCase): def verdict(self, entry, *, standalone=False, include_all=False, declared=frozenset()): - from verify import _candidate_verdict + from packs.gaps import _candidate_verdict return _candidate_verdict( entry, entry.get("name", ""), standalone, include_all, set(declared) @@ -366,7 +367,7 @@ class SkippingIsNotSettling(unittest.TestCase): import tempfile from model.profiles import _emulator_profiles_cache, load_emulator_profiles - from verify import find_undeclared_files + from packs.gaps import find_undeclared_files tmp = tempfile.TemporaryDirectory() root = Path(tmp.name) diff --git a/tests/test_no_game_data.py b/tests/test_no_game_data.py index 175c3786e..cb9d13de3 100644 --- a/tests/test_no_game_data.py +++ b/tests/test_no_game_data.py @@ -31,10 +31,13 @@ import yaml 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 packs import archive as packs_archive +from packs import bysystem +from packs import manifest as packs_manifest +from packs import platformpack import install -import packverify -import verify +from packs import integrity as packverify +from packs import coverage REPO_ROOT = Path(__file__).resolve().parent.parent @@ -117,17 +120,17 @@ class _Fixture(unittest.TestCase): def pack(self, no_game_data: bool) -> tuple[str, set[str], str]: printed = io.StringIO() with contextlib.redirect_stdout(printed): - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "handheld", str(self.platforms), self.db, str(self.bios), str(self.out), emulators_dir=str(self.emulators), emu_profiles=PROFILES, offline=True, no_game_data=no_game_data, ) with zipfile.ZipFile(zip_path) as archive: - members = set(archive.namelist()) - set(builder.PACK_DOCUMENTS) + members = set(archive.namelist()) - set(packs_archive.PACK_DOCUMENTS) return zip_path, members, printed.getvalue() def manifest(self, no_game_data: bool = False) -> dict: - return builder.generate_manifest( + return packs_manifest.generate_manifest( "handheld", str(self.platforms), self.db, str(self.bios), str(self.platforms / "_registry.yml"), emulators_dir=str(self.emulators), emu_profiles=PROFILES, offline=True, no_game_data=no_game_data, @@ -184,7 +187,7 @@ class PackNarrowing(_Fixture): def test_verify_reports_the_pack_the_builder_wrote(self): zip_path, members, _ = self.pack(no_game_data=True) config = load_platform_config("handheld", str(self.platforms)) - result = verify.verify_platform( + result = coverage.verify_platform( config, self.db, str(self.emulators), PROFILES, no_game_data=True, ) self.assertEqual(set(result["pack_destinations"]), members) @@ -204,14 +207,14 @@ class PackNarrowing(_Fixture): def test_the_full_report_is_unchanged(self): config = load_platform_config("handheld", str(self.platforms)) - result = verify.verify_platform(config, self.db, str(self.emulators), PROFILES) + result = coverage.verify_platform(config, self.db, str(self.emulators), PROFILES) self.assertNotIn("left_out", result) self.assertEqual(set(result["pack_destinations"]), FIRMWARE | GAME) def test_split_parts_add_up_to_the_narrowed_pack(self): printed = io.StringIO() with contextlib.redirect_stdout(printed): - parts = builder.generate_split_packs( + parts = bysystem.generate_split_packs( "handheld", str(self.platforms), self.db, str(self.bios), str(self.out), emulators_dir=str(self.emulators), emu_profiles=PROFILES, offline=True, no_game_data=True, @@ -220,7 +223,7 @@ class PackNarrowing(_Fixture): for part in parts: self.assertIn("_NoGameData", part) with zipfile.ZipFile(part) as archive: - held |= set(archive.namelist()) - set(builder.PACK_DOCUMENTS) + held |= set(archive.namelist()) - set(packs_archive.PACK_DOCUMENTS) self.assertEqual(held, FIRMWARE) diff --git a/tests/test_owner_resolution.py b/tests/test_owner_resolution.py index 408770382..270aa953a 100644 --- a/tests/test_owner_resolution.py +++ b/tests/test_owner_resolution.py @@ -17,8 +17,8 @@ import tempfile import unittest from pathlib import Path -import cross_reference -import slots +from packs import crossref +from packs import slots from core.ziptools import build_zip_contents_index from model.database import load_database from model.profiles import load_emulator_profiles @@ -37,7 +37,7 @@ class ReadersNameTheOwner(unittest.TestCase): cls.sha1_by_path = {r["path"]: s for s, r in cls.db["files"].items()} def test_the_site_credits_the_copy_the_pack_ships(self): - consumers = cross_reference.FileConsumers( + consumers = crossref.FileConsumers( self.db, build_zip_contents_index(self.db) ) consumers.add_emulators(self.profiles) @@ -97,7 +97,7 @@ class EachForkReadsItsOwnCopy(unittest.TestCase): self._tree.cleanup() def test_the_site_credits_each_owner_with_its_copy(self): - consumers = cross_reference.FileConsumers(self.db, data_dir_registry={}) + consumers = crossref.FileConsumers(self.db, data_dir_registry={}) consumers.add_emulators({ owner: {"type": "standalone", "files": [{"name": self.NAME}]} for owner in self.sha1_of diff --git a/tests/test_pack_conformance_dirs.py b/tests/test_pack_conformance_dirs.py index 28356cb5f..c6c1ba081 100644 --- a/tests/test_pack_conformance_dirs.py +++ b/tests/test_pack_conformance_dirs.py @@ -17,7 +17,9 @@ from pathlib import Path from unittest import mock import generate_pack as gp -import packverify +from packs import finalize as packs_finalize +from packs import naming +from packs import integrity as packverify REPO_ROOT = Path(__file__).resolve().parents[1] @@ -42,7 +44,7 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase): if split: Path(self.tmp.name, "X_Split").mkdir(exist_ok=True) with self.subTest(split=split), mock.patch.object( - gp, "verify_and_finalize_packs", return_value=True + packs_finalize, "verify_and_finalize_packs", return_value=True ) as finalize: gp._run_platform_packs( self._args(split), [], {}, {}, {}, {}, {}, None @@ -63,21 +65,21 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase): with mock.patch.object(gp, "list_registered_platforms", return_value=["fix"]), \ mock.patch.object( - gp, "_expected_pack_names", + naming, "_expected_pack_names", return_value={"fix": {"Fix_BIOS_Pack.zip"}}, ), \ - mock.patch.object(gp, "_pack_archives", return_value=["Fix_BIOS_Pack.zip"]), \ + mock.patch.object(naming, "_pack_archives", return_value=["Fix_BIOS_Pack.zip"]), \ mock.patch.object( gp, "verify_pack", return_value=(True, {"summary": { "verified": 0, "total_files": 0, "untracked": 0, "errors": 0, }, "errors": []}), ), \ - mock.patch.object(gp, "inject_manifest"), \ - mock.patch.object(gp, "_target_cores_for", return_value=None), \ + mock.patch.object(packs_finalize, "inject_manifest"), \ + mock.patch.object(packs_finalize, "_target_cores_for", return_value=None), \ mock.patch.object(gp, "verify_pack_against_platform", record), \ mock.patch.object(packverify, "verify_pack_against_platform", record): - gp.verify_and_finalize_packs( + packs_finalize.verify_and_finalize_packs( str(out), {"files": {}, "indexes": {}}, platforms_dir="fixture-platforms", emulators_dir="fixture-emulators", diff --git a/tests/test_pack_core_extras.py b/tests/test_pack_core_extras.py index 6bae4cd22..2f17fc8eb 100644 --- a/tests/test_pack_core_extras.py +++ b/tests/test_pack_core_extras.py @@ -19,8 +19,10 @@ import zipfile from pathlib import Path import yaml +from packs import naming +from packs import platformpack -import packverify +from packs import integrity as packverify REPO_ROOT = Path(__file__).resolve().parent.parent @@ -150,9 +152,6 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): from model.platforms import _platform_config_cache from model.profiles import load_emulator_profiles, _emulator_profiles_cache import generate_db - import generate_pack - - self.gp = generate_pack tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -192,7 +191,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): self.profiles = load_emulator_profiles("emulators") def _build(self, source: str, required: bool) -> tuple[str, set[str]]: - zip_path = self.gp.generate_pack( + zip_path = platformpack.generate_pack( "p", "platforms", self.db, "bios", "out", emulators_dir="emulators", emu_profiles=self.profiles, source=source, required_only=required, offline=True, @@ -222,7 +221,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): ok, _c, _p, errors, *_rest = self._check(zip_path, source, required) self.assertTrue(ok, errors) self.assertEqual( - self.gp._pack_variant(os.path.basename(zip_path)), (source, required) + naming._pack_variant(os.path.basename(zip_path)), (source, required) ) def test_a_narrowed_pack_missing_a_required_file_fails(self): diff --git a/tests/test_pack_counts.py b/tests/test_pack_counts.py index c4e9e2f8e..808bc9425 100644 --- a/tests/test_pack_counts.py +++ b/tests/test_pack_counts.py @@ -32,12 +32,15 @@ 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 +from packs import archive as packs_archive +from packs import datatrees +from packs import manifest as packs_manifest +from packs import platformpack import generate_readme import generate_site import release_notes import release_record -import split_pack +from packs import parts HAS_JSONSCHEMA = jsonschema is not None REPO_ROOT = Path(__file__).resolve().parent.parent @@ -114,7 +117,7 @@ class PackCountFixture(unittest.TestCase): self._tmp.cleanup() def _manifest(self) -> dict: - return builder.generate_manifest( + return packs_manifest.generate_manifest( "demo", str(self.platforms), self.db, str(self.bios), str(self.platforms / "_registry.yml"), emulators_dir=str(self.emulators), emu_profiles=self.profiles, @@ -126,7 +129,7 @@ class ManifestStatesWhatThePackHolds(PackCountFixture): def test_the_count_is_the_one_an_extraction_shows(self): out = self.root / "dist" out.mkdir() - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "demo", str(self.platforms), self.db, str(self.bios), str(out), emulators_dir=str(self.emulators), emu_profiles=self.profiles, data_registry=self.registry, @@ -143,7 +146,7 @@ class ManifestStatesWhatThePackHolds(PackCountFixture): sum( member.file_size for member in members - if member.filename not in builder.PACK_DOCUMENTS + if member.filename not in packs_archive.PACK_DOCUMENTS ), ) @@ -163,7 +166,7 @@ class ManifestStatesWhatThePackHolds(PackCountFixture): self.addCleanup(_platform_config_cache.clear) out = self.root / "dist" out.mkdir() - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "demo", str(self.platforms), self.db, str(self.bios), str(out), emulators_dir=str(self.emulators), emu_profiles=self.profiles, data_registry=self.registry, @@ -178,7 +181,7 @@ class ManifestStatesWhatThePackHolds(PackCountFixture): ) self.assertEqual( manifest["pack_size"], - sum(m.file_size for m in members if m.filename not in builder.PACK_DOCUMENTS), + sum(m.file_size for m in members if m.filename not in packs_archive.PACK_DOCUMENTS), ) def test_the_installer_count_is_left_alone(self): @@ -186,7 +189,7 @@ class ManifestStatesWhatThePackHolds(PackCountFixture): manifest = self._manifest() self.assertEqual(manifest["total_files"], len(manifest["files"])) self.assertEqual(manifest["total_files"], 2) - self.assertEqual(manifest["pack_files"], 2 + 3 + len(builder.PACK_DOCUMENTS)) + self.assertEqual(manifest["pack_files"], 2 + 3 + len(packs_archive.PACK_DOCUMENTS)) @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") def test_the_manifest_schema_accepts_the_two_figures(self): @@ -221,7 +224,7 @@ class ManifestFollowsTheBuilder(PackCountFixture): def _pack_names(self) -> set[str]: out = self.root / "dist" out.mkdir(exist_ok=True) - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "demo", str(self.platforms), self.db, str(self.bios), str(out), emulators_dir=str(self.emulators), emu_profiles=self.profiles, data_registry=self.registry, @@ -313,7 +316,7 @@ class APackForAndroidHidesItsMedia(PackCountFixture): }})) out = self.root / f"dist-{target}" out.mkdir() - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "demo", str(self.platforms), self.db, str(self.bios), str(out), emulators_dir=str(self.emulators), emu_profiles=self.profiles, data_registry=self.registry, offline=True, target_name=target, @@ -331,7 +334,7 @@ class APackForAndroidHidesItsMedia(PackCountFixture): def test_the_manifest_counts_it(self): members = self._pack(None) - manifest = builder.generate_manifest( + manifest = packs_manifest.generate_manifest( "demo", str(self.platforms), self.db, str(self.bios), str(self.platforms / "_registry.yml"), emulators_dir=str(self.emulators), emu_profiles=self.profiles, @@ -340,7 +343,7 @@ class APackForAndroidHidesItsMedia(PackCountFixture): self.assertEqual(manifest["pack_files"], len(set(members) | {"manifest.json"})) def test_the_integrity_check_takes_it_for_a_marker(self): - import packverify + from packs import integrity as packverify buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as archive: @@ -351,7 +354,7 @@ class APackForAndroidHidesItsMedia(PackCountFixture): self.assertEqual(errors, ["zero-byte: empty.bin"]) def test_a_platform_without_android_gets_none(self): - self.assertEqual(builder.pack_markers("demo", None, str(self.platforms)), ()) + self.assertEqual(datatrees.pack_markers("demo", None, str(self.platforms)), ()) class TheTableDescribesTheRelease(unittest.TestCase): @@ -420,7 +423,7 @@ class ReleaseRecord(unittest.TestCase): "Demo_2.0_BIOS_Pack.zip", {f"dir/file{n}.bin": _incompressible(n) for n in range(6)}, ) - self.parts = split_pack.split_pack(big, limit=big.stat().st_size - 1) + self.parts = parts.split_pack(big, limit=big.stat().st_size - 1) def tearDown(self): self._tmp.cleanup() @@ -651,7 +654,7 @@ class CoreCopiesKeepTheirCategory(unittest.TestCase): copies, game data, under core files.""" def test_a_copy_counts_as_its_entry_says(self): - from packextras import _collect_emulator_extras, hidden_extras + from packs.extras import _collect_emulator_extras, hidden_extras with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: held = Path(tmp) / "x.dat" diff --git a/tests/test_pack_destinations.py b/tests/test_pack_destinations.py index 45035c286..3bcd57c53 100644 --- a/tests/test_pack_destinations.py +++ b/tests/test_pack_destinations.py @@ -63,8 +63,8 @@ class _Fixture(unittest.TestCase): def _both(self) -> tuple[dict, set[str]]: 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 + from packs.platformpack import generate_pack + from packs.coverage import verify_platform profiles = load_emulator_profiles(str(self.emulators)) report = verify_platform( @@ -114,7 +114,7 @@ class AnEntryWithoutAFileTakesNoPath(unittest.TestCase): base destination as a pack path, and the comparison failed on ''.""" def test_it_is_left_out(self): - from verify import _builder_placement + from packs.coverage import _builder_placement shipped, occupied = _builder_placement( [("s", "bios/", None), ("s", "", "x"), ("s", "bios/a.bin", "bios/a.bin")], False @@ -129,8 +129,9 @@ class ARequiredOnlyPack(_Fixture): def test_verify_credits_what_the_pack_writes(self): 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 + from packs.archive import PackRecord + from packs.platformpack import generate_pack + from packs.coverage import verify_platform (self.emulators / "coreemu.yml").write_text(yaml.safe_dump({ "emulator": "CoreEmu", "type": "libretro", "systems": ["sys"], @@ -174,7 +175,7 @@ class EveryNarrowingIsCompared(unittest.TestCase): import inspect import pipeline - from generate_pack import _narrowings + from packs.naming import _narrowings dimensions = set(inspect.signature(_narrowings).parameters) compared = set(pipeline.NARROWINGS_COMPARED) @@ -191,7 +192,8 @@ class EveryNarrowingIsCompared(unittest.TestCase): import inspect import pipeline - from generate_pack import _narrowings, generate_emulator_pack + from packs.naming import _narrowings + from packs.emulatorpack import generate_emulator_pack taken = (set(inspect.signature(_narrowings).parameters) & set(inspect.signature(generate_emulator_pack).parameters)) diff --git a/tests/test_pack_failures.py b/tests/test_pack_failures.py index d521a270f..489d068ff 100644 --- a/tests/test_pack_failures.py +++ b/tests/test_pack_failures.py @@ -17,6 +17,9 @@ from pathlib import Path from unittest import mock import generate_pack as gp +from packs import finalize +from packs import manifest +from packs import platformpack REPO_ROOT = Path(__file__).resolve().parents[1] @@ -44,8 +47,8 @@ class FailedPlatformFailsTheRun(unittest.TestCase): ) def test_pack_mode(self): - with mock.patch.object(gp, "generate_pack", _boom), \ - mock.patch.object(gp, "verify_and_finalize_packs", return_value=True), \ + with mock.patch.object(platformpack, "generate_pack", _boom), \ + mock.patch.object(finalize, "verify_and_finalize_packs", return_value=True), \ self.assertRaises(SystemExit) as ctx: gp._run_platform_packs( self._args(), [(["retropie"], "retropie")], {}, {}, {}, {}, {}, None @@ -53,7 +56,7 @@ class FailedPlatformFailsTheRun(unittest.TestCase): self.assertEqual(ctx.exception.code, 1) def test_manifest_mode(self): - with mock.patch.object(gp, "generate_manifest", _boom), self.assertRaises(SystemExit) as ctx: + with mock.patch.object(manifest, "generate_manifest", _boom), self.assertRaises(SystemExit) as ctx: gp._run_manifest_mode( self._args(), [(["retropie"], "retropie")], {}, {}, {}, {} ) diff --git a/tests/test_pack_file_names.py b/tests/test_pack_file_names.py index 37d38e62a..9b0a8e0c9 100644 --- a/tests/test_pack_file_names.py +++ b/tests/test_pack_file_names.py @@ -15,7 +15,8 @@ import tempfile import unittest from pathlib import Path -from generate_pack import _name_part, generate_emulator_pack +from packs.naming import _name_part +from packs.emulatorpack import generate_emulator_pack REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_pack_grouping.py b/tests/test_pack_grouping.py index 6e189b9eb..b24c09fd3 100644 --- a/tests/test_pack_grouping.py +++ b/tests/test_pack_grouping.py @@ -21,7 +21,7 @@ class SlotPassReadsTheRegionGrouping(unittest.TestCase): def test_ranked_mega_cd_alternatives_are_decided(self): if not (REPO_ROOT / "database.json").is_file(): self.skipTest("database.json not built") - import generate_pack as gp + from packs import platformpack from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -32,7 +32,7 @@ class SlotPassReadsTheRegionGrouping(unittest.TestCase): db = load_database("database.json") profiles = load_emulator_profiles("emulators") config = load_platform_config("retroarch", "platforms") - drops, _fallbacks, _undecided = gp._select_variants( + drops, _fallbacks, _undecided = platformpack._select_variants( config, config["systems"], "emulators", db, config.get("base_destination", ""), profiles, None, "full", regions=None, one_per_slot=True, @@ -56,7 +56,7 @@ class VariantGroupSpansSystems(unittest.TestCase): """ if not (REPO_ROOT / "database.json").is_file(): self.skipTest("database.json not built") - import generate_pack as gp + from packs import platformpack from model import region from model.database import load_database from model.profiles import load_emulator_profiles @@ -68,7 +68,7 @@ class VariantGroupSpansSystems(unittest.TestCase): db = load_database("database.json") profiles = load_emulator_profiles("emulators") config = load_platform_config("retroarch", "platforms") - drops, _fallbacks, _undecided = gp._select_variants( + drops, _fallbacks, _undecided = platformpack._select_variants( config, config["systems"], "emulators", db, config.get("base_destination", ""), profiles, None, "full", regions=region.parse_requested("us"), one_per_slot=False, diff --git a/tests/test_pack_integrity.py b/tests/test_pack_integrity.py index b3465a844..ecc512145 100644 --- a/tests/test_pack_integrity.py +++ b/tests/test_pack_integrity.py @@ -32,7 +32,7 @@ def _pack_path(platform_name: str) -> str | None: """Path of the platform's full pack, by the exact name the builder writes.""" if not os.path.isdir(DIST_DIR): return None - from generate_pack import _expected_pack_names + from packs.naming import _expected_pack_names names = _expected_pack_names([platform_name], PLATFORMS_DIR, [], None) for entry in sorted(names[platform_name]): diff --git a/tests/test_pack_member_identity.py b/tests/test_pack_member_identity.py index 10574805d..0df62c56c 100644 --- a/tests/test_pack_member_identity.py +++ b/tests/test_pack_member_identity.py @@ -19,7 +19,7 @@ import unittest import zipfile from pathlib import Path -from packverify import verify_pack +from packs.integrity import verify_pack REPO_ROOT = Path(__file__).resolve().parents[1] @@ -92,7 +92,7 @@ class OneComparisonOfArchiveMembers(unittest.TestCase): import tempfile import zipfile - from packverify import _same_members + from packs.integrity import _same_members def archive(members: dict) -> bytes: buffer = io.BytesIO() diff --git a/tests/test_pack_readme.py b/tests/test_pack_readme.py index f8c47a612..cabad65a9 100644 --- a/tests/test_pack_readme.py +++ b/tests/test_pack_readme.py @@ -16,7 +16,7 @@ from pathlib import Path import yaml -from packreadme import _build_readme +from packs.readme import _build_readme REPO_ROOT = Path(__file__).resolve().parents[1] @@ -116,7 +116,7 @@ class TheOneLinerFollowsTheRegistry(unittest.TestCase): def test_the_commands_are_written_once(self): """The address comes from install_base in platforms/_guides.yml, the one the site's commands use.""" - import packreadme + from packs import readme as packreadme import sitebootstrap from siteguides import INSTALL_BASE diff --git a/tests/test_path_conflict_status.py b/tests/test_path_conflict_status.py index 15101b3e8..04ba371fe 100644 --- a/tests/test_path_conflict_status.py +++ b/tests/test_path_conflict_status.py @@ -23,8 +23,9 @@ import yaml 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 +from packs import emulatorpack +from packs import platformpack +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent @@ -79,7 +80,7 @@ class ConflictingDeclarations(unittest.TestCase): out.mkdir() report = io.StringIO() with contextlib.redirect_stdout(report): - builder.generate_pack( + platformpack.generate_pack( "conflict", str(self.platforms), self.db, str(self.root / "bios"), str(out), emulators_dir=str(self.emulators), emu_profiles={}, offline=True, @@ -156,7 +157,7 @@ class AnExtraDoesNotPassAHashCheck(unittest.TestCase): out.mkdir() report = io.StringIO() with contextlib.redirect_stdout(report): - builder.generate_pack( + platformpack.generate_pack( "hashed", str(self.platforms), self.db, str(self.root / "bios"), str(out), emulators_dir=str(self.emulators), offline=True, ) @@ -210,7 +211,7 @@ class TheEmulatorPackShipsWhatTheCoreAccepts(unittest.TestCase): out.mkdir() report = io.StringIO() with contextlib.redirect_stdout(report): - zip_path = builder.generate_emulator_pack( + zip_path = emulatorpack.generate_emulator_pack( ["mac"], str(self.emulators), self.db, str(self.root / "bios"), str(out), offline=True, ) @@ -219,7 +220,8 @@ class TheEmulatorPackShipsWhatTheCoreAccepts(unittest.TestCase): self.assertNotIn("ROM", archive.namelist()) def test_verify_does_not_call_it_ok(self): - from verify import Severity, verify_emulator + from packs.verdicts import Severity + from packs.emulatorcheck import verify_emulator result = verify_emulator(["mac"], str(self.emulators), self.db) self.assertEqual(result["severity_counts"][Severity.OK], 0) @@ -263,12 +265,13 @@ class AlternativesAgreeWithThePack(unittest.TestCase): def test_verify_counts_what_the_pack_ships(self): import zipfile - from verify import Status, verify_emulator + from packs.verdicts import Status + from packs.emulatorcheck import verify_emulator out = self.root / "dist" out.mkdir() with contextlib.redirect_stdout(io.StringIO()): - zip_path = builder.generate_emulator_pack( + zip_path = emulatorpack.generate_emulator_pack( ["eng"], str(self.emulators), self.db, str(self.root / "bios"), str(out), offline=True, ) @@ -323,13 +326,14 @@ class AMaskedArchiveIsMissing(unittest.TestCase): self._tmp.cleanup() def test_both_report_the_archive_missing(self): - from verify import Status, verify_emulator + from packs.verdicts import Status + from packs.emulatorcheck import verify_emulator out = self.root / "dist" out.mkdir() report = io.StringIO() with contextlib.redirect_stdout(report): - builder.generate_emulator_pack( + emulatorpack.generate_emulator_pack( ["a", "b"], str(self.emulators), self.db, str(self.root / "bios"), str(out), offline=True, ) diff --git a/tests/test_path_null_copies.py b/tests/test_path_null_copies.py index 76db05ecf..8686c612a 100644 --- a/tests/test_path_null_copies.py +++ b/tests/test_path_null_copies.py @@ -27,7 +27,7 @@ class NoPathNoCopy(unittest.TestCase): 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 + from packs.extras import _collect_emulator_extras profiles = load_emulator_profiles("emulators") nameless = { diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index 1ce25ef60..55f048977 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -21,7 +21,8 @@ from pathlib import Path from unittest import mock import refresh_data_dirs as rdd -from generate_pack import _data_directory_members +from packs import datadirs +from packs.datatrees import _data_directory_members REPO_ROOT = Path(__file__).resolve().parents[1] @@ -60,7 +61,7 @@ class RefreshConcurrency(unittest.TestCase): ), mock.patch.object( rdd.shutil, "move", side_effect=AssertionError("copy across filesystems") ): - count = rdd._download_and_extract_zip("https://x/pak.zip", str(self.cache)) + count = datadirs._download_and_extract_zip("https://x/pak.zip", str(self.cache)) self.assertEqual(count, 1) self.assertEqual((self.cache / "a.bin").read_bytes(), b"new") leftovers = [p.name for p in self.cache.parent.iterdir() if p.name != "pak"] @@ -87,9 +88,9 @@ class RefreshConcurrency(unittest.TestCase): entry = {"source_type": "zip", "source_url": "https://x/pak.zip", "local_cache": str(self.cache)} with mock.patch.object(rdd.urllib.request, "urlopen", fake_urlopen), \ - mock.patch.object(rdd, "_get_remote_etag", return_value="e1"): + mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"): self.assertTrue( - rdd.refresh_entry("pak", entry, force=True, versions_path=self.versions) + datadirs.refresh_entry("pak", entry, force=True, versions_path=self.versions) ) self.assertEqual(seen, [True]) @@ -102,14 +103,14 @@ class RefreshConcurrency(unittest.TestCase): "local_cache": str(self.cache)} with mock.patch.object(rdd.urllib.request, "urlopen", lambda *a, **k: _Response(payload)), \ - mock.patch.object(rdd, "_get_remote_etag", return_value="e1"): - self.assertTrue(rdd.refresh_entry("pak", entry, versions_path=self.versions)) - self.assertEqual(rdd._load_versions(self.versions)["pak"]["archive_size"], + mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"): + self.assertTrue(datadirs.refresh_entry("pak", entry, versions_path=self.versions)) + self.assertEqual(datadirs._load_versions(self.versions)["pak"]["archive_size"], len(payload)) - rdd._record_version("pak", {"sha": "e1"}, self.versions) + datadirs._record_version("pak", {"sha": "e1"}, self.versions) (self.cache / "a.bin").write_bytes(b"kept") - self.assertFalse(rdd.refresh_entry("pak", entry, versions_path=self.versions)) - self.assertEqual(rdd._load_versions(self.versions)["pak"], + self.assertFalse(datadirs.refresh_entry("pak", entry, versions_path=self.versions)) + self.assertEqual(datadirs._load_versions(self.versions)["pak"], {"sha": "e1", "archive_size": len(payload)}) self.assertEqual((self.cache / "a.bin").read_bytes(), b"kept") @@ -120,15 +121,15 @@ class RefreshConcurrency(unittest.TestCase): import fcntl self.cache.mkdir(parents=True) - rdd._record_version("pak", {"sha": "e1", "archive_size": 1}, self.versions) + datadirs._record_version("pak", {"sha": "e1", "archive_size": 1}, self.versions) entry = {"source_type": "zip", "source_url": "https://x/pak.zip", "local_cache": str(self.cache)} result: list = [] with open(self.cache.with_name(".pak.lock"), "a") as reader, \ - mock.patch.object(rdd, "_get_remote_etag", return_value="e1"): + mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"): fcntl.flock(reader, fcntl.LOCK_SH) worker = threading.Thread(target=lambda: result.append( - rdd.refresh_entry("pak", entry, versions_path=self.versions) + datadirs.refresh_entry("pak", entry, versions_path=self.versions) ), daemon=True) worker.start() worker.join(timeout=20) @@ -148,10 +149,10 @@ class RefreshConcurrency(unittest.TestCase): entered = threading.Event() def refresh() -> None: - with rdd.cache_lock(self.cache): + with datadirs.cache_lock(self.cache): entered.set() - with open(lock_path, "a") as reader, self.assertLogs(rdd.log, "WARNING") as logs: + with open(lock_path, "a") as reader, self.assertLogs(datadirs.log, "WARNING") as logs: fcntl.flock(reader, fcntl.LOCK_SH) worker = threading.Thread(target=refresh, daemon=True) worker.start() @@ -171,14 +172,14 @@ class RefreshConcurrency(unittest.TestCase): Path(self.versions).parent.mkdir(parents=True) Path(self.versions).write_text(json.dumps({"keep": {"sha": "1"}})) with mock.patch.object(rdd.json, "dump", side_effect=OSError("disk full")), self.assertRaises(OSError): - rdd._save_versions({"keep": {"sha": "2"}}, self.versions) + datadirs._save_versions({"keep": {"sha": "2"}}, self.versions) self.assertEqual(json.loads(Path(self.versions).read_text()), {"keep": {"sha": "1"}}) def test_concurrent_writers_keep_each_other(self): keys = [f"k{i}" for i in range(16)] threads = [ threading.Thread( - target=rdd._record_version, args=(k, {"sha": k}, self.versions) + target=datadirs._record_version, args=(k, {"sha": k}, self.versions) ) for k in keys ] @@ -186,7 +187,7 @@ class RefreshConcurrency(unittest.TestCase): thread.start() for thread in threads: thread.join() - self.assertEqual(sorted(rdd._load_versions(self.versions)), sorted(keys)) + self.assertEqual(sorted(datadirs._load_versions(self.versions)), sorted(keys)) class PackWalkHoldsTheCache(unittest.TestCase): @@ -216,7 +217,7 @@ class EmulatorPackHoldsTheCache(unittest.TestCase): def test_the_walk_holds_a_shared_lock(self): import fcntl - from generate_pack import _pack_data_tree + from packs.datatrees import _pack_data_tree with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: cache = Path(tmp) / "data" / "scummvm" @@ -234,7 +235,7 @@ class EmulatorPackHoldsTheCache(unittest.TestCase): fcntl.flock(handle, fcntl.LOCK_UN) held.append(False) - with mock.patch("generate_pack._add_pack_member", member): + with mock.patch("packs.archive._add_pack_member", member): _pack_data_tree(None, str(cache), "scummvm", set(), set(), set()) self.assertEqual(held, [True]) @@ -248,11 +249,11 @@ class AWaitIsAnnounced(unittest.TestCase): taken = threading.Event() def second_run() -> None: - with rdd.cache_lock(cache): + with datadirs.cache_lock(cache): taken.set() - with self.assertLogs(rdd.log, "WARNING") as logs: - with rdd.cache_lock(cache): + with self.assertLogs(datadirs.log, "WARNING") as logs: + with datadirs.cache_lock(cache): worker = threading.Thread(target=second_run) worker.start() for _ in range(100): @@ -270,9 +271,9 @@ class DryRunReport(unittest.TestCase): """What a dry run says: why each entry would be fetched, and how many.""" def test_a_quoted_etag_is_cut_without_its_quotes(self): - self.assertEqual(rdd._short_tag('"0x8DF0B72EB52A1C0"'), "0x8DF0B72EB5") - self.assertEqual(rdd._short_tag('W/"2685251384"'), "2685251384") - self.assertEqual(rdd._short_tag(None), "none") + self.assertEqual(datadirs._short_tag('"0x8DF0B72EB52A1C0"'), "0x8DF0B72EB5") + self.assertEqual(datadirs._short_tag('W/"2685251384"'), "2685251384") + self.assertEqual(datadirs._short_tag(None), "none") def test_the_remote_tag_is_shown_beside_the_cached_one(self): with tempfile.TemporaryDirectory() as tmp: @@ -280,9 +281,9 @@ class DryRunReport(unittest.TestCase): versions.write_text(json.dumps({"k": {"etag": '"2725165595"', "archive_size": 1}})) entry = {"source_type": "zip", "source_url": "https://x.invalid/a.zip", "local_cache": tmp} - with mock.patch.object(rdd, "_get_remote_etag", return_value='"2685251384"'), \ - self.assertLogs(rdd.log, "INFO") as logs: - self.assertTrue(rdd.refresh_entry("k", entry, dry_run=True, + with mock.patch.object(datadirs, "_get_remote_etag", return_value='"2685251384"'), \ + self.assertLogs(datadirs.log, "INFO") as logs: + self.assertTrue(datadirs.refresh_entry("k", entry, dry_run=True, versions_path=str(versions))) self.assertIn("cached: 2725165595, remote: 2685251384", logs.output[0]) @@ -302,7 +303,7 @@ class TheManifestCarriesTheArchiveSize(unittest.TestCase): the installer announces as the tree's download.""" def test_recorded_size_is_written_and_an_unrecorded_one_left_out(self): - from generate_pack import _manifest_data_directories + from packs.datatrees import _manifest_data_directories (REPO_ROOT / "tmp").mkdir(exist_ok=True) with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: diff --git a/tests/test_refresh_failures.py b/tests/test_refresh_failures.py index f91527f13..f810e69f2 100644 --- a/tests/test_refresh_failures.py +++ b/tests/test_refresh_failures.py @@ -22,6 +22,8 @@ from pathlib import Path from unittest import mock import check_buildbot_system +import refresh_data_dirs +from packs import datadirs REPO_ROOT = Path(__file__).resolve().parent.parent @@ -153,9 +155,6 @@ class AnEmptyExtractionKeepsTheCache(unittest.TestCase): directory, recorded the version and reported success.""" def setUp(self): - import refresh_data_dirs - - self.module = refresh_data_dirs scratch = Path(__file__).resolve().parent.parent / "tmp" scratch.mkdir(exist_ok=True) self.root = Path(tempfile.mkdtemp(dir=scratch)) @@ -172,8 +171,8 @@ class AnEmptyExtractionKeepsTheCache(unittest.TestCase): payload.write_bytes(b"x") with tarfile.open(archive, "w:gz") as tf: tf.add(payload, arcname="repo-main/OtherDir/a.txt") - with self.assertRaises(self.module.NothingExtractedError): - self.module._download_and_extract( + with self.assertRaises(datadirs.NothingExtractedError): + datadirs._download_and_extract( archive.as_uri(), "repo-main/Data/Sys", str(self.cache), [] ) self.assertEqual((self.cache / "keep.dat").read_bytes(), b"cached") @@ -184,8 +183,8 @@ class AnEmptyExtractionKeepsTheCache(unittest.TestCase): archive = self.root / "archive.zip" with zipfile.ZipFile(archive, "w") as zf: zf.writestr("only/", b"") - with self.assertRaises(self.module.NothingExtractedError): - self.module._download_and_extract_zip(archive.as_uri(), str(self.cache)) + with self.assertRaises(datadirs.NothingExtractedError): + datadirs._download_and_extract_zip(archive.as_uri(), str(self.cache)) self.assertEqual((self.cache / "keep.dat").read_bytes(), b"cached") @@ -195,7 +194,7 @@ class TheVersionIsReadBeforeTheDownload(unittest.TestCase): run called it up to date.""" def test_a_build_published_during_the_download(self): - import refresh_data_dirs as rdd + from packs import datadirs root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) @@ -211,9 +210,9 @@ class TheVersionIsReadBeforeTheDownload(unittest.TestCase): versions = root / "versions.json" entry = {"source_type": "zip", "source_url": "https://example.invalid/Sys.zip", "local_cache": str(root / "cache")} - with mock.patch.object(rdd, "_get_remote_etag", etag), \ - mock.patch.object(rdd, "_download_and_extract_zip", download): - self.assertTrue(rdd._refresh_entry("sys", entry, True, False, str(versions))) + with mock.patch.object(datadirs, "_get_remote_etag", etag), \ + mock.patch.object(datadirs, "_download_and_extract_zip", download): + self.assertTrue(datadirs._refresh_entry("sys", entry, True, False, str(versions))) self.assertEqual(json.loads(versions.read_text())["sys"]["sha"], "build-1") @@ -222,9 +221,6 @@ class ABadResponseIsTriedAgain(unittest.TestCase): failed the whole data step on it, and the next download was fine.""" def setUp(self) -> None: - import refresh_data_dirs as rdd - - self.rdd = rdd root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, root, True) self.versions = str(root / "versions.json") @@ -243,21 +239,21 @@ class ABadResponseIsTriedAgain(unittest.TestCase): with mock.patch.object(self.rdd, "_get_remote_etag", lambda _url: "tag"), \ mock.patch.object(self.rdd, "_download_and_extract_zip", download), \ - mock.patch.object(self.rdd.time, "sleep", self.waits.append): - return self.rdd._refresh_entry("s", self.entry, True, False, self.versions) + mock.patch.object(refresh_data_dirs.time, "sleep", self.waits.append): + return datadirs._refresh_entry("s", self.entry, True, False, self.versions) def test_a_bad_archive_then_a_good_one_refreshes(self): self.assertTrue(self.run_with([zipfile.BadZipFile("File is not a zip file"), 12])) - self.assertEqual(self.waits, [self.rdd.DOWNLOAD_RETRY_WAITS[0]]) + self.assertEqual(self.waits, [datadirs.DOWNLOAD_RETRY_WAITS[0]]) def test_a_source_bad_on_every_try_fails_after_them(self): bad = zipfile.BadZipFile("File is not a zip file") - tries = len(self.rdd.DOWNLOAD_RETRY_WAITS) + 1 + tries = len(datadirs.DOWNLOAD_RETRY_WAITS) + 1 self.assertIsNone(self.run_with([bad] * tries)) - self.assertEqual(self.waits, list(self.rdd.DOWNLOAD_RETRY_WAITS)) + self.assertEqual(self.waits, list(datadirs.DOWNLOAD_RETRY_WAITS)) def test_an_empty_archive_is_not_tried_again(self): - self.assertIsNone(self.run_with([self.rdd.NothingExtractedError("nothing")])) + self.assertIsNone(self.run_with([datadirs.NothingExtractedError("nothing")])) self.assertEqual(self.waits, []) diff --git a/tests/test_region.py b/tests/test_region.py index 2a6deadcf..5cd13a461 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -15,7 +15,7 @@ from model import profiles as model_profiles from model.profiles import _emulator_profiles_cache from model import region from resolve import regions as resolve_regions -from packextras import emulator_region_drops +from packs.extras import emulator_region_drops class TestVocabulary(unittest.TestCase): @@ -475,7 +475,7 @@ class TestFallbackGroups(unittest.TestCase): ) def test_the_readme_names_a_slot_as_a_reader_does(self): - from packreadme import _group_label + from packs.readme import _group_label self.assertEqual(_group_label("PicoDrive:variant:megacd"), "megacd (PicoDrive)") self.assertEqual(_group_label("sega-mega-cd"), "sega-mega-cd") @@ -699,7 +699,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): from model import profiles as model_profiles from model.profiles import _emulator_profiles_cache import generate_pack as builder - import verify as reporter + from packs import coverage tmp, root, db, config = self._fixture() try: @@ -717,10 +717,10 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): "the builder must drop the Japanese alternative, not the US one", ) - plain = reporter.verify_platform( + plain = coverage.verify_platform( config, db, str(root / "emulators"), profiles, ) - narrowed = reporter.verify_platform( + narrowed = coverage.verify_platform( config, db, str(root / "emulators"), profiles, regions=["north-america"], ) @@ -742,7 +742,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): for a region the request excludes.""" from model import profiles as model_profiles from model.profiles import _emulator_profiles_cache - import verify as reporter + from packs import coverage tmp, root, db, config = self._fixture() try: @@ -751,10 +751,10 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): del db["indexes"]["by_name"]["jp.bin"] _emulator_profiles_cache.clear() profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) - plain = reporter.verify_platform( + plain = coverage.verify_platform( config, db, str(root / "emulators"), profiles, ) - narrowed = reporter.verify_platform( + narrowed = coverage.verify_platform( config, db, str(root / "emulators"), profiles, regions=["north-america"], ) @@ -772,20 +772,21 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): answers the request. verify said all OK and named none.""" from model import profiles as model_profiles from model.profiles import _emulator_profiles_cache - import verify as reporter + from packs import coverage + from packs import report as packs_report tmp, root, db, config = self._fixture() try: _emulator_profiles_cache.clear() profiles = model_profiles.load_emulator_profiles(str(root / "emulators")) - result = reporter.verify_platform( + result = coverage.verify_platform( config, db, str(root / "emulators"), profiles, regions=["brazil"], ) self.assertEqual(result["region_fallbacks"], ["demo-system"]) out = io.StringIO() with contextlib.redirect_stdout(out): - reporter.print_platform_result(result, ["Demo"]) + packs_report.print_platform_result(result, ["Demo"]) self.assertIn("all kept (1): demo-system", out.getvalue()) finally: _emulator_profiles_cache.clear() @@ -824,7 +825,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): repo = Path(__file__).resolve().parent.parent if not (repo / "emulators" / "o2em.yml").is_file(): self.skipTest("no o2em profile") - from verify import verify_emulator + from packs.emulatorcheck import verify_emulator from model.database import load_database db = load_database(str(repo / "database.json")) @@ -1311,8 +1312,8 @@ class ARefusedRegionalFileHoldsNoSlot(unittest.TestCase): import yaml - from generate_pack import generate_emulator_pack - from verify import verify_emulator + from packs.emulatorpack import generate_emulator_pack + from packs.emulatorcheck import verify_emulator _emulator_profiles_cache.clear() repo = Path(__file__).resolve().parents[1] @@ -1459,7 +1460,7 @@ class RegionWordsInAPackReadme(unittest.TestCase): """The pack README title-cased each slug: asia-ntsc read "Asia Ntsc".""" def test_the_priority_line_reads_as_written(self): - from packreadme import _build_readme + from packs.readme import _build_readme readme = _build_readme( "retroarch", "RetroArch", "system", 1, 1, diff --git a/tests/test_region_agnostic_scan.py b/tests/test_region_agnostic_scan.py index 2efa728da..d4dba731f 100644 --- a/tests/test_region_agnostic_scan.py +++ b/tests/test_region_agnostic_scan.py @@ -29,7 +29,7 @@ class ScanCopiesStay(unittest.TestCase): 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 + from packs.extras import platform_region_groups db = load_database("database.json") profiles = load_emulator_profiles("emulators") diff --git a/tests/test_region_groups.py b/tests/test_region_groups.py index dcaa40774..2837c8156 100644 --- a/tests/test_region_groups.py +++ b/tests/test_region_groups.py @@ -12,7 +12,7 @@ import tests import unittest from pathlib import Path -from packextras import extra_region_groups, system_spellings +from packs.extras import extra_region_groups, system_spellings REPO_ROOT = Path(__file__).resolve().parent.parent @@ -50,7 +50,7 @@ class TheEnterpriseKeepsItsRom(unittest.TestCase): 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 + from packs.extras import platform_region_groups db = load_database(str(REPO_ROOT / "database.json")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -113,7 +113,7 @@ class ALosingClaimIsKeyedLikeTheWinner(unittest.TestCase): 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 + from packs.extras import platform_region_groups previous = os.getcwd() os.chdir(REPO_ROOT) diff --git a/tests/test_region_held.py b/tests/test_region_held.py index c7b85c7f4..999152a5d 100644 --- a/tests/test_region_held.py +++ b/tests/test_region_held.py @@ -17,7 +17,7 @@ import tempfile import unittest from pathlib import Path -from packextras import _ships +from packs.extras import _ships REPO_ROOT = Path(__file__).resolve().parents[1] @@ -92,7 +92,7 @@ class ADataDirectoryCopyIsHeld(unittest.TestCase): ) def test_emulator_entry_from_a_data_tree(self): - from packextras import _emulator_ships + from packs.extras import _emulator_ships from resolve.validation import _build_validation_index profile = self.profiles["dolphin-mmjr2"] diff --git a/tests/test_region_required_only.py b/tests/test_region_required_only.py index 4a4a40937..d00445328 100644 --- a/tests/test_region_required_only.py +++ b/tests/test_region_required_only.py @@ -14,7 +14,7 @@ import ast import unittest from pathlib import Path -from packextras import platform_region_groups +from packs.extras import platform_region_groups REPO_ROOT = Path(__file__).resolve().parents[1] @@ -48,7 +48,7 @@ class EmulatorModeToo(unittest.TestCase): the optional US cards won the group, then --required-only removed them.""" def test_the_required_card_survives(self): - from packextras import emulator_region_drops + from packs.extras import emulator_region_drops profile = {"systems": ["nec-pc-engine"], "files": [ {"name": "syscard3.pce", "required": True, "region": ["japan"]}, diff --git a/tests/test_required_only_twins.py b/tests/test_required_only_twins.py index e4858d6ec..b53841bd7 100644 --- a/tests/test_required_only_twins.py +++ b/tests/test_required_only_twins.py @@ -24,7 +24,8 @@ import yaml from model.platforms import _platform_config_cache from model.profiles import _emulator_profiles_cache import generate_db -import generate_pack as builder +from packs import manifest as packs_manifest +from packs import platformpack class RequiredTwins(unittest.TestCase): @@ -80,7 +81,7 @@ class RequiredTwins(unittest.TestCase): def test_the_required_only_pack_carries_the_required_file(self): out = self.root / "dist" out.mkdir() - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "twins", str(self.platforms), self.db, str(self.root / "bios"), str(out), emulators_dir=str(self.emulators), emu_profiles={}, required_only=True, offline=True, @@ -89,7 +90,7 @@ class RequiredTwins(unittest.TestCase): self.assertIn("ATARIOSB.ROM", archive.namelist()) def test_the_required_only_manifest_lists_it(self): - manifest = builder.generate_manifest( + manifest = packs_manifest.generate_manifest( "twins", str(self.platforms), self.db, str(self.root / "bios"), str(self.platforms / "_registry.yml"), emulators_dir=str(self.emulators), emu_profiles={}, diff --git a/tests/test_romm_hash_rule.py b/tests/test_romm_hash_rule.py index af535f8c0..013ff065d 100644 --- a/tests/test_romm_hash_rule.py +++ b/tests/test_romm_hash_rule.py @@ -19,7 +19,7 @@ from pathlib import Path from resolve.nativemode import HASH_RULES, SIZE_AND_ANY_HASH from resolve.validation import baseline_verdict, frontend_digest_matches -from verify import Status, verify_entry_md5 +from packs.verdicts import Status, verify_entry_md5 REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_save_root.py b/tests/test_save_root.py index 4b5d9a2a4..65883cbb4 100644 --- a/tests/test_save_root.py +++ b/tests/test_save_root.py @@ -31,7 +31,7 @@ from unittest import mock import yaml -from packpaths import ( +from packs.paths import ( EMULATOR_PACK_SAVE_FOLDER, SaveLayout, _resolve_destination, @@ -190,7 +190,7 @@ class ThePlatformNamesItsSaveDirectory(unittest.TestCase): self.assertEqual(_bios_tree_below("batocera", "userdata-saves"), "") def test_the_systems_a_core_runs_for(self): - from packpaths import libretro_systems + from packs.paths import libretro_systems config = {"libretro_systems": {"dolphin": ["wii", "gamecube"], "fbalpha": ["fbneo"], "fbalpha2012": ["cps3", "fbneo"]}} @@ -276,7 +276,7 @@ class _Fixture(unittest.TestCase): return load_emulator_profiles(str(self.emulators)) def pack(self, name: str) -> list[str]: - from generate_pack import generate_pack + from packs.platformpack import generate_pack out = self.root / f"out-{name}" out.mkdir() @@ -289,7 +289,7 @@ class _Fixture(unittest.TestCase): return sorted(zf.namelist()) def manifest(self, name: str) -> dict: - from generate_pack import generate_manifest + from packs.manifest import generate_manifest return generate_manifest( name, str(self.platforms), self.db, str(self.bios), @@ -298,7 +298,7 @@ class _Fixture(unittest.TestCase): ) def verify(self, name: str) -> dict: - from verify import verify_platform + from packs.coverage import verify_platform return verify_platform(self.config(name), self.db, str(self.emulators)) @@ -307,7 +307,7 @@ class ThePackPlacesThemInTheSaveFolder(_Fixture): SAVED = "saves/CoreX/CoreX/sysdata/keys.txt" def test_the_report_marks_the_entry(self): - from verify import find_undeclared_files + from packs.gaps import find_undeclared_files report = find_undeclared_files( self.config("testra"), str(self.emulators), self.db, self.profiles() @@ -360,8 +360,9 @@ class ThePackPlacesThemInTheSaveFolder(_Fixture): self.assertFalse(any(p.startswith("saves/") for p in report["pack_destinations"])) def test_the_emulator_pack_and_verify_emulator_agree(self): - from generate_pack import PackRecord, generate_emulator_pack - from verify import verify_emulator + from packs.archive import PackRecord + from packs.emulatorpack import generate_emulator_pack + from packs.emulatorcheck import verify_emulator record = PackRecord() generate_emulator_pack( diff --git a/tests/test_site_availability.py b/tests/test_site_availability.py index 583084182..acc7aab8c 100644 --- a/tests/test_site_availability.py +++ b/tests/test_site_availability.py @@ -75,7 +75,7 @@ class AHeldEntrySaysWhere(unittest.TestCase): import zipfile import generate_site - from cross_reference import FileConsumers, held_copy + from packs.crossref import FileConsumers, held_copy with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: data, bios = Path(tmp) / "data", Path(tmp) / "bios" diff --git a/tests/test_site_entry.py b/tests/test_site_entry.py index 4811dbf4e..0e5206f6d 100644 --- a/tests/test_site_entry.py +++ b/tests/test_site_entry.py @@ -471,7 +471,7 @@ class PackNamesItsVersion(unittest.TestCase): def test_a_version_with_an_underscore_is_read_whole(self): """AmberELEC's prerelease-20261019_1835 read as 1835, and the page said the pack was built for another version.""" - from generate_pack import _platform_pack_stem + from packs.naming import _platform_pack_stem version = load_platform_config("amberelec", "platforms")["version"] name = _platform_pack_stem(["amberelec"], "amberelec", "platforms") + "_BIOS_Pack.zip" diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py index f66f648c2..6ba1e6ad7 100644 --- a/tests/test_site_exports.py +++ b/tests/test_site_exports.py @@ -679,7 +679,7 @@ class AHashFindsEveryPageThatNamesIt(unittest.TestCase): import generate_site from model.platforms import load_platform_config - from cross_reference import FileConsumers + from packs.crossref import FileConsumers from core.ziptools import build_zip_contents_index root = Path(__file__).resolve().parents[1] @@ -912,7 +912,7 @@ class AFileHasAnAddressByContent(unittest.TestCase): / "site.ts").read_text() self.assertIn("api/v1/lookup/", script) self.assertIn("params.has('sha1')", script) - from cross_reference import FileConsumers + from packs.crossref import FileConsumers card = "\n".join(generate_site._system_file_card( {"name": "x.rom", "sha1": "ab" * 20, "size": 1}, FileConsumers({"files": {}}), @@ -928,7 +928,7 @@ class ACardNamesThePacksThatInstallIt(unittest.TestCase): def test_a_manifest_destination_reaches_the_card(self): import json as _json - from cross_reference import FileConsumers + from packs.crossref import FileConsumers from generate_site import _installed_places with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as tmp: @@ -1166,7 +1166,7 @@ class TheOneLinerIsWhereUsersLand(unittest.TestCase): def test_platform_and_system_pages(self): import generate_site - from cross_reference import FileConsumers + from packs.crossref import FileConsumers cov = {"platform": "Batocera", "mode": "md5", "present": 0, "total": 0, "verified": 0, "missing": 0, "details": [], "config": {"systems": {}}} @@ -1249,7 +1249,7 @@ class EveryPageLinksItsOwnData(unittest.TestCase): def test_platform_and_system_documents(self): import generate_site - from cross_reference import FileConsumers + from packs.crossref import FileConsumers cov = {"platform": "Batocera", "mode": "md5", "present": 0, "total": 0, "verified": 0, "missing": 0, "details": [], "config": {"systems": {}}} diff --git a/tests/test_site_reference.py b/tests/test_site_reference.py index f982cb3a1..7e5e07452 100644 --- a/tests/test_site_reference.py +++ b/tests/test_site_reference.py @@ -446,7 +446,7 @@ def _built(path: Path) -> Path: def _verify_status(entry: dict, path: Path, mode: str) -> str: """What verify.py says of one entry, the platform's native logic.""" - from verify import verify_entry_existence, verify_entry_md5, verify_entry_sha1 + from packs.verdicts import verify_entry_existence, verify_entry_md5, verify_entry_sha1 local = str(path) if path.is_file() else None if mode == "existence": @@ -1024,7 +1024,7 @@ class TheFolderCheckReadsEmuDecksWhitelist(unittest.TestCase): (api / "emudeck.json").write_text(json.dumps({"items": [{"contract": contract}]})) found = check_platform_folder.check("emudeck", root, api.as_uri() + "/") # The verifier's verdict on the matching entry, file by file. - from verify import verify_entry_md5 + from packs.verdicts import verify_entry_md5 verdicts = {name: verify_entry_md5(contract["systems"]["sony-playstation"]["files"][0], str(root / name))["status"] diff --git a/tests/test_site_render.py b/tests/test_site_render.py index a859be437..ec48f124b 100644 --- a/tests/test_site_render.py +++ b/tests/test_site_render.py @@ -173,7 +173,7 @@ class FileCardsLinkTheReadingEntry(unittest.TestCase): """The platform links landed on their section, the emulator links on the top of a page of a hundred entries.""" import generate_site - from cross_reference import FileConsumers + from packs.crossref import FileConsumers consumers = FileConsumers({"files": {}}) files = [{"name": "scph1001.bin"}, {"name": "scph5501.bin"}, @@ -202,7 +202,7 @@ class DirectoryMembersNameTheirEmulator(unittest.TestCase): 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 + from packs.crossref import FileConsumers cls.db = load_database(str(REPO_ROOT / "database.json")) if cls.SHA1 not in cls.db.get("files", {}): @@ -399,7 +399,7 @@ class TheSearchLandsOnTheCard(unittest.TestCase): def test_a_system_card_is_a_heading_with_its_anchor(self): import generate_site - from cross_reference import FileConsumers + from packs.crossref import FileConsumers entry = {"name": "a.bin", "sha1": "a" * 40, "md5": "b" * 32, "size": 3} lines = generate_site._system_file_card(entry, FileConsumers({"files": {}})) @@ -415,7 +415,7 @@ class TheSearchSkipsLinkLists(unittest.TestCase): def test_a_system_card_keeps_its_name_and_skips_its_body(self): import generate_site - from cross_reference import FileConsumers + from packs.crossref import FileConsumers consumers = FileConsumers({"files": {}}) sha1 = "a" * 40 @@ -436,7 +436,7 @@ class TheSearchSkipsLinkLists(unittest.TestCase): def test_a_game_data_card_skips_its_name_too(self): import generate_site - from cross_reference import FileConsumers + from packs.crossref import FileConsumers entry = {"name": "0.ogg", "sha1": "a" * 40, "size": 3} lines = generate_site._system_file_card( @@ -509,7 +509,7 @@ class AMemberIsReadInItsArchive(unittest.TestCase): import generate_site as gs from resolve.archives import archive_entry from resolve.localfile import resolve_local_file - from cross_reference import FileConsumers + from packs.crossref import FileConsumers db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8")) profile = yaml.safe_load((REPO_ROOT / "emulators" / "fbneo.yml").read_text(encoding="utf-8")) diff --git a/tests/test_site_system_links.py b/tests/test_site_system_links.py index e60c36367..a14f0a9dd 100644 --- a/tests/test_site_system_links.py +++ b/tests/test_site_system_links.py @@ -140,7 +140,7 @@ class AnIdNamesOneCardPerPage(unittest.TestCase): the same id, and the deployed site refused 20 pages.""" def test_the_second_card_has_no_id(self): - from cross_reference import FileConsumers + from packs.crossref import FileConsumers entry = {"name": "a.bin", "sha1": "a" * 40, "md5": "b" * 32, "size": 3, "path": "bios/Nintendo/DS/a.bin"} diff --git a/tests/test_site_systems.py b/tests/test_site_systems.py index 415d34c45..a44eb1ea2 100644 --- a/tests/test_site_systems.py +++ b/tests/test_site_systems.py @@ -42,7 +42,7 @@ import json import generate_site as gs import siterender -from cross_reference import FileConsumers +from packs.crossref import FileConsumers import make_og_cards from sitestarlight import toc_slug @@ -1256,7 +1256,7 @@ class EachFileDownloadsFromItsCard(unittest.TestCase): fourth of a card's facts.""" def test_the_card_title_holds_the_download(self) -> None: - from cross_reference import FileConsumers + from packs.crossref import FileConsumers f = _naomi_file("apple2-asoft-auto.rom", "3", "bios/Apple/Apple II/apple2-asoft-auto.rom") title = next(line for line in gs._system_file_card(f, FileConsumers({"files": {}})) diff --git a/tests/test_site_wanted.py b/tests/test_site_wanted.py index 678b50e5c..f81e1ef38 100644 --- a/tests/test_site_wanted.py +++ b/tests/test_site_wanted.py @@ -26,7 +26,7 @@ from pathlib import Path import generate_site import sitewanted -import validate_pr +from resolve import review import yaml from model.database import load_database from tests.test_site_pronouns import pronouns @@ -157,7 +157,7 @@ class _World(unittest.TestCase): ]}] self.platform_hashes = {"sha1": set(), "md5": set(), "names": set(), "folders": {}, "named": {}} - self.profile_hashes = validate_pr.load_profile_hashes(str(emulators), self.db) + self.profile_hashes = review.load_profile_hashes(str(emulators), self.db) self.placer = sitewanted.Placer(self.db, self.platform_hashes, self.profile_hashes) self.data = sitewanted.build_wanted( self.profiles, self.coverages, self.gap_report, self.db, self.placer, @@ -392,7 +392,7 @@ class EveryFolderIsTheReviewsFolder(_World): path = self.tmp / "card" / name path.parent.mkdir(exist_ok=True) path.write_bytes(data) - result = validate_pr.validate_file( + result = review.validate_file( f"card/{name}", self.db, platform_hashes, self.profile_hashes) entry = self.entry(name) folder = self.data["folders"][entry["f"]] @@ -406,7 +406,7 @@ class EveryFolderIsTheReviewsFolder(_World): for entry in self.data["entries"]: values = [v for algo in ("sha1", "md5", "sha256") for v in entry.get("h", {}).get(algo, []) if len(v) == sitewanted.FULL_LENGTH[algo]] - spot = validate_pr.placement(values, entry["n"], self.db, self.platform_hashes, + spot = review.placement(values, entry["n"], self.db, self.platform_hashes, self.profile_hashes, declared="h" in entry, exists=self.placer.paths.__contains__, systems=["x"]) @@ -420,11 +420,11 @@ class EveryFolderIsTheReviewsFolder(_World): """nohash.bin is held only in bios/Other/Elsewhere/, a folder no file of system x is in: the folder comes from system x.""" self.assertEqual(self.data["folders"][self.entry("nohash.bin")["f"]], "bios/Maker/Console/") - spot = validate_pr.placement([], "nohash.bin", self.db, self.platform_hashes, + spot = review.placement([], "nohash.bin", self.db, self.platform_hashes, self.profile_hashes, declared=False, systems=["x"]) self.assertEqual(spot.folder, "bios/Maker/Console/") # The review, given the name alone, reads the systems that declare it. - self.assertEqual(validate_pr.placement([], "nohash.bin", self.db, self.platform_hashes, + self.assertEqual(review.placement([], "nohash.bin", self.db, self.platform_hashes, self.profile_hashes, declared=False).folder, "bios/Maker/Console/") @@ -432,13 +432,13 @@ class EveryFolderIsTheReviewsFolder(_World): folder = self.data["folders"][self.entry("nohash.bin")["f"]] path = self.tmp / folder / "nohash.bin" path.write_bytes(b"a copy of the wanted file") - result = validate_pr.validate_file(f"{folder}nohash.bin", self.db, self.platform_hashes, + result = review.validate_file(f"{folder}nohash.bin", self.db, self.platform_hashes, self.profile_hashes) self.assertFalse([m for kind, m in result.checks if kind == "WARN" and m.startswith("Placed under")]) self.assertIn(("PASS", "Correct placement: bios/Maker/Console/"), result.checks) def test_a_declared_directory_names_its_folder(self): - spot = validate_pr.placement([], "v.bin", self.db, self.platform_hashes, self.profile_hashes, + spot = review.placement([], "v.bin", self.db, self.platform_hashes, self.profile_hashes, declared=False, directory="system/Maker/Console/") self.assertEqual(spot.folder, "bios/Maker/Console/") @@ -517,9 +517,9 @@ class ThePageReadsTheListAsTheResolverDoes(_World): self.assertEqual(out, [["nohash.bin"], [], []]) def test_the_issue_form_is_filled_as_the_review_fills_it(self): - result = validate_pr.ValidationResult("b.bin") + result = review.ValidationResult("b.bin") result.sha1, result.md5, result.size = sha1(WANTED), md5(WANTED), len(WANTED) - self.assertEqual(self._page(WANTED, "b.bin")["issue"], validate_pr.large_file_issue_url(result)) + self.assertEqual(self._page(WANTED, "b.bin")["issue"], review.large_file_issue_url(result)) class TheTwoPagesLinkEachOther(unittest.TestCase): @@ -583,11 +583,11 @@ class AFolderComesFromTheSystem(unittest.TestCase): if not (REPO_ROOT / "database.json").is_file(): raise unittest.SkipTest("no database") cls.db = load_database(str(REPO_ROOT / "database.json")) - cls.platform_hashes = validate_pr.load_platform_hashes(str(REPO_ROOT / "platforms"), cls.db) - cls.profile_hashes = validate_pr.load_profile_hashes(str(REPO_ROOT / "emulators"), cls.db) + cls.platform_hashes = review.load_platform_hashes(str(REPO_ROOT / "platforms"), cls.db) + cls.profile_hashes = review.load_profile_hashes(str(REPO_ROOT / "emulators"), cls.db) - def place(self, systems: list[str], directory: str) -> validate_pr.Placement: - return validate_pr.placement([], "config.ini", self.db, self.platform_hashes, + def place(self, systems: list[str], directory: str) -> review.Placement: + return review.placement([], "config.ini", self.db, self.platform_hashes, self.profile_hashes, declared=False, systems=systems, directory=directory) @@ -632,15 +632,15 @@ class ThePublishedList(unittest.TestCase): def test_every_folder_is_the_reviews(self): placer = sitewanted.Placer( - self.db, validate_pr.load_platform_hashes(str(REPO_ROOT / "platforms"), self.db), - validate_pr.load_profile_hashes(str(REPO_ROOT / "emulators"), self.db)) + self.db, review.load_platform_hashes(str(REPO_ROOT / "platforms"), self.db), + review.load_profile_hashes(str(REPO_ROOT / "emulators"), self.db)) # An entry placed by its hashes. The others take their folder from # their system and directory, which the list does not carry: the # synthetic world above holds them to the rule. for entry in self.data["entries"]: values = [v for algo in ("sha1", "md5", "sha256") for v in entry.get("h", {}).get(algo, []) if len(v) == sitewanted.FULL_LENGTH[algo]] - if not validate_pr.expected_folders(values, placer.platform_hashes, placer.profile_hashes): + if not review.expected_folders(values, placer.platform_hashes, placer.profile_hashes): continue spot = placer.place(entry.get("h", {}), entry["n"]) with self.subTest(entry=entry["n"]): diff --git a/tests/test_site_weight.py b/tests/test_site_weight.py index 027a6a5af..fc1e848d4 100644 --- a/tests/test_site_weight.py +++ b/tests/test_site_weight.py @@ -17,7 +17,7 @@ import generate_site import sitestarlight import siterender import sitemarkup as markup -from cross_reference import FileConsumers +from packs.crossref import FileConsumers def _file(name: str, index: int, console: str, maker: str = "Maker") -> dict: diff --git a/tests/test_slots.py b/tests/test_slots.py index 98943a7b3..0d04a4a20 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -13,7 +13,10 @@ import unittest from pathlib import Path import slots -from slots import Claim, Conflict, arbitrate, format_decision +from packs import slots as packs_slots +from resolve import collisions as resolve_collisions +from packs.slots import Claim, Conflict, arbitrate +from slots import format_decision def _db(entries: dict[str, dict]) -> dict: @@ -108,7 +111,7 @@ class TestConflicts(unittest.TestCase): {"name": "IPL.bin", "destination": "bios/GC/JAP/IPL.bin", "md5": "m" * 32}, {"name": "other.bin", "destination": "bios/other.bin"}, ]}}} - conflicts = slots.find_conflicts(config, self._profile("GC/JAP/IPL.bin"), REGIONS_DB) + conflicts = packs_slots.find_conflicts(config, self._profile("GC/JAP/IPL.bin"), REGIONS_DB) self.assertEqual([c.destination for c in conflicts], ["bios/GC/JAP/IPL.bin"]) def test_a_core_found_by_content_takes_any_dump_it_accepts(self): @@ -120,11 +123,11 @@ class TestConflicts(unittest.TestCase): "region": ["japan"]}, {"name": "IPL_alt.bin", "md5": "m" * 32, "region": ["japan"]}, ] - by_name = slots.find_conflicts( + by_name = packs_slots.find_conflicts( self._config("m" * 32), {"dolphin": {"files": files}}, REGIONS_DB ) self.assertEqual(len(by_name), 1) - by_content = slots.find_conflicts( + by_content = packs_slots.find_conflicts( self._config("m" * 32), {"dolphin": {"found_by": "content", "files": files}}, REGIONS_DB, @@ -133,7 +136,7 @@ class TestConflicts(unittest.TestCase): # Another region is another slot: openMSX finds each ROM by sha1 too, # and one machine's ROM never stands for another's. files[1]["region"] = ["north-america"] - other_slot = slots.find_conflicts( + other_slot = packs_slots.find_conflicts( self._config("m" * 32), {"dolphin": {"found_by": "content", "files": files}}, REGIONS_DB, @@ -141,7 +144,7 @@ class TestConflicts(unittest.TestCase): self.assertEqual(len(other_slot), 1) def test_wrong_region_under_a_region_slot_is_reported(self): - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config("m" * 32), self._profile("GC/JAP/IPL.bin"), REGIONS_DB ) self.assertEqual(len(conflicts), 1) @@ -153,7 +156,7 @@ class TestConflicts(unittest.TestCase): self.assertEqual(conflicts[0].emulators, ["dolphin"]) def test_agreement_is_not_a_conflict(self): - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config("n" * 32), self._profile("GC/JAP/IPL.bin"), REGIONS_DB ) self.assertEqual(conflicts, []) @@ -169,14 +172,14 @@ class TestConflicts(unittest.TestCase): ] } } - conflicts = slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) + conflicts = packs_slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) self.assertEqual(conflicts, []) def test_a_platform_list_naming_the_profile_file_is_agreement(self): """Recalbox names both scph1001.bin revisions. The resolver stops on the first, the profile pins the other, and --strict reported a contradiction nobody has to correct.""" - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config(f"{'m' * 32},{'n' * 32}"), self._profile("GC/JAP/IPL.bin"), REGIONS_DB, @@ -195,7 +198,7 @@ class TestConflicts(unittest.TestCase): ] } } - conflicts = slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) + conflicts = packs_slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) self.assertEqual(conflicts, []) def test_an_entry_the_pack_never_carries_claims_nothing(self): @@ -209,7 +212,7 @@ class TestConflicts(unittest.TestCase): ] } } - conflicts = slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) + conflicts = packs_slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) self.assertEqual(conflicts, []) def test_a_name_only_resolution_asserts_nothing(self): @@ -223,7 +226,7 @@ class TestConflicts(unittest.TestCase): } } profile = {"dolphin": {"files": [{"name": "IPL.bin", "path": "slot/IPL.bin"}]}} - self.assertEqual(slots.find_conflicts(config, profile, REGIONS_DB), []) + self.assertEqual(packs_slots.find_conflicts(config, profile, REGIONS_DB), []) def test_a_bare_sibling_met_first_does_not_hide_the_contradiction(self): """RetroArch declares dsi_bios7.bin bare under one system and with a @@ -236,7 +239,7 @@ class TestConflicts(unittest.TestCase): {"name": "IPL.bin", "destination": "GC/JAP/IPL.bin", "md5": "m" * 32}]}, } } - conflicts = slots.find_conflicts(config, self._profile("GC/JAP/IPL.bin"), REGIONS_DB) + conflicts = packs_slots.find_conflicts(config, self._profile("GC/JAP/IPL.bin"), REGIONS_DB) self.assertEqual([c.destination for c in conflicts], ["GC/JAP/IPL.bin"]) def test_launchers_and_aliases_never_claim(self): @@ -247,7 +250,7 @@ class TestConflicts(unittest.TestCase): } } self.assertEqual( - slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB), [] + packs_slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB), [] ) def test_the_arbitration_reads_the_same_evidence_as_the_builder(self): @@ -264,17 +267,17 @@ class TestConflicts(unittest.TestCase): import verify for function in ( - slots.platform_claims, - slots.profile_claims, - slots.find_conflicts, - slots.find_collisions, + packs_slots.platform_claims, + packs_slots.profile_claims, + packs_slots.find_conflicts, + resolve_collisions.find_collisions, ): parameters = inspect.signature(function).parameters with self.subTest(function=function.__name__): self.assertIn("zip_contents", parameters) self.assertIn("data_dir_registry", parameters) - parameters = inspect.signature(slots.pack_overrides).parameters + parameters = inspect.signature(packs_slots.pack_overrides).parameters self.assertIn("zip_contents", parameters) self.assertIn("data_dir_registry", parameters) @@ -310,9 +313,9 @@ class TestConflicts(unittest.TestCase): } } self.assertEqual( - slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB), [] + packs_slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB), [] ) - self.assertEqual(slots.profile_claims(profile, REGIONS_DB), []) + self.assertEqual(packs_slots.profile_claims(profile, REGIONS_DB), []) def test_a_filename_agnostic_profile_claims_nothing(self): """The gap report skips a `bios_mode: agnostic` profile whole: the @@ -320,16 +323,16 @@ class TestConflicts(unittest.TestCase): ARMSX2's GameIndex.yaml replaced the one RetroArch declares.""" profile = self._profile("GC/JAP/IPL.bin") self.assertTrue( - slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) + packs_slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB) ) profile["dolphin"]["bios_mode"] = "agnostic" - self.assertEqual(slots.profile_claims(profile, REGIONS_DB), []) + self.assertEqual(packs_slots.profile_claims(profile, REGIONS_DB), []) self.assertEqual( - slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB), [] + packs_slots.find_conflicts(self._config("m" * 32), profile, REGIONS_DB), [] ) def test_base_destination_prefixes_both_sides(self): - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config("m" * 32), self._profile("GC/JAP/IPL.bin"), REGIONS_DB, @@ -338,7 +341,7 @@ class TestConflicts(unittest.TestCase): self.assertEqual(conflicts[0].destination, "bios/GC/JAP/IPL.bin") def test_report_line_names_both_answers(self): - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config("m" * 32), self._profile("GC/JAP/IPL.bin"), REGIONS_DB ) line = slots.format_conflict(conflicts[0]) @@ -351,33 +354,33 @@ class TestArbitration(unittest.TestCase): """A pack answers to whoever asked for it, and serves both when it can.""" def _conflict(self): - platform = slots.Claim( + platform = packs_slots.Claim( "platform", "GC/JAP/IPL.bin", "IPL.bin", entry={"md5": "m" * 32, "sha1": "a" * 40}, local_path="bios/Console/GC/USA/IPL.bin", status="md5_exact", ) - profile = slots.Claim( + profile = packs_slots.Claim( "profile", "GC/JAP/IPL.bin", "IPL.bin", emulator="dolphin", local_path="bios/Console/GC/JAP/IPL.bin", status="path_exact", ) - return slots.Conflict("GC/JAP/IPL.bin", platform, [profile]) + return packs_slots.Conflict("GC/JAP/IPL.bin", platform, [profile]) def test_existence_mode_serves_both(self): - decision = slots.arbitrate(self._conflict(), "existence") + decision = packs_slots.arbitrate(self._conflict(), "existence") self.assertEqual(decision.winner.origin, "profile") self.assertTrue(decision.serves_both) def test_md5_mode_keeps_the_frontend_green(self): - decision = slots.arbitrate(self._conflict(), "md5") + decision = packs_slots.arbitrate(self._conflict(), "md5") self.assertEqual(decision.winner.origin, "platform") self.assertFalse(decision.serves_both) def test_sha1_mode_is_content_checking_too(self): - decision = slots.arbitrate(self._conflict(), "sha1") + decision = packs_slots.arbitrate(self._conflict(), "sha1") self.assertEqual(decision.winner.origin, "platform") def test_an_emulator_pack_answers_to_the_emulator(self): - decision = slots.arbitrate(self._conflict(), "md5", addressee="emulator") + decision = packs_slots.arbitrate(self._conflict(), "md5", addressee="emulator") self.assertEqual(decision.winner.origin, "profile") self.assertFalse(decision.serves_both) @@ -389,14 +392,14 @@ class TestArbitration(unittest.TestCase): conflict.platform_claim.entry = {"name": "IPL.bin"} for mode in ("md5", "sha1"): with self.subTest(mode=mode): - self.assertTrue(slots.arbitrate(conflict, mode).serves_both) + self.assertTrue(packs_slots.arbitrate(conflict, mode).serves_both) # RomM compares size then any hash: a hash of another kind is content. conflict.platform_claim.entry = {"name": "IPL.bin", "sha1": "a" * 40, "size": 3} self.assertFalse( - slots.arbitrate(conflict, "md5", rule="size_and_any_hash").serves_both + packs_slots.arbitrate(conflict, "md5", rule="size_and_any_hash").serves_both ) conflict.platform_claim.entry = {"name": "x.zip", "zipped_file": "IPL.bin"} - self.assertFalse(slots.arbitrate(conflict, "md5").serves_both) + self.assertFalse(packs_slots.arbitrate(conflict, "md5").serves_both) def test_the_pack_serves_the_proven_file_at_a_hashless_md5_entry(self): config = { @@ -411,7 +414,7 @@ class TestArbitration(unittest.TestCase): {"name": "IPL.bin", "md5": "n" * 32}, {"name": "IPL.bin", "path": "hashed/IPL.bin", "md5": "n" * 32}, ]}} - overrides = slots.pack_overrides(config, profiles, REGIONS_DB) + overrides = packs_slots.pack_overrides(config, profiles, REGIONS_DB) # The hashed declaration keeps the file the frontend checks. self.assertEqual(overrides, {"IPL.bin": "bios/Console/GC/JAP/IPL.bin"}) @@ -430,20 +433,20 @@ class TestArbitration(unittest.TestCase): {"name": "IPL.bin", "path": "GC/JAP/IPL.bin"}, ]}} with self.subTest(mode=mode): - [conflict] = slots.find_conflicts(config, profiles, REGIONS_DB) - decision = slots.arbitrate(conflict, mode) - served = slots.pack_overrides(config, profiles, REGIONS_DB).get( + [conflict] = packs_slots.find_conflicts(config, profiles, REGIONS_DB) + decision = packs_slots.arbitrate(conflict, mode) + served = packs_slots.pack_overrides(config, profiles, REGIONS_DB).get( "GC/JAP/IPL.bin", conflict.platform_claim.local_path ) self.assertEqual(served, decision.winner.local_path) def test_the_reported_line_gives_the_ground_for_the_decision(self): - kept = slots.format_decision(slots.arbitrate(self._conflict(), "md5")) + kept = slots.format_decision(packs_slots.arbitrate(self._conflict(), "md5")) self.assertIn("verifies content", kept) # A fact about each layer, no verdict on the platform's list. self.assertIn("the file dolphin reads", kept) self.assertNotIn("wrong", slots.__loader__.get_source("slots").lower()) - served = slots.format_decision(slots.arbitrate(self._conflict(), "existence")) + served = slots.format_decision(packs_slots.arbitrate(self._conflict(), "existence")) self.assertIn("both are satisfied", served) def test_each_emulator_is_given_the_file_it_reads(self): @@ -451,12 +454,12 @@ class TestArbitration(unittest.TestCase): reads, while geolith pins another one.""" conflict = self._conflict() conflict.profile_claims = [ - slots.Claim("profile", "neocdz.zip", "neocdz.zip", emulator="fbneo", + packs_slots.Claim("profile", "neocdz.zip", "neocdz.zip", emulator="fbneo", local_path="a/neocdz.zip.ba20a7be", status="members_held"), - slots.Claim("profile", "neocdz.zip", "neocdz.zip", emulator="geolith", + packs_slots.Claim("profile", "neocdz.zip", "neocdz.zip", emulator="geolith", local_path="b/neocdz.zip.712816a3", status="md5_exact"), ] - kept = slots.format_decision(slots.arbitrate(conflict, "md5")) + kept = slots.format_decision(packs_slots.arbitrate(conflict, "md5")) self.assertIn("a/neocdz.zip.ba20a7be, the file fbneo reads", kept) self.assertIn("b/neocdz.zip.712816a3, the file geolith reads", kept) self.assertEqual(conflict.files_read(), [ @@ -471,7 +474,7 @@ class TheStrongestProofTakesAnUndeclaredPath(unittest.TestCase): path, whatever the proof, and mame2015 received another revision.""" def test_a_held_hash_beats_a_bare_name_whatever_the_order(self): - from packextras import _collect_emulator_extras + from packs.extras import _collect_emulator_extras config = { "platform": "P", "verification_mode": "existence", @@ -534,7 +537,7 @@ class TestSelfContradictingDestinations(unittest.TestCase): {"name": "IPL.bin", "destination": "disk.rom", "md5": "m" * 32}, {"name": "IPL.bin", "destination": "disk.rom", "md5": "n" * 32}, ) - collisions = slots.find_collisions(config, REGIONS_DB) + collisions = resolve_collisions.find_collisions(config, REGIONS_DB) self.assertEqual(len(collisions), 1) self.assertEqual(len(collisions[0].resolved), 2) @@ -547,7 +550,7 @@ class TestSelfContradictingDestinations(unittest.TestCase): "alpha": {"files": [{"name": "IPL.bin", "destination": "disk.rom", "md5": "n" * 32}]}, }} - collision = slots.find_collisions(config, REGIONS_DB)[0] + collision = resolve_collisions.find_collisions(config, REGIONS_DB)[0] line = slots.format_collision(collision) left, packed = collision.resolved # The builder walks the systems sorted: alpha's declaration ships. @@ -563,7 +566,7 @@ class TestSelfContradictingDestinations(unittest.TestCase): {"name": "IPL.bin", "destination": "a.zip", "md5": "m" * 32, "zipped_file": "two.bin"}, ) - self.assertEqual(slots.find_collisions(config, REGIONS_DB), []) + self.assertEqual(resolve_collisions.find_collisions(config, REGIONS_DB), []) def test_a_file_both_declarations_accept_settles_the_path(self): """RetroDECK: ATARIOSB.ROM under one system with one md5, under @@ -574,11 +577,11 @@ class TestSelfContradictingDestinations(unittest.TestCase): {"name": "IPL.bin", "destination": "disk.rom", "md5": f"{'n' * 32},{'m' * 32}"}, ) - self.assertEqual(slots.find_collisions(config, REGIONS_DB), []) + self.assertEqual(resolve_collisions.find_collisions(config, REGIONS_DB), []) def test_a_primary_and_its_pinned_variant_are_one_family(self): self.assertTrue( - slots._same_file_family( + resolve_collisions._same_file_family( ["bios/M/C/rom.zip", "bios/M/C/.variants/rom.zip.abcd1234"] ) ) @@ -586,14 +589,14 @@ class TestSelfContradictingDestinations(unittest.TestCase): def test_a_variant_kept_under_its_plain_name_is_one_family(self): # 63 variants carry no hash suffix, aes.zip among them. self.assertTrue( - slots._same_file_family( + resolve_collisions._same_file_family( ["bios/SNK/Neo Geo/aes.zip", "bios/SNK/Neo Geo/.variants/aes.zip"] ) ) def test_only_a_hash_suffix_is_stripped(self): self.assertFalse( - slots._same_file_family( + resolve_collisions._same_file_family( ["bios/M/C/rom.zip", "bios/M/C/.variants/rom.zip.zip"] ) ) @@ -611,7 +614,7 @@ class TestSelfContradictingDestinations(unittest.TestCase): def test_two_machines_are_not_one_family(self): self.assertFalse( - slots._same_file_family( + resolve_collisions._same_file_family( ["bios/Microsoft/MSX/DISK.ROM", "bios/Tandy/CoCo/disk.rom"] ) ) @@ -620,14 +623,14 @@ class TestSelfContradictingDestinations(unittest.TestCase): config = self._config( {"name": "IPL.bin", "destination": "disk.rom", "md5": "m" * 32} ) - self.assertEqual(slots.find_collisions(config, REGIONS_DB), []) + self.assertEqual(resolve_collisions.find_collisions(config, REGIONS_DB), []) def test_the_line_names_every_file_claiming_the_path(self): config = self._config( {"name": "IPL.bin", "destination": "disk.rom", "md5": "m" * 32}, {"name": "IPL.bin", "destination": "disk.rom", "md5": "n" * 32}, ) - line = slots.format_collision(slots.find_collisions(config, REGIONS_DB)[0]) + line = slots.format_collision(resolve_collisions.find_collisions(config, REGIONS_DB)[0]) self.assertIn("USA/IPL.bin", line) self.assertIn("JAP/IPL.bin", line) @@ -660,13 +663,13 @@ class TestBuildModeDecidesWhoClaims(unittest.TestCase): "files": [entry]}} def test_a_standalone_only_file_does_not_claim_a_core_slot(self): - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config(), self._profile(mode="standalone"), REGIONS_DB ) self.assertEqual(conflicts, []) def test_it_claims_when_the_platform_runs_that_emulator_standalone(self): - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config(standalone=["ares"]), self._profile(mode="standalone"), REGIONS_DB, @@ -675,7 +678,7 @@ class TestBuildModeDecidesWhoClaims(unittest.TestCase): self.assertEqual(len(conflicts), 1) def test_a_libretro_only_file_is_silent_in_standalone_mode(self): - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config(standalone=["ares"]), self._profile(mode="libretro"), REGIONS_DB, @@ -684,7 +687,7 @@ class TestBuildModeDecidesWhoClaims(unittest.TestCase): self.assertEqual(conflicts, []) def test_standalone_mode_reads_the_standalone_destination(self): - claims = slots.profile_claims( + claims = packs_slots.profile_claims( self._profile(standalone_path="elsewhere/IPL.bin"), REGIONS_DB, standalone_cores={"ares"}, @@ -697,7 +700,7 @@ class TestBuildModeDecidesWhoClaims(unittest.TestCase): "files": [{"name": "IPL.bin", "path": "GC/JAP/IPL.bin", "mode": "standalone"}]}} - conflicts = slots.find_conflicts( + conflicts = packs_slots.find_conflicts( self._config(standalone=["ares"]), profile, REGIONS_DB, standalone_cores={"ares"}, ) @@ -708,7 +711,7 @@ class TestBuildModeDecidesWhoClaims(unittest.TestCase): "files": [{"name": "IPL.bin", "path": "GC/JAP/IPL.bin", "standalone_path": "elsewhere/IPL.bin"}]}} - claims = slots.profile_claims( + claims = packs_slots.profile_claims( profile, REGIONS_DB, standalone_cores={"ares"} ) self.assertEqual(claims[0].destination, "GC/JAP/IPL.bin") @@ -718,18 +721,18 @@ class TestProvenEvidence(unittest.TestCase): """What counts as proof that a claim is about content, not about a name.""" def test_hash_evidence_is_proof(self): - self.assertTrue(slots.Claim("profile", "d", "n", status="sha1_exact").is_proven) - self.assertTrue(slots.Claim("profile", "d", "n", status="md5_exact").is_proven) + self.assertTrue(packs_slots.Claim("profile", "d", "n", status="sha1_exact").is_proven) + self.assertTrue(packs_slots.Claim("profile", "d", "n", status="md5_exact").is_proven) def test_path_evidence_is_proof(self): # Dolphin declares no checksum for the GameCube boot ROM because its # source declares none, so the path is then the whole assertion. - self.assertTrue(slots.Claim("profile", "d", "n", status="path_exact").is_proven) + self.assertTrue(packs_slots.Claim("profile", "d", "n", status="path_exact").is_proven) def test_a_name_is_not_proof(self): - self.assertFalse(slots.Claim("profile", "d", "n", status="name_exact").is_proven) + self.assertFalse(packs_slots.Claim("profile", "d", "n", status="name_exact").is_proven) self.assertFalse( - slots.Claim("profile", "d", "n", status="hash_mismatch").is_proven + packs_slots.Claim("profile", "d", "n", status="hash_mismatch").is_proven ) @@ -752,9 +755,9 @@ class AnExactSizeContestsAnotherSize(unittest.TestCase): def test_a_held_copy_of_the_declared_size_proves_the_claim(self): entry = {"name": "IPLROM.X1T", "size": 32768} - self.assertTrue(slots._size_the_code_reads(entry, str(self.ipl))) - self.assertFalse(slots._size_the_code_reads(entry, str(self.font))) - self.assertTrue(slots.Claim("profile", "d", "n", status=slots.SIZE_EXACT).is_proven) + self.assertTrue(packs_slots._size_the_code_reads(entry, str(self.ipl))) + self.assertFalse(packs_slots._size_the_code_reads(entry, str(self.font))) + self.assertTrue(packs_slots.Claim("profile", "d", "n", status=packs_slots.SIZE_EXACT).is_proven) def test_retroarch_ships_the_turbo_ipl(self): import json as _json @@ -788,7 +791,7 @@ class ManifestFollowsTheArbitration(unittest.TestCase): db = load_database(str(repo / "database.json")) config = load_platform_config("retroarch", str(repo / "platforms")) profiles = load_emulator_profiles(str(repo / "emulators")) - overrides = slots.pack_overrides( + overrides = packs_slots.pack_overrides( config, profiles, db, build_zip_contents_index(db), load_data_dir_registry(str(repo / "platforms")), ) @@ -890,13 +893,13 @@ class AnArchiveIsClaimedByItsMembers(unittest.TestCase): } def test_existence_serves_the_copy_the_core_boots_from(self): - overrides = slots.pack_overrides(self._config("existence", "short"), self.profiles, self.db) + overrides = packs_slots.pack_overrides(self._config("existence", "short"), self.profiles, self.db) self.assertEqual(overrides, {"system/fbneo/neocdz.zip": self.paths["full"][0]}) def test_a_content_check_keeps_the_pin_and_reports_it(self): config = self._config("md5", "short") - self.assertEqual(slots.pack_overrides(config, self.profiles, self.db), {}) - conflicts = slots.find_conflicts(config, self.profiles, self.db, "system") + self.assertEqual(packs_slots.pack_overrides(config, self.profiles, self.db), {}) + conflicts = packs_slots.find_conflicts(config, self.profiles, self.db, "system") self.assertEqual([c.destination for c in conflicts], ["system/fbneo/neocdz.zip"]) def test_a_pin_nobody_holds_yields_where_only_the_path_is_checked(self): @@ -906,29 +909,29 @@ class AnArchiveIsClaimedByItsMembers(unittest.TestCase): config["systems"]["snk-neogeo-cd"]["files"][0].update( destination="neocdz.zip", md5="f" * 32 ) - overrides = slots.pack_overrides(config, self.profiles, self.db) + overrides = packs_slots.pack_overrides(config, self.profiles, self.db) self.assertEqual(overrides, {"system/neocdz.zip": self.paths["full"][0]}) config["verification_mode"] = "md5" - self.assertEqual(slots.find_conflicts(config, self.profiles, self.db, "system"), []) + self.assertEqual(packs_slots.find_conflicts(config, self.profiles, self.db, "system"), []) def test_a_target_without_the_core_keeps_the_pin(self): """DuckStation exists on no RetroArch target and still replaced the scph5000.bin System.dat pins in every --target pack.""" config = self._config("existence", "short") - self.assertTrue(slots.pack_overrides(config, self.profiles, self.db)) + self.assertTrue(packs_slots.pack_overrides(config, self.profiles, self.db)) self.assertEqual( - slots.pack_overrides(config, self.profiles, self.db, target_cores={"other"}), {} + packs_slots.pack_overrides(config, self.profiles, self.db, target_cores={"other"}), {} ) def test_a_baseline_pack_serves_the_baseline(self): config = self._config("existence", "short") self.assertEqual( - slots.pack_overrides(config, self.profiles, self.db, source="platform"), {} + packs_slots.pack_overrides(config, self.profiles, self.db, source="platform"), {} ) def test_a_pin_holding_the_members_is_agreement(self): config = self._config("md5", "full") - self.assertEqual(slots.find_conflicts(config, self.profiles, self.db, "system"), []) + self.assertEqual(packs_slots.find_conflicts(config, self.profiles, self.db, "system"), []) @@ -947,7 +950,7 @@ class ARecordIsFoundByItsPathOnce(unittest.TestCase): """_accepted_by_all walked all 19 000 records for every path asked.""" def test_the_files_are_walked_once(self): - import slots + from resolve import collisions as resolve_collisions class Counted(dict): walks = 0 @@ -959,8 +962,8 @@ class ARecordIsFoundByItsPathOnce(unittest.TestCase): files = Counted({"a" * 40: {"path": "bios/x.bin"}, "b" * 40: {"path": "bios/y.bin"}}) db = {"files": files} for _ in range(50): - self.assertEqual(slots._record_at("bios/y.bin", db)["path"], "bios/y.bin") - self.assertIsNone(slots._record_at("bios/z.bin", db)) + self.assertEqual(resolve_collisions._record_at("bios/y.bin", db)["path"], "bios/y.bin") + self.assertIsNone(resolve_collisions._record_at("bios/z.bin", db)) self.assertEqual(Counted.walks, 1) @@ -986,8 +989,8 @@ class TwoPathsHoldingOneContentAgree(unittest.TestCase): different = Claim("profile", "Machines/MSX2EXT.rom", "MSX2EXT.rom", emulator="bluemsx", local_path=str(other), status="path_exact") - self.assertTrue(slots._satisfies(same, platform, db)) - self.assertFalse(slots._satisfies(different, platform, db)) + self.assertTrue(packs_slots._satisfies(same, platform, db)) + self.assertFalse(packs_slots._satisfies(different, platform, db)) class ACopierHeaderIsNotAnotherImage(unittest.TestCase): @@ -1017,13 +1020,13 @@ class ACopierHeaderIsNotAnotherImage(unittest.TestCase): local_path=str(plain), status="crc32_exact", entry={"name": "syscard3.pce", "crc32": [crc], "size": [1024, 1536]}, ) - self.assertTrue(slots._satisfies(profile, platform, db)) + self.assertTrue(packs_slots._satisfies(profile, platform, db)) one_size = Claim( "profile", "syscard3.pce", "syscard3.pce", emulator="geargrafx", local_path=str(plain), status="crc32_exact", entry={"name": "syscard3.pce", "crc32": [crc], "size": 1024}, ) - self.assertFalse(slots._satisfies(one_size, platform, db)) + self.assertFalse(packs_slots._satisfies(one_size, platform, db)) class TheSlotsSummaryClosesTheRun(unittest.TestCase): diff --git a/tests/test_slots_shipped_file.py b/tests/test_slots_shipped_file.py index b328d9d79..49fafc3d5 100644 --- a/tests/test_slots_shipped_file.py +++ b/tests/test_slots_shipped_file.py @@ -21,7 +21,8 @@ from pathlib import Path from model.database import load_database from model.platforms import load_platform_config -import slots +from packs import slots +from resolve import collisions REPO_ROOT = Path(__file__).resolve().parents[1] @@ -48,7 +49,7 @@ class SlotsReadTheShippedFile(unittest.TestCase): self.assertFalse(config.get("case_insensitive_fs")) listed = { path - for collision in slots.find_collisions(config, db) + for collision in collisions.find_collisions(config, db) for path in collision.resolved } self.assertNotIn(MSX_DISK, listed) @@ -57,7 +58,7 @@ class SlotsReadTheShippedFile(unittest.TestCase): folded["case_insensitive_fs"] = True listed = { path - for collision in slots.find_collisions(folded, db) + for collision in collisions.find_collisions(folded, db) for path in collision.resolved } self.assertIn(MSX_DISK, listed) diff --git a/tests/test_split_extras.py b/tests/test_split_extras.py index ad7a26c5c..78794a98a 100644 --- a/tests/test_split_extras.py +++ b/tests/test_split_extras.py @@ -20,7 +20,9 @@ import yaml 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 +from packs.archive import PackRecord +from packs.platformpack import generate_pack +from packs.bysystem import 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 81dd24e0a..e9a5da330 100644 --- a/tests/test_split_names.py +++ b/tests/test_split_names.py @@ -22,7 +22,7 @@ import yaml 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 +from packs.bysystem import generate_split_packs class SplitPartNames(unittest.TestCase): diff --git a/tests/test_split_pack.py b/tests/test_split_pack.py index 3df9cc69a..6ecb30016 100644 --- a/tests/test_split_pack.py +++ b/tests/test_split_pack.py @@ -27,9 +27,10 @@ import unittest import zipfile from pathlib import Path -import generate_pack as builder +from packs import finalize +from packs import naming from core.artifacts import artifact_lock -import split_pack +from packs import parts as packs_parts REPO_ROOT = Path(__file__).resolve().parent.parent @@ -70,7 +71,7 @@ class SplitFixture(unittest.TestCase): with zipfile.ZipFile(part) as archive: self.assertIsNone(archive.testzip()) for name in archive.namelist(): - if split_pack.is_marker(name): + if packs_parts.is_marker(name): continue self.assertNotIn(name, found, "a file sits in two parts") found[name] = archive.read(name) @@ -79,21 +80,21 @@ class SplitFixture(unittest.TestCase): class PartsAreArchives(SplitFixture): def test_a_pack_under_the_limit_stays_one_file(self): - parts = split_pack.split_pack(self.pack, limit=1 << 20) + parts = packs_parts.split_pack(self.pack, limit=1 << 20) self.assertEqual(parts, [self.pack]) self.assertTrue(self.pack.is_file()) def test_the_parts_extracted_together_are_the_pack(self): - parts = split_pack.split_pack(self.pack, limit=LIMIT) + parts = packs_parts.split_pack(self.pack, limit=LIMIT) self.assertGreater(len(parts), 1) self.assertEqual(self._read(parts), self.members) def test_every_part_fits_the_asset_limit(self): - for part in split_pack.split_pack(self.pack, limit=LIMIT): + for part in packs_parts.split_pack(self.pack, limit=LIMIT): self.assertLess(part.stat().st_size, LIMIT) def test_a_part_name_says_how_many_there_are(self): - parts = split_pack.split_pack(self.pack, limit=LIMIT) + parts = packs_parts.split_pack(self.pack, limit=LIMIT) count = len(parts) self.assertEqual( [part.name for part in parts], @@ -104,23 +105,23 @@ class PartsAreArchives(SplitFixture): ) def test_the_whole_archive_leaves_once_its_parts_are_checked(self): - split_pack.split_pack(self.pack, limit=LIMIT) + packs_parts.split_pack(self.pack, limit=LIMIT) self.assertFalse(self.pack.exists()) def test_the_same_pack_gives_the_same_parts(self): - first = [p.read_bytes() for p in split_pack.split_pack(self.pack, limit=LIMIT)] + first = [p.read_bytes() for p in packs_parts.split_pack(self.pack, limit=LIMIT)] other = self.dist / "again" other.mkdir() again = other / self.pack.name self._build(again, self.members) - second = [p.read_bytes() for p in split_pack.split_pack(again, limit=LIMIT)] + second = [p.read_bytes() for p in packs_parts.split_pack(again, limit=LIMIT)] self.assertEqual(first, second) def test_a_file_no_part_can_hold_is_refused(self): big = self.dist / "Big_BIOS_Pack.zip" self._build(big, {"huge.bin": _payload(1, LIMIT * 2), "small.bin": b"x"}) with self.assertRaises(ValueError): - split_pack.split_pack(big, limit=LIMIT) + packs_parts.split_pack(big, limit=LIMIT) self.assertTrue(big.is_file(), "the pack is kept when it cannot be split") self.assertEqual(sorted(p.name for p in self.dist.glob("Big*")), [big.name]) @@ -133,7 +134,7 @@ class PartsAreArchives(SplitFixture): archive.writestr(info, _payload(3, 3000)) for n in range(4): archive.writestr(f"data{n}.bin", _payload(n, 900)) - parts = split_pack.split_pack(tool, limit=LIMIT) + parts = packs_parts.split_pack(tool, limit=LIMIT) modes = {} for part in parts: with zipfile.ZipFile(part) as archive: @@ -151,13 +152,13 @@ class EachPartNamesItsSiblings(SplitFixture): found = {} for part in parts: with zipfile.ZipFile(part) as archive: - names = [n for n in archive.namelist() if split_pack.is_marker(n)] + names = [n for n in archive.namelist() if packs_parts.is_marker(n)] self.assertEqual(len(names), 1, part.name) found[part.name] = archive.read(names[0]).decode("utf-8") return found def test_every_part_carries_one_marker(self): - parts = split_pack.split_pack(self.pack, limit=LIMIT) + parts = packs_parts.split_pack(self.pack, limit=LIMIT) count = len(parts) for index, part in enumerate(parts, 1): with zipfile.ZipFile(part) as archive: @@ -165,7 +166,7 @@ class EachPartNamesItsSiblings(SplitFixture): archive.namelist()) def test_the_marker_names_the_pack_the_part_and_every_size(self): - parts = split_pack.split_pack(self.pack, limit=LIMIT) + parts = packs_parts.split_pack(self.pack, limit=LIMIT) count = len(parts) for index, (name, text) in enumerate(self._markers(parts).items(), 1): with self.subTest(part=name): @@ -179,7 +180,7 @@ class EachPartNamesItsSiblings(SplitFixture): ) def test_the_parts_still_fit_with_their_markers(self): - for part in split_pack.split_pack(self.pack, limit=LIMIT): + for part in packs_parts.split_pack(self.pack, limit=LIMIT): self.assertLess(part.stat().st_size, LIMIT) def test_a_pack_holding_a_marker_name_is_refused(self): @@ -188,13 +189,13 @@ class EachPartNamesItsSiblings(SplitFixture): self.pack.unlink() self._build(self.pack, members) with self.assertRaises(ValueError): - split_pack.split_pack(self.pack, limit=LIMIT) + packs_parts.split_pack(self.pack, limit=LIMIT) self.assertTrue(self.pack.is_file()) def test_a_marker_is_not_a_part(self): - self.assertTrue(split_pack.is_marker("Demo_BIOS_Pack.part2of3.txt")) - self.assertFalse(split_pack.is_part("Demo_BIOS_Pack.part2of3.txt")) - self.assertFalse(split_pack.is_marker("Demo_BIOS_Pack.part2of3.zip")) + self.assertTrue(packs_parts.is_marker("Demo_BIOS_Pack.part2of3.txt")) + self.assertFalse(packs_parts.is_part("Demo_BIOS_Pack.part2of3.txt")) + self.assertFalse(packs_parts.is_marker("Demo_BIOS_Pack.part2of3.zip")) class SplitHoldsTheDirectory(SplitFixture): @@ -221,15 +222,15 @@ class SplitHoldsTheDirectory(SplitFixture): class PartsAreNotTakenForPacks(SplitFixture): def test_a_part_is_recognised_by_its_name(self): - self.assertTrue(split_pack.is_part("RetroArch_BIOS_Pack.part1of2.zip")) - self.assertFalse(split_pack.is_part("RetroArch_BIOS_Pack.zip")) - self.assertFalse(split_pack.is_part("RetroArch_BIOS_Pack.zip.001")) + self.assertTrue(packs_parts.is_part("RetroArch_BIOS_Pack.part1of2.zip")) + self.assertFalse(packs_parts.is_part("RetroArch_BIOS_Pack.zip")) + self.assertFalse(packs_parts.is_part("RetroArch_BIOS_Pack.zip.001")) def test_pack_verification_skips_the_parts(self): """A part holds half a platform by design: judged as a pack it fails.""" - parts = split_pack.split_pack(self.pack, limit=LIMIT) + parts = packs_parts.split_pack(self.pack, limit=LIMIT) self.assertEqual( - builder._pack_archives(str(self.dist)), [], + naming._pack_archives(str(self.dist)), [], [p.name for p in parts], ) @@ -240,15 +241,15 @@ class PartsAreNotTakenForPacks(SplitFixture): for name in ("RetroBIOS.zip", "RetroBIOS-tools.zip", "RetroBIOS-batocera.zip"): self._build(self.dist / name, {"RetroBIOS.sh": b"#!/bin/sh\n"}) before = {p.name: p.read_bytes() for p in self.dist.glob("RetroBIOS*.zip")} - self.assertEqual(builder._pack_archives(str(self.dist)), [self.pack.name]) + self.assertEqual(naming._pack_archives(str(self.dist)), [self.pack.name]) # A --system platform pack carries its system after the suffix. system = self.dist / "Demo_1.0_BIOS_Pack_Playstation.zip" self._build(system, {"one.bin": b"1"}) - self.assertEqual(builder._pack_archives(str(self.dist)), + self.assertEqual(naming._pack_archives(str(self.dist)), sorted([self.pack.name, system.name])) system.unlink() with contextlib.redirect_stdout(io.StringIO()): - builder.verify_and_finalize_packs(str(self.dist), {"files": {}, "indexes": {}}, + finalize.verify_and_finalize_packs(str(self.dist), {"files": {}, "indexes": {}}, skip_conformance=True) self.assertEqual({p.name: p.read_bytes() for p in self.dist.glob("RetroBIOS*.zip")}, before) @@ -256,7 +257,7 @@ class PartsAreNotTakenForPacks(SplitFixture): def test_the_directory_form_splits_only_what_is_too_large(self): small = self.dist / "Small_BIOS_Pack.zip" self._build(small, {"one.bin": b"1"}) - written = split_pack.split_directory(self.dist, limit=LIMIT) + written = packs_parts.split_directory(self.dist, limit=LIMIT) names = sorted(path.name for path in written) self.assertIn("Small_BIOS_Pack.zip", names) self.assertNotIn("Demo_1.0_BIOS_Pack.zip", names) diff --git a/tests/test_standalone_mode.py b/tests/test_standalone_mode.py index 7cb48baad..cc50784c7 100644 --- a/tests/test_standalone_mode.py +++ b/tests/test_standalone_mode.py @@ -18,7 +18,7 @@ from pathlib import Path import yaml -from cross_reference import cross_reference +from packs.crossref import cross_reference REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_system_ids.py b/tests/test_system_ids.py index 9570e2a3c..40c6eb385 100644 --- a/tests/test_system_ids.py +++ b/tests/test_system_ids.py @@ -16,7 +16,7 @@ from pathlib import Path from model.systems import SYSTEM_ALIASES, _norm_system_id from model.profiles import load_emulator_profiles -from packextras import _names_content, _slug_for +from packs.extras import _names_content, _slug_for REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_system_pack_extras.py b/tests/test_system_pack_extras.py index 698423f51..96545538f 100644 --- a/tests/test_system_pack_extras.py +++ b/tests/test_system_pack_extras.py @@ -31,7 +31,7 @@ class SystemExtras(unittest.TestCase): """One extra stands per destination and the other cores' claims ride on it. Their systems are the file's systems too: narrowed to one of them, pack and installer both keep the file the core reads.""" - from manifestselect import SelectionIndex + from packs.manifestselect import SelectionIndex extras = [{ "name": "floppy.wav", "destination": "mame/samples/floppy.wav", diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index c524bc54f..09f6acdd1 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -25,7 +25,9 @@ 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 packs import archive +from packs import emulatorpack +from packs import md5pack from tests.scratchtree import scratch_checkout, snapshot REPO_ROOT = Path(__file__).resolve().parent.parent @@ -42,9 +44,9 @@ class SpellingsAgree(unittest.TestCase): def test_the_pack_name_normalizes_the_spelling(self): self.assertEqual( - builder._system_display_name("atari_2600"), builder._system_display_name("atari-2600") + emulatorpack._system_display_name("atari_2600"), emulatorpack._system_display_name("atari-2600") ) - self.assertEqual(builder._system_display_name("msxturboR"), builder._system_display_name("msxturbor")) + self.assertEqual(emulatorpack._system_display_name("msxturboR"), emulatorpack._system_display_name("msxturbor")) class TheListingCountsLikeTheSelection(unittest.TestCase): @@ -74,7 +76,7 @@ class StandaloneNeedsAStandaloneBuild(unittest.TestCase): _emulator_profiles_cache.clear() self.addCleanup(_emulator_profiles_cache.clear) db = {"files": {}, "indexes": {"by_md5": {}, "by_crc32": {}, "by_name": {}}} - result = builder.generate_md5_pack( + result = md5pack.generate_md5_pack( [("md5", "d8f1206299c48946e6ec5ef96d014eaa")], db, tmp, tmp, emulator_name="handy", emulators_dir=str(Path(tmp, "emulators")), standalone=True, ) @@ -442,7 +444,7 @@ class ASystemReportCountsTheClaimsThePackCounts(unittest.TestCase): read only the entry's own system.""" def test_a_claim_riding_on_an_entry_selects_it(self): - from packextras import extras_for_systems, report_owned_by_systems + from packs.extras import extras_for_systems, report_owned_by_systems entry = { "name": "taitofx1.zip", "system": "arcade", "systems": ["arcade"], @@ -476,15 +478,15 @@ class VerifyReportsTheRequiredOnlyPack(unittest.TestCase): import contextlib import io - from verify import verify_emulator + from packs.emulatorcheck import verify_emulator db = load_database("database.json") for name in ("beetle_psx", "dolphin", "fbneo", "geolith", "mame"): with self.subTest(emulator=name): - record = builder.PackRecord() + record = archive.PackRecord() with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): - builder.generate_emulator_pack( + emulatorpack.generate_emulator_pack( [name], "emulators", db, "bios", "", offline=True, platforms_dir="platforms", record=record, required_only=True, ) @@ -582,13 +584,14 @@ class EmulatorVerifyReadsNoArchiveItDoesNotNeed(unittest.TestCase): from unittest import mock import verify + from packs import emulatorcheck if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not generated") 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) + result = emulatorcheck.verify_emulator(["handy"], str(REPO_ROOT / "emulators"), db) self.assertTrue(result) @@ -598,15 +601,15 @@ class CoverageWithoutProfilesMatchesTheCli(unittest.TestCase): a neocdz.zip discrepancy the pack and the CLI do not have.""" def test_omitting_profiles_gives_the_same_report(self): - import verify + from packs import coverage if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not generated") 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, + bare = coverage.verify_platform(config, db, emulators) + full = coverage.verify_platform(config, db, emulators, load_emulator_profiles(emulators)) def discrepancies(result): @@ -627,7 +630,7 @@ class ASystemPackHoldsThatSystem(unittest.TestCase): from contextlib import redirect_stdout import yaml - from verify import verify_system + from packs.emulatorcheck import verify_system _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) @@ -659,7 +662,7 @@ class ASystemPackHoldsThatSystem(unittest.TestCase): })) report = verify_system(["atari-lynx"], "emulators", db) with redirect_stdout(io.StringIO()): - path = builder.generate_system_pack( + path = emulatorpack.generate_system_pack( ["atari-lynx"], "emulators", db, "bios", "out", offline=True, ) with zipfile.ZipFile(path) as zf: @@ -681,7 +684,7 @@ class ATreeHoldsAPathForAnotherProfile(unittest.TestCase): from contextlib import redirect_stdout import yaml - from verify import verify_emulator + from packs.emulatorcheck import verify_emulator _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) @@ -720,9 +723,9 @@ class ATreeHoldsAPathForAnotherProfile(unittest.TestCase): names = ["atree", "msxemu"] report = verify_emulator(names, "emulators", db, platforms_dir="platforms", system_ids=["colecovision"]) - record = builder.PackRecord() + record = archive.PackRecord() with redirect_stdout(io.StringIO()): - builder.generate_emulator_pack( + emulatorpack.generate_emulator_pack( names, "emulators", db, "bios", "", offline=True, platforms_dir="platforms", record=record, system_ids=["colecovision"], ) diff --git a/tests/test_target_names.py b/tests/test_target_names.py index edf5dbeb6..37d59533a 100644 --- a/tests/test_target_names.py +++ b/tests/test_target_names.py @@ -115,18 +115,18 @@ class EachPlatformNamesTheTargetItsOwnWay(unittest.TestCase): import contextlib import io - import generate_pack + from packs import naming platforms_dir = str(REPO_ROOT / "platforms") with contextlib.redirect_stdout(io.StringIO()): - expected = generate_pack._expected_pack_names( + expected = naming._expected_pack_names( ["batocera", "recalbox"], platforms_dir, None, "rpi4" ) self.assertTrue(any("_Bcm2711_" in name for name in expected["batocera"])) self.assertTrue(any("_Rpi464_" in name for name in expected["recalbox"])) for platform, tag in (("batocera", "bcm2711"), ("recalbox", "rpi4_64")): self.assertEqual( - generate_pack._platform_target(platform, "rpi4", platforms_dir), tag + naming._platform_target(platform, "rpi4", platforms_dir), tag ) def test_no_naming_site_reads_the_typed_target(self): diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index e94c85805..ea0e33d8a 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -364,10 +364,10 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase): self.assertIn("amiberry-7.1.1-332", resolved) def test_the_list_names_the_boards_of_each_downloaded_core(self): - import generate_pack + from packs import manifestcores core_names = {"amiberry": [], "higan_sfc_balanced": ["nside_sfc_balanced"]} - boards = generate_pack._downloaded_cores( + boards = manifestcores._downloaded_cores( self.config, self.profiles, core_names, str(REPO_ROOT / "platforms")) self.assertEqual(set(boards), {"amiberry", "higan_sfc_balanced"}) self.assertIn("x86_64", boards["amiberry"]) diff --git a/tests/test_target_verify.py b/tests/test_target_verify.py index 5ca9010fb..b8cc0e74d 100644 --- a/tests/test_target_verify.py +++ b/tests/test_target_verify.py @@ -21,7 +21,7 @@ import unittest from pathlib import Path from model.targets import build_target_cores_cache -from generate_pack import _target_cores_for +from packs.finalize import _target_cores_for REPO_ROOT = Path(__file__).resolve().parent.parent @@ -49,7 +49,7 @@ class ANameClaimsOnlyANarrowingThatHappened(unittest.TestCase): on switch'.""" def test_a_platform_without_the_target_is_named_plainly(self): - from generate_pack import _narrowings, _platform_target + from packs.naming import _narrowings, _platform_target platforms = str(REPO_ROOT / "platforms") self.assertIsNone(_platform_target("bizhawk", "switch", platforms)) @@ -137,6 +137,8 @@ class ASplitBuildsOnlyTheTargetsSystems(unittest.TestCase): from unittest import mock import generate_pack + from packs import bysystem + from packs import platformpack from model.profiles import load_emulator_profiles platforms = str(REPO_ROOT / "platforms") @@ -149,10 +151,10 @@ class ASplitBuildsOnlyTheTargetsSystems(unittest.TestCase): return with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out, \ - mock.patch.object(generate_pack, "generate_pack", record), \ + mock.patch.object(platformpack, "generate_pack", record), \ mock.patch.object(generate_pack, "_collect_emulator_extras", return_value=[]): - generate_pack.generate_split_packs( + bysystem.generate_split_packs( "retroarch", platforms, {"files": {}}, "bios", out, emu_profiles=profiles, target_cores=_target_cores_for("retroarch", "switch", platforms), @@ -206,6 +208,8 @@ class TheSplitDirectoryReadsThePackStem(unittest.TestCase): from unittest import mock import generate_pack + from packs import bysystem + from packs import naming config = {"platform": "Foo: Bar", "version": "release/1.22", "systems": {}} with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out, \ @@ -213,10 +217,10 @@ class TheSplitDirectoryReadsThePackStem(unittest.TestCase): return_value=config), \ mock.patch.object(generate_pack, "_collect_emulator_extras", return_value=[]): - generate_pack.generate_split_packs( + bysystem.generate_split_packs( "foo", "platforms", {"files": {}}, "bios", out, emu_profiles={}, ) - stem = generate_pack._platform_pack_stem(["foo"], "foo", "platforms") + stem = naming._platform_pack_stem(["foo"], "foo", "platforms") self.assertEqual(os.listdir(out), [f"{stem}_Split"]) self.assertEqual(stem, "Foo-_Bar_release-1.22") diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index b2d77a8f6..b40f69f00 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -24,6 +24,9 @@ import diff_truth import pipeline from resolve import truth import verify +from packs import coverage +from packs import report as packs_report +from packs import verdicts REPO_ROOT = Path(__file__).resolve().parents[1] @@ -271,7 +274,7 @@ class TheGapHeadingAddsUp(unittest.TestCase): 16 entries were set aside without a word.""" def test_every_entry_is_counted_once(self): - import cross_reference as xref + from packs import crossref files = [ {"name": "kick.rom", "required": True}, @@ -284,11 +287,11 @@ class TheGapHeadingAddsUp(unittest.TestCase): ] profiles = {"emu": {"emulator": "Emu", "type": "libretro", "systems": ["s"], "files": files}} - report = xref.cross_reference(profiles, {}, {"files": {}, "indexes": {}}, + report = crossref.cross_reference(profiles, {}, {"files": {}, "indexes": {}}, all_declared={"kick.rom": [(None, "kick.rom")]}) data = report["emu"] self.assertEqual( - xref.profile_breakdown(data), + crossref.profile_breakdown(data), "1 declared by platforms, 3 undeclared, 1 unsourceable, " "2 set aside (1 other versions of a slot, 1 outside the pack)", ) @@ -442,12 +445,12 @@ class TheVerifySummaryCountsDiscrepancies(unittest.TestCase): def test_the_closing_line_names_them(self): details = [ - {"system": "arcade", "name": "aes.zip", "status": verify.Status.OK, + {"system": "arcade", "name": "aes.zip", "status": verdicts.Status.OK, "discrepancy": "file present (OK) but hash differs"}, # Printed as MISSING, so not a second time as a discrepancy. - {"system": "arcade", "name": "x.zip", "status": verify.Status.MISSING, + {"system": "arcade", "name": "x.zip", "status": verdicts.Status.MISSING, "discrepancy": "unmet"}, - {"system": "arcade", "name": "x.zip", "status": verify.Status.MISSING}, + {"system": "arcade", "name": "x.zip", "status": verdicts.Status.MISSING}, ] summary = verify._overall_summary([ ({"severity_counts": {}, "details": details}, ["RetroArch"]), @@ -456,9 +459,9 @@ class TheVerifySummaryCountsDiscrepancies(unittest.TestCase): self.assertIn("1 discrepancy (RetroArch 1)", summary) def test_a_shared_destination_names_the_path_and_both_sides(self): - result = {"name": "disk.rom", "status": verify.Status.UNTESTED} + result = {"name": "disk.rom", "status": verdicts.Status.UNTESTED} entry = {"name": "disk.rom", "md5": "793f8678" + "0" * 24} - self.assertTrue(verify._twin_unmet( + self.assertTrue(coverage._twin_unmet( result, "coco", entry, "nec-pc-88", "bios/disk.rom" )) message = result["discrepancy"] @@ -472,8 +475,8 @@ class EveryPlatformInTheSummaryCarriesItsCount(unittest.TestCase): named counts did not add up to the total.""" def test_a_count_of_one_is_written(self): - one = {"severity_counts": {verify.Severity.WARNING: 1}, "details": []} - two = {"severity_counts": {verify.Severity.WARNING: 2}, "details": []} + one = {"severity_counts": {verdicts.Severity.WARNING: 1}, "details": []} + two = {"severity_counts": {verdicts.Severity.WARNING: 2}, "details": []} summary = verify._overall_summary([(two, ["Lakka"]), (one, ["ROCKNIX"])]) self.assertIn("3 warning (Lakka 2, ROCKNIX 1)", summary) @@ -491,7 +494,7 @@ class HeldButNotPackedNamesEachReason(unittest.TestCase): def _printed(self, entries: list[dict]) -> str: out = io.StringIO() with contextlib.redirect_stdout(out): - verify._print_undeclared_section({"undeclared_files": entries}, False) + packs_report._print_undeclared_section({"undeclared_files": entries}, False) return out.getvalue() def test_each_reason_carries_its_count(self): diff --git a/tests/test_twin_declaration_status.py b/tests/test_twin_declaration_status.py index 96a564a44..71a40cd79 100644 --- a/tests/test_twin_declaration_status.py +++ b/tests/test_twin_declaration_status.py @@ -23,8 +23,10 @@ import yaml from model.platforms import _platform_config_cache import generate_db -import generate_pack as builder -from verify import Status, verify_platform +from packs import archive +from packs import platformpack +from packs.verdicts import Status +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent @@ -70,10 +72,10 @@ class TwinDeclarationStatus(unittest.TestCase): return config def _check(self, config: dict) -> None: - record = builder.PackRecord() + record = archive.PackRecord() out = io.StringIO() with contextlib.redirect_stdout(out): - builder.generate_pack( + platformpack.generate_pack( "twin", "platforms", self.db, "bios", "out", emulators_dir="emulators", emu_profiles={}, record=record, offline=True, diff --git a/tests/test_twin_declarations.py b/tests/test_twin_declarations.py index e1cf6a916..a7ed1db91 100644 --- a/tests/test_twin_declarations.py +++ b/tests/test_twin_declarations.py @@ -19,7 +19,7 @@ from pathlib import Path from model.profiles import _emulator_profiles_cache import generate_db -from verify import verify_platform +from packs.coverage import verify_platform class TwinDeclarations(unittest.TestCase): diff --git a/tests/test_undeclared_dedup.py b/tests/test_undeclared_dedup.py index 98238585a..1c5227af2 100644 --- a/tests/test_undeclared_dedup.py +++ b/tests/test_undeclared_dedup.py @@ -16,7 +16,7 @@ import unittest class StandaloneFallsBackOnPath(unittest.TestCase): def test_both_paths_survive(self): - from verify import find_undeclared_files + from packs.gaps import find_undeclared_files profile = { "emulator": "Clock Signal", diff --git a/tests/test_unplaced_extras.py b/tests/test_unplaced_extras.py index b039b8c0b..5fc3af97c 100644 --- a/tests/test_unplaced_extras.py +++ b/tests/test_unplaced_extras.py @@ -21,9 +21,9 @@ import yaml 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 -from verify import verify_platform +from packs import manifest as packs_manifest +from packs.extras import platform_region_groups +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent @@ -106,7 +106,7 @@ class SlugPlatform(unittest.TestCase): self.assertEqual(coverage["core_missing"], 1) def test_the_manifest_says_why_it_is_absent(self): - manifest = builder.generate_manifest( + manifest = packs_manifest.generate_manifest( "slugs", "platforms", self.db, "bios", "platforms/_registry.yml", emulators_dir="emulators", emu_profiles=self.profiles, offline=True, ) @@ -206,7 +206,7 @@ class FlatFirmwareFolder(unittest.TestCase): load_platform_config("flat", "platforms"), db, "emulators", profiles, ) - return builder.generate_manifest( + return packs_manifest.generate_manifest( "flat", "platforms", db, "bios", "platforms/_registry.yml", emulators_dir="emulators", emu_profiles=profiles, offline=True, ) @@ -250,7 +250,8 @@ class UserProvidedIsNeverTakenFromTheCollection(unittest.TestCase): made it report 1/1 OK for a pack that holds no such file.""" def test_verify_matches_the_builder(self): - from verify import Status, verify_emulator + from packs.verdicts import Status + from packs.emulatorcheck import verify_emulator with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() diff --git a/tests/test_validate_pr.py b/tests/test_validate_pr.py index 8c67e4602..438d536d8 100644 --- a/tests/test_validate_pr.py +++ b/tests/test_validate_pr.py @@ -17,6 +17,7 @@ import unittest from pathlib import Path import validate_pr +from resolve import review REPO_ROOT = Path(__file__).resolve().parent.parent @@ -43,13 +44,13 @@ class _Fixture(unittest.TestCase): class FileShapeChecks(_Fixture): def test_missing_file_fails_without_hashing(self): - result = validate_pr.validate_file("bios/nope.bin", None, EMPTY_HASHES) + result = review.validate_file("bios/nope.bin", None, EMPTY_HASHES) self.assertFalse(result.passed) self.assertEqual(result.sha1, "") def test_a_path_never_read_shows_no_digest(self): """Empty Size, SHA1, MD5 and CRC32 lines read as an empty file contributed.""" - result = validate_pr.validate_file("bios/nope.bin", None, EMPTY_HASHES) + result = review.validate_file("bios/nope.bin", None, EMPTY_HASHES) markdown = result.to_markdown() for label in ("**Size**", "**SHA1**", "**MD5**", "**CRC32**"): self.assertNotIn(label, markdown) @@ -63,18 +64,18 @@ class FileShapeChecks(_Fixture): validate_pr.expand_folders(["card", "empty", "loose.bin"]), [str(Path("card/bios/a.bin")), str(Path("card/bios/sub/b.bin")), "empty", "loose.bin"], ) - result = validate_pr.validate_file("empty", None, EMPTY_HASHES) + result = review.validate_file("empty", None, EMPTY_HASHES) self.assertIn("Folder with no file in it", result.to_markdown()) def test_empty_file_fails(self): rel = self._bios_file("bios/Sony/PS/empty.bin", b"") - result = validate_pr.validate_file(rel, None, EMPTY_HASHES) + result = review.validate_file(rel, None, EMPTY_HASHES) self.assertFalse(result.passed) self.assertIn("empty", result.to_markdown().lower()) def test_executable_extension_is_refused(self): rel = self._bios_file("bios/Sony/PS/payload.exe") - result = validate_pr.validate_file(rel, None, EMPTY_HASHES) + result = review.validate_file(rel, None, EMPTY_HASHES) self.assertFalse(result.passed) self.assertIn("Blocked file extension", result.to_markdown()) @@ -85,7 +86,7 @@ class FileShapeChecks(_Fixture): data = b"MZ pinned" rel = self._bios_file("bios/Lexaloffle/PICO-8/pico8.exe", data) pins = {"sha1": {hashlib.sha1(data).hexdigest(): {"lexaloffle"}}} - result = validate_pr.validate_file(rel, None, EMPTY_HASHES, pins) + result = review.validate_file(rel, None, EMPTY_HASHES, pins) self.assertNotIn("Blocked file extension", result.to_markdown()) self.assertIn("pins by sha1: lexaloffle", result.to_markdown()) @@ -94,24 +95,24 @@ class FileShapeChecks(_Fixture): data = b"MZ weak" rel = self._bios_file("bios/Sony/PS/tool.exe", data) pins = {"md5": {hashlib.md5(data).hexdigest(): {"someemu"}}} - result = validate_pr.validate_file(rel, None, EMPTY_HASHES, pins) + result = review.validate_file(rel, None, EMPTY_HASHES, pins) self.assertFalse(result.passed) self.assertIn("Blocked file extension", result.to_markdown()) def test_oversized_file_is_refused(self): rel = self._bios_file("bios/Sony/PS/big.bin") - original = validate_pr.MAX_FILE_SIZE - validate_pr.MAX_FILE_SIZE = 2 + original = review.MAX_FILE_SIZE + review.MAX_FILE_SIZE = 2 try: - result = validate_pr.validate_file(rel, None, EMPTY_HASHES) + result = review.validate_file(rel, None, EMPTY_HASHES) finally: - validate_pr.MAX_FILE_SIZE = original + review.MAX_FILE_SIZE = original self.assertFalse(result.passed) self.assertIn("too large", result.to_markdown()) def test_ordinary_file_passes(self): rel = self._bios_file("bios/Sony/PlayStation/scph.bin") - result = validate_pr.validate_file(rel, None, EMPTY_HASHES) + result = review.validate_file(rel, None, EMPTY_HASHES) self.assertTrue(result.passed, result.to_markdown()) self.assertEqual(len(result.sha1), 40) @@ -131,8 +132,8 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): "emulator: Engine\ntype: standalone\nsystems: [x]\nfiles:\n" f" - name: \"data.bin\"\n sha1: \"{hashlib.sha1(data).hexdigest()}\"\n" ) - known = validate_pr.load_profile_hashes(str(emulators)) - result = validate_pr.validate_file( + known = review.load_profile_hashes(str(emulators)) + result = review.validate_file( self._bios_file("bios/Maker/Engine/data.bin", data), None, EMPTY_HASHES, known, ) self.assertIn(("PASS", "Hash matches a file the emulator profile declares: engine"), @@ -154,8 +155,8 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): ) db = {"files": {hashlib.sha1(held).hexdigest(): {"path": "bios/Maker/Console/a.bin"}}, "indexes": {"by_md5": {}, "by_sha256": {}}} - known = validate_pr.load_profile_hashes(str(emulators), db) - result = validate_pr.validate_file( + known = review.load_profile_hashes(str(emulators), db) + result = review.validate_file( self._bios_file("Downloads/b.bin", missing), db, EMPTY_HASHES, known, ) self.assertIn( @@ -167,19 +168,19 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): # A file of that name already there: the copy is a variant. self._bios_file("bios/Maker/Console/b.bin", b"another") self.assertEqual( - validate_pr.validate_file("Downloads/b.bin", db, EMPTY_HASHES, known).destination, + review.validate_file("Downloads/b.bin", db, EMPTY_HASHES, known).destination, f"bios/Maker/Console/.variants/b.bin.{result.sha1[:8]}", ) # Copied under the declared name, never over a file, and only once. card = self._bios_file("card/B.BIN", missing) - named = validate_pr.validate_file(card, db, EMPTY_HASHES, known) + named = review.validate_file(card, db, EMPTY_HASHES, known) self.assertEqual(validate_pr.place([named]), [named.destination]) self.assertEqual((self.tmp / named.destination).read_bytes(), missing) self.assertTrue((self.tmp / card).is_file()) self.assertEqual(validate_pr.place([named]), []) - unknown = validate_pr.validate_file(self._bios_file("card/x.bin"), db, EMPTY_HASHES, known) + unknown = review.validate_file(self._bios_file("card/x.bin"), db, EMPTY_HASHES, known) self.assertEqual((unknown.outcome, unknown.destination), ("unknown", "")) - placed = validate_pr.validate_file( + placed = review.validate_file( self._bios_file("bios/Other/Place/b.bin", missing), db, EMPTY_HASHES, known, ) self.assertTrue(any("Placed under bios/Other/Place/" in m for _s, m in placed.checks)) @@ -202,8 +203,8 @@ class ADeclaredFileBesideItsHeldNameIsAVariant(_Fixture): ) db = {"files": {"a" * 40: {"path": "bios/Maker/Console/v.bin"}}, "indexes": {"by_md5": {}, "by_sha256": {}, "by_name": {"v.bin": ["a" * 40]}}} - known = validate_pr.load_profile_hashes(str(emulators), db) - result = validate_pr.validate_file( + known = review.load_profile_hashes(str(emulators), db) + result = review.validate_file( self._bios_file("card/v.bin", data), db, EMPTY_HASHES, known) slot = f"bios/Maker/Console/.variants/v.bin.{result.sha1[:8]}" self.assertEqual(result.destination, slot) @@ -226,14 +227,14 @@ class ASizeEveryDeclarationRulesOutIsNotAVariant(_Fixture): def test_a_truncated_file_is_warned_and_not_offered_a_slot(self): rel = self._bios_file("scph5501.bin", b"x" * 1024) - text = validate_pr.validate_file(rel, self.DB, self.PLATFORM).to_markdown() + text = review.validate_file(rel, self.DB, self.PLATFORM).to_markdown() self.assertIn("expects 524,288 bytes", text) self.assertNotIn(".variants/", text) self.assertNotIn("File size OK", text) def test_a_right_sized_variant_goes_beside_its_name(self): rel = self._bios_file("scph5501.bin", b"y" * 524288) - text = validate_pr.validate_file(rel, self.DB, self.PLATFORM).to_markdown() + text = review.validate_file(rel, self.DB, self.PLATFORM).to_markdown() self.assertIn("bios/Sony/PlayStation/.variants/scph5501.bin.", text) self.assertNotIn("expects", text) @@ -250,7 +251,7 @@ class SymlinksAreRefusedBeforeReading(_Fixture): self._bios_file("bios/Sony/PS/real.bin") link = self.tmp / "bios" / "Sony" / "PS" / "link.bin" link.symlink_to(self.tmp / "bios" / "Sony" / "PS" / "real.bin") - result = validate_pr.validate_file( + result = review.validate_file( "bios/Sony/PS/link.bin", None, EMPTY_HASHES ) self.assertFalse(result.passed) @@ -266,7 +267,7 @@ class SymlinksAreRefusedBeforeReading(_Fixture): calls.append(p) or real(p, *a, **k) ) try: - validate_pr.validate_file("bios/Sony/PS/link.bin", None, EMPTY_HASHES) + review.validate_file("bios/Sony/PS/link.bin", None, EMPTY_HASHES) finally: validate_pr.compute_hashes = real self.assertEqual(calls, [], "a symlink target must not be read") @@ -276,7 +277,7 @@ class SymlinksAreRefusedBeforeReading(_Fixture): link = self.tmp / "bios" / "Sony" / "PS" / "zero.bin" link.parent.mkdir(parents=True, exist_ok=True) link.symlink_to("/dev/zero") - result = validate_pr.validate_file( + result = review.validate_file( "bios/Sony/PS/zero.bin", None, EMPTY_HASHES ) self.assertFalse(result.passed) @@ -285,24 +286,24 @@ class SymlinksAreRefusedBeforeReading(_Fixture): class HashRecognition(_Fixture): def test_a_declared_sha1_is_recognised(self): rel = self._bios_file("bios/Sony/PS/known.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) + probe = review.validate_file(rel, None, EMPTY_HASHES) known = {"sha1": {probe.sha1}, "md5": set(), "names": set()} - result = validate_pr.validate_file(rel, None, known) + result = review.validate_file(rel, None, known) self.assertIn("SHA1 matches known platform requirement", result.to_markdown()) def test_a_declared_md5_is_recognised(self): rel = self._bios_file("bios/Sony/PS/known.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) + probe = review.validate_file(rel, None, EMPTY_HASHES) known = {"sha1": set(), "md5": {probe.md5}, "names": set()} self.assertIn( "MD5 matches known platform requirement", - validate_pr.validate_file(rel, None, known).to_markdown(), + review.validate_file(rel, None, known).to_markdown(), ) def test_a_known_name_with_another_hash_is_flagged_as_a_variant(self): rel = self._bios_file("bios/Sony/PS/known.bin") known = {"sha1": set(), "md5": set(), "names": {"known.bin"}} - markdown = validate_pr.validate_file(rel, None, known).to_markdown() + markdown = review.validate_file(rel, None, known).to_markdown() self.assertIn("may be a variant", markdown) self.assertIn(".variants/known.bin.", markdown) @@ -310,7 +311,7 @@ class HashRecognition(_Fixture): """Random bytes read "PASS" and "all checks passed", and the warning named the platform configs alone though the profiles were searched.""" rel = self._bios_file("bios/Sony/PS/mystery.bin") - result = validate_pr.validate_file(rel, None, EMPTY_HASHES) + result = review.validate_file(rel, None, EMPTY_HASHES) markdown = result.to_markdown() self.assertEqual(result.outcome, "unknown") self.assertIn("### REVIEW", markdown) @@ -330,7 +331,7 @@ class HashRecognition(_Fixture): archive.writestr("other.bin", b"noise") db = {"files": {hashlib.sha1(held).hexdigest(): {"path": "bios/Sony/PS/scph5501.bin"}}} known = {**EMPTY_HASHES, "md5": {hashlib.md5(declared).hexdigest()}} - result = validate_pr.validate_file("mybios.zip", db, known) + result = review.validate_file("mybios.zip", db, known) markdown = result.to_markdown() self.assertEqual(result.outcome, "unknown") self.assertIn("unzipped, not the archive", markdown) @@ -344,11 +345,11 @@ class HashRecognition(_Fixture): """A copy of a held file passed, and was sent to the folder that already holds it.""" rel = self._bios_file("elsewhere/dupe.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) + probe = review.validate_file(rel, None, EMPTY_HASHES) db = {"files": {probe.sha1: {"path": "bios/Sony/PS/original.bin"}}} known = {**EMPTY_HASHES, "sha1": {probe.sha1}, "folders": {probe.sha1: {"bios/Sony/PS/"}}} - result = validate_pr.validate_file(rel, db, known) + result = review.validate_file(rel, db, known) markdown = result.to_markdown() self.assertEqual(result.outcome, "held") self.assertIn("### REVIEW", markdown) @@ -359,17 +360,17 @@ class HashRecognition(_Fixture): def test_a_copy_in_a_tree_read_by_path_is_kept(self): rel = self._bios_file("bios/ScummVM/a/dupe.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) + probe = review.validate_file(rel, None, EMPTY_HASHES) db = {"files": {probe.sha1: {"path": "bios/ScummVM/b/dupe.bin"}}} - self.assertNotEqual(validate_pr.validate_file(rel, db, EMPTY_HASHES).outcome, "held") + self.assertNotEqual(review.validate_file(rel, db, EMPTY_HASHES).outcome, "held") def test_the_file_the_database_holds_is_not_its_own_duplicate(self): """The documented example on a tracked file warned "Duplicate: identical file already exists at" the very path being validated.""" rel = self._bios_file("bios/Sony/PS/held.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) + probe = review.validate_file(rel, None, EMPTY_HASHES) db = {"files": {probe.sha1: {"path": rel}}} - markdown = validate_pr.validate_file(rel, db, EMPTY_HASHES).to_markdown() + markdown = review.validate_file(rel, db, EMPTY_HASHES).to_markdown() self.assertNotIn("Duplicate", markdown) self.assertIn("Already in the database at this path", markdown) @@ -385,15 +386,15 @@ class PlacementBySystem(_Fixture): def test_a_file_under_another_maker_is_told_where_its_system_lives(self): rel = self._bios_file("bios/Nintendo/Game Boy/scph.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) - markdown = validate_pr.validate_file(rel, None, self._known(probe.sha1)).to_markdown() + probe = review.validate_file(rel, None, EMPTY_HASHES) + markdown = review.validate_file(rel, None, self._known(probe.sha1)).to_markdown() self.assertIn("bios/Sony/PlayStation/", markdown) self.assertNotIn("Correct placement", markdown) def test_the_folder_of_its_system_passes(self): rel = self._bios_file("bios/Sony/PlayStation/scph.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) - markdown = validate_pr.validate_file(rel, None, self._known(probe.sha1)).to_markdown() + probe = review.validate_file(rel, None, EMPTY_HASHES) + markdown = review.validate_file(rel, None, self._known(probe.sha1)).to_markdown() self.assertIn("Correct placement: bios/Sony/PlayStation/", markdown) def test_systems_spread_over_makers_name_no_home(self): @@ -409,7 +410,7 @@ class PlacementBySystem(_Fixture): db = {"files": {"aaaa": {"path": "bios/Arcade/MAME/a.zip"}, "bbbb": {"path": "bios/Apple/Apple II/b.zip"}}, "indexes": {"by_md5": {}}} - known = validate_pr.load_platform_hashes(str(platforms), db) + known = review.load_platform_hashes(str(platforms), db) self.assertEqual(known["folders"], {}) @@ -418,29 +419,29 @@ class Placement(_Fixture): rel = self._bios_file("bios/Sega/Saturn/sega_101.bin") self.assertIn( "Correct placement: bios/Sega/Saturn/", - validate_pr.validate_file(rel, None, EMPTY_HASHES).to_markdown(), + review.validate_file(rel, None, EMPTY_HASHES).to_markdown(), ) def test_a_file_at_the_bios_root_is_flagged(self): rel = self._bios_file("bios/loose.bin") self.assertIn( "bios/Manufacturer/Console/", - validate_pr.validate_file(rel, None, EMPTY_HASHES).to_markdown(), + review.validate_file(rel, None, EMPTY_HASHES).to_markdown(), ) def test_a_file_outside_bios_is_flagged(self): rel = self._bios_file("elsewhere/loose.bin") self.assertIn( "not under bios/", - validate_pr.validate_file(rel, None, EMPTY_HASHES).to_markdown(), + review.validate_file(rel, None, EMPTY_HASHES).to_markdown(), ) class Reporting(_Fixture): def test_markdown_carries_every_digest_and_the_verdict(self): rel = self._bios_file("bios/Sega/Saturn/sega.bin") - probe = validate_pr.validate_file(rel, None, EMPTY_HASHES) - result = validate_pr.validate_file(rel, None, {**EMPTY_HASHES, "sha1": {probe.sha1}}) + probe = review.validate_file(rel, None, EMPTY_HASHES) + result = review.validate_file(rel, None, {**EMPTY_HASHES, "sha1": {probe.sha1}}) markdown = result.to_markdown() for value in (result.sha1, result.md5, result.crc32): self.assertIn(value, markdown) @@ -448,7 +449,7 @@ class Reporting(_Fixture): def test_a_failure_is_marked_in_the_heading(self): rel = self._bios_file("bios/Sega/Saturn/bad.exe") - self.assertIn("### FAIL", validate_pr.validate_file(rel, None, EMPTY_HASHES).to_markdown()) + self.assertIn("### FAIL", review.validate_file(rel, None, EMPTY_HASHES).to_markdown()) @unittest.skipUnless((REPO_ROOT / "database.json").is_file(), "database.json is not built") def test_the_status_line_names_what_is_left_to_review(self): @@ -473,7 +474,7 @@ class Reporting(_Fixture): class PlatformHashLoading(_Fixture): def test_missing_directory_yields_empty_sets(self): - known = validate_pr.load_platform_hashes(str(self.tmp / "absent")) + known = review.load_platform_hashes(str(self.tmp / "absent")) self.assertEqual(known, {"sha1": set(), "md5": set(), "sha256": set(), "crc32": set(), "names": set(), "folders": {}, "sizes": {}, "entries": {}, "named": {}, "name_systems": {}, "system_dirs": {}, @@ -494,7 +495,7 @@ class PlatformHashLoading(_Fixture): f" sha1: {'a' * 40}\n" f" md5: {'b' * 32}\n" ) - known = validate_pr.load_platform_hashes(str(platforms)) + known = review.load_platform_hashes(str(platforms)) self.assertIn("a" * 40, known["sha1"]) self.assertIn("b" * 32, known["md5"]) self.assertIn("boot.bin", known["names"]) @@ -514,7 +515,7 @@ class ThePlatformsOwnCheckDecides(_Fixture): encoding="utf-8") (platforms / "p.yml").write_text(f"platform: P\nsystems:\n s:\n files:\n{systems}", encoding="utf-8") - return validate_pr.load_platform_hashes(str(platforms)) + return review.load_platform_hashes(str(platforms)) def _zip(self) -> str: import zipfile @@ -526,7 +527,7 @@ class ThePlatformsOwnCheckDecides(_Fixture): return "contrib/set.zip" def _verdict(self, path: str, known: dict) -> str: - return validate_pr.validate_file(path, None, known).to_markdown() + return review.validate_file(path, None, known).to_markdown() def test_a_member_pinned_by_zipped_file(self): import hashlib @@ -561,8 +562,8 @@ class ThePlatformsOwnCheckDecides(_Fixture): db = {"files": {"m" * 40: {"path": "bios/Arcade/MAME/set.zip"}, "c" * 40: {"path": "bios/Coleco/Adam/set.zip"}}, "indexes": {"by_name": {"set.zip": ["m" * 40, "c" * 40]}}} - self.assertEqual(validate_pr._variant_home(db, "set.zip", "c" * 40), "bios/Coleco/Adam/") - self.assertEqual(validate_pr._variant_home(db, "set.zip"), "bios/Arcade/MAME/") + self.assertEqual(review._variant_home(db, "set.zip", "c" * 40), "bios/Coleco/Adam/") + self.assertEqual(review._variant_home(db, "set.zip"), "bios/Arcade/MAME/") def test_another_member_is_still_a_variant(self): known = self._platforms( @@ -614,7 +615,7 @@ class AFileOutsideBiosIsToldWhereToGo(unittest.TestCase): import os as _os import tempfile as _tempfile - from validate_pr import validate_file + from resolve.review import validate_file content = b"bios bytes" import hashlib as _hashlib @@ -657,7 +658,7 @@ class ProfileHashesReadAsTheResolverDoes(unittest.TestCase): " - name: bsx.bin\n sha256: \"aa,bb\"\n", encoding="utf-8", ) - known = validate_pr.load_profile_hashes(tmp) + known = review.load_profile_hashes(tmp) self.assertEqual(known["crc32"][("bf63fb1f", 16384)], {"core"}) self.assertIn("bb", known["sha256"]) diff --git a/tests/test_validate_pr_flow.py b/tests/test_validate_pr_flow.py index 803a53326..47cf6a193 100644 --- a/tests/test_validate_pr_flow.py +++ b/tests/test_validate_pr_flow.py @@ -21,6 +21,8 @@ from pathlib import Path import yaml import validate_pr +from core import gitclone +from resolve import review REPO_ROOT = Path(__file__).resolve().parent.parent @@ -94,15 +96,15 @@ class OversizedFileAdvice(unittest.TestCase): os.chdir(self.tmp) self.addCleanup(self._tmp.cleanup) self.addCleanup(os.chdir, self._cwd) - self._max = validate_pr.MAX_FILE_SIZE - self.addCleanup(setattr, validate_pr, "MAX_FILE_SIZE", self._max) + self._max = review.MAX_FILE_SIZE + self.addCleanup(setattr, review, "MAX_FILE_SIZE", self._max) def _message(self) -> str: path = self.tmp / "bios" / "Sony" / "PlayStation 3" / "PS3UPDAT.PUP" path.parent.mkdir(parents=True) path.write_bytes(b"PUP" * 4) - validate_pr.MAX_FILE_SIZE = 4 - result = validate_pr.validate_file( + review.MAX_FILE_SIZE = 4 + result = review.validate_file( str(path.relative_to(self.tmp)), None, {"sha1": set(), "md5": set(), "names": set()}, ) @@ -114,7 +116,7 @@ class OversizedFileAdvice(unittest.TestCase): self.assertNotIn("storage: external", message) self.assertIn("large-files", message) self.assertIn("open an issue", message) - self.assertIn(validate_pr.LARGE_FILE_ISSUE_URL, message) + self.assertIn(review.LARGE_FILE_ISSUE_URL, message) def test_the_issue_form_is_filled_and_nothing_points_to_the_pr(self): """The link opened an empty form, and the same report said to put the @@ -123,8 +125,8 @@ class OversizedFileAdvice(unittest.TestCase): path = self.tmp / "big.bin" path.write_bytes(b"x" * 8) - validate_pr.MAX_FILE_SIZE = 4 - result = validate_pr.validate_file( + review.MAX_FILE_SIZE = 4 + result = review.validate_file( "big.bin", None, {"sha1": set(), "md5": set(), "names": set()}, ) message = next(m for s, m in result.checks if s == "FAIL" and "too large" in m) @@ -141,7 +143,7 @@ class OversizedFileAdvice(unittest.TestCase): self.assertNotIn("not under bios/", others) def test_the_linked_issue_template_exists(self): - template = validate_pr.LARGE_FILE_ISSUE_URL.rsplit("template=", 1)[1] + template = review.LARGE_FILE_ISSUE_URL.rsplit("template=", 1)[1] self.assertTrue( (REPO_ROOT / ".github" / "ISSUE_TEMPLATE" / template).is_file(), template ) @@ -206,7 +208,7 @@ class AnUnfetchedUpstreamIsFetched(unittest.TestCase): cwd = os.getcwd() os.chdir(clone) try: - with mock.patch.object(validate_pr, "PROJECT_URLS", (str(project),)): + with mock.patch.object(gitclone, "PROJECT_URLS", (str(project),)): self.assertEqual(validate_pr.get_changed_files(), ["bios/new.bin"]) finally: os.chdir(cwd) diff --git a/tests/test_validate_pr_hashes.py b/tests/test_validate_pr_hashes.py index c0f11c3a7..3c268f784 100644 --- a/tests/test_validate_pr_hashes.py +++ b/tests/test_validate_pr_hashes.py @@ -20,9 +20,9 @@ REPO_ROOT = Path(__file__).resolve().parents[1] class EveryAcceptedRevisionIsKnown(unittest.TestCase): def test_multi_hash_members_are_known(self): - import validate_pr + from resolve import review - known = validate_pr.load_platform_hashes(str(REPO_ROOT / "platforms")) + known = review.load_platform_hashes(str(REPO_ROOT / "platforms")) raw = yaml.safe_load((REPO_ROOT / "platforms" / "recalbox.yml").read_text()) listed = [ value.strip().lower() diff --git a/tests/test_validated_choice.py b/tests/test_validated_choice.py index 973535351..2fab81e45 100644 --- a/tests/test_validated_choice.py +++ b/tests/test_validated_choice.py @@ -301,7 +301,7 @@ class AlternativesAreLookedUpBySlot(unittest.TestCase): def test_same_answer_one_pass_per_profile(self): from unittest import mock - import packextras + from packs import extras as packextras from resolve import validation files = [{"name": "DUKE3D.GRP", "size": n} for n in (1, 2)] + [ @@ -351,11 +351,11 @@ class AVersionTakenWithoutACheck(unittest.TestCase): )) def test_the_pack_reads_it_as_an_alternative(self): - import generate_pack + from packs import platformpack fe = {"name": "BLOOD.RFF", "source_profile": "raze", "source_path": "BLOOD.RFF"} with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: - self.assertTrue(generate_pack._matches_an_alternative( + self.assertTrue(platformpack._matches_an_alternative( fe, self._file(tmp), {"raze": self.RAZE} )) diff --git a/tests/test_verify_data_dir_notice.py b/tests/test_verify_data_dir_notice.py index fa73b0559..b71776c2d 100644 --- a/tests/test_verify_data_dir_notice.py +++ b/tests/test_verify_data_dir_notice.py @@ -19,7 +19,8 @@ import unittest from pathlib import Path import generate_db -from verify import print_platform_result, verify_platform +from packs.report import print_platform_result +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_verify_emulator_evidence.py b/tests/test_verify_emulator_evidence.py index 2b33db6d2..7fb1cb846 100644 --- a/tests/test_verify_emulator_evidence.py +++ b/tests/test_verify_emulator_evidence.py @@ -22,7 +22,9 @@ import tempfile import unittest from pathlib import Path -import verify +from packs import emulatorcheck +from packs import report +from packs import verdicts REPO_ROOT = Path(__file__).resolve().parent.parent @@ -54,13 +56,14 @@ def _db(path: Path, name: str) -> dict: def _pack_files(root: Path, emulators: Path, db: dict) -> set[str]: """The paths the emulator pack writes, built in memory as the pipeline does.""" - import generate_pack + from packs import archive + from packs import emulatorpack - record = generate_pack.PackRecord() + record = archive.PackRecord() cwd = os.getcwd() os.chdir(root) try: - generate_pack.generate_emulator_pack( + emulatorpack.generate_emulator_pack( ["demo"], str(emulators), db, "bios", "", False, zip_contents={}, offline=True, record=record, ) @@ -105,7 +108,7 @@ class HashMismatchIsNotCoverage(unittest.TestCase): cwd = os.getcwd() os.chdir(self.root) try: - return verify.verify_emulator( + return emulatorcheck.verify_emulator( ["demo"], str(self.emulators), self.db ) finally: @@ -118,7 +121,7 @@ class HashMismatchIsNotCoverage(unittest.TestCase): statuses = {d["name"]: d["status"] for d in result["details"]} self.assertNotEqual( statuses.get("shared.rom"), - verify.Status.OK, + verdicts.Status.OK, "an entry whose only candidate contradicts its hash counted as covered", ) @@ -146,7 +149,7 @@ class HashMismatchIsNotCoverage(unittest.TestCase): detail = next( d for d in self._run()["details"] if d["name"] == "shared.rom" ) - self.assertEqual(detail["status"], verify.Status.OK) + self.assertEqual(detail["status"], verdicts.Status.OK) def test_an_entry_declaring_no_hash_is_still_ok(self): """Nothing to contradict, so presence is all the evidence there is.""" @@ -163,7 +166,7 @@ class HashMismatchIsNotCoverage(unittest.TestCase): detail = next( d for d in self._run()["details"] if d["name"] == "shared.rom" ) - self.assertEqual(detail["status"], verify.Status.OK) + self.assertEqual(detail["status"], verdicts.Status.OK) def test_a_genuinely_absent_file_still_reads_missing(self): (self.emulators / "demo.yml").write_text( @@ -179,7 +182,7 @@ class HashMismatchIsNotCoverage(unittest.TestCase): detail = next( d for d in self._run()["details"] if d["name"] == "nowhere.rom" ) - self.assertEqual(detail["status"], verify.Status.MISSING) + self.assertEqual(detail["status"], verdicts.Status.MISSING) class ArchiveHashMismatchIsNotCoverage(unittest.TestCase): @@ -234,7 +237,7 @@ class ArchiveHashMismatchIsNotCoverage(unittest.TestCase): cwd = os.getcwd() os.chdir(self.root) try: - return verify.verify_emulator(["demo"], str(self.emulators), self.db) + return emulatorcheck.verify_emulator(["demo"], str(self.emulators), self.db) finally: os.chdir(cwd) @@ -253,7 +256,7 @@ class ArchiveHashMismatchIsNotCoverage(unittest.TestCase): statuses = self._statuses(self._run()) self.assertEqual(len(statuses), 2, statuses) self.assertNotIn( - verify.Status.OK, + verdicts.Status.OK, statuses, "an archive whose bytes contradict its declared hash counted as covered", ) @@ -269,7 +272,7 @@ class ArchiveHashMismatchIsNotCoverage(unittest.TestCase): def test_a_matching_container_hash_is_still_ok(self): self._profile(hashlib.md5(self.archive.read_bytes()).hexdigest()) - self.assertEqual(set(self._statuses(self._run())), {verify.Status.OK}) + self.assertEqual(set(self._statuses(self._run())), {verdicts.Status.OK}) class UnsourceableIsNotAGap(unittest.TestCase): @@ -317,7 +320,7 @@ class UnsourceableIsNotAGap(unittest.TestCase): cwd = os.getcwd() os.chdir(self.root) try: - return verify.verify_emulator( + return emulatorcheck.verify_emulator( ["demo"], str(self.emulators), self.db ) finally: @@ -325,7 +328,7 @@ class UnsourceableIsNotAGap(unittest.TestCase): def test_an_unsourceable_entry_carries_its_reason(self): detail = next(d for d in self._result()["details"] if d["name"] == "paid.so") - self.assertEqual(detail["status"], verify.Status.MISSING) + self.assertEqual(detail["status"], verdicts.Status.MISSING) self.assertIn("unsourceable", detail) self.assertIn("paid", detail["unsourceable"]) @@ -333,7 +336,7 @@ class UnsourceableIsNotAGap(unittest.TestCase): detail = next( d for d in self._result()["details"] if d["name"] == "findable.rom" ) - self.assertEqual(detail["status"], verify.Status.MISSING) + self.assertEqual(detail["status"], verdicts.Status.MISSING) self.assertNotIn("unsourceable", detail) def test_the_summary_counts_the_two_apart(self): @@ -342,7 +345,7 @@ class UnsourceableIsNotAGap(unittest.TestCase): buffer = io.StringIO() with contextlib.redirect_stdout(buffer): - verify.print_emulator_result(self._result()) + report.print_emulator_result(self._result()) summary = buffer.getvalue().splitlines()[0] self.assertIn("1 missing", summary) self.assertIn("1 unsourceable", summary) @@ -353,7 +356,7 @@ class UnsourceableIsNotAGap(unittest.TestCase): buffer = io.StringIO() with contextlib.redirect_stdout(buffer): - verify.print_emulator_result(self._result()) + report.print_emulator_result(self._result()) out = buffer.getvalue() self.assertIn("UNSOURCEABLE: paid.so", out) self.assertIn("MISSING (required): findable.rom", out) @@ -435,10 +438,10 @@ class StandaloneSlotsFollowThePack(unittest.TestCase): self._tmp.cleanup() def test_each_standalone_folder_is_a_slot(self): - standalone = verify.verify_emulator( + standalone = emulatorcheck.verify_emulator( ["dual"], str(self.emulators), self.db, standalone=True ) - core = verify.verify_emulator(["dual"], str(self.emulators), self.db) + core = emulatorcheck.verify_emulator(["dual"], str(self.emulators), self.db) self.assertEqual(standalone["total_files"], 2) self.assertEqual(core["total_files"], 1) diff --git a/tests/test_verify_listing.py b/tests/test_verify_listing.py index 8522fa708..43486d420 100644 --- a/tests/test_verify_listing.py +++ b/tests/test_verify_listing.py @@ -58,6 +58,7 @@ class VerifyRefusesWhatAModeDoesNotRead(unittest.TestCase): def test_emulator_mode_reads_the_given_platforms_dir(self): import verify + from packs import emulatorcheck seen: list[str] = [] @@ -67,7 +68,7 @@ class VerifyRefusesWhatAModeDoesNotRead(unittest.TestCase): db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}}} with mock.patch.object(verify, "load_data_dir_registry", registry): - verify.verify_emulator( + emulatorcheck.verify_emulator( ["handy"], str(REPO_ROOT / "emulators"), db, platforms_dir="elsewhere" ) self.assertEqual(seen, ["elsewhere"]) @@ -90,6 +91,7 @@ class VerifyAppliesWhatItAccepts(unittest.TestCase): class EmulatorPackReadsThePlatformsDir(unittest.TestCase): def test_the_registry_comes_from_the_given_dir(self): import generate_pack + from packs import emulatorpack seen: list[str] = [] @@ -100,7 +102,7 @@ class EmulatorPackReadsThePlatformsDir(unittest.TestCase): db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}}} out = REPO_ROOT / "tmp" / "emupack-registry" with mock.patch.object(generate_pack, "load_data_dir_registry", registry): - generate_pack.generate_emulator_pack( + emulatorpack.generate_emulator_pack( ["handy"], str(REPO_ROOT / "emulators"), db, "bios", str(out), zip_contents={}, platforms_dir="elsewhere", ) @@ -117,7 +119,7 @@ class CoreArchivesAreCounted(unittest.TestCase): import contextlib import io - import verify + from packs import report result = {"undeclared_files": [ {"name": "neogeo.zip", "category": "bios_zip", "required": True, @@ -125,7 +127,7 @@ class CoreArchivesAreCounted(unittest.TestCase): ]} out = io.StringIO() with contextlib.redirect_stdout(out): - verify._print_undeclared_section(result, verbose=False) + report._print_undeclared_section(result, verbose=False) self.assertIn("1 required missing", out.getvalue()) self.assertIn("neogeo.zip", out.getvalue()) @@ -135,26 +137,26 @@ class ExistenceReportsWhatThePackReports(unittest.TestCase): """30 RetroArch entries printed DISCREPANCY in the pack, nothing in verify.""" import tempfile - import verify + from packs import verdicts with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: path = Path(tmp) / "aes.zip" path.write_bytes(b"local dump") entry = {"name": "aes.zip", "md5": "9d2ff2333e23910cf56f7f785609d36a"} - result = verify.verify_entry_existence( + result = verdicts.verify_entry_existence( entry, str(path), resolve_status="hash_mismatch", platform_display="RetroArch" ) - self.assertEqual(result["status"], verify.Status.OK) + self.assertEqual(result["status"], verdicts.Status.OK) self.assertIn("declared hash 9d2ff233", result["discrepancy"]) def test_the_file_found_is_named(self): """RetroArch, Lakka and RetroPie pages showed no "Served by" line: existence mode returned no path, where the hash modes return one.""" - import verify + from packs import verdicts - found = verify.verify_entry_existence({"name": "a.bin"}, "bios/X/Y/a.bin") + found = verdicts.verify_entry_existence({"name": "a.bin"}, "bios/X/Y/a.bin") self.assertEqual(found["path"], "bios/X/Y/a.bin") - self.assertNotIn("path", verify.verify_entry_existence({"name": "a.bin"}, None)) + self.assertNotIn("path", verdicts.verify_entry_existence({"name": "a.bin"}, None)) class TheDestinationsFlagNeedsAPack(unittest.TestCase): @@ -193,7 +195,7 @@ class EveryGapCountedIsNamed(unittest.TestCase): import contextlib import io - import verify + from packs import report result = {"undeclared_files": [ {"name": "opt.rom", "emulator": "core", "required": False, "in_repo": False}, @@ -201,11 +203,11 @@ class EveryGapCountedIsNamed(unittest.TestCase): "category": "game_data"}, ]} with contextlib.redirect_stdout(io.StringIO()) as quiet: - verify._print_undeclared_section(result, verbose=False) + report._print_undeclared_section(result, verbose=False) self.assertIn("1 optional missing (--verbose lists them)", quiet.getvalue()) self.assertIn("1 missing (--verbose lists them)", quiet.getvalue()) with contextlib.redirect_stdout(io.StringIO()) as verbose: - verify._print_undeclared_section(result, verbose=True) + report._print_undeclared_section(result, verbose=True) self.assertIn("MISSING (optional): core needs opt.rom", verbose.getvalue()) self.assertIn("MISSING (game data): engine needs level.dat", verbose.getvalue()) @@ -219,7 +221,7 @@ class BundledGameDataIsNotMissing(unittest.TestCase): import contextlib import io - import verify + from packs import report result = {"undeclared_files": [ {"name": "abuse.lsp", "emulator": "Abuse", "required": True, @@ -229,7 +231,7 @@ class BundledGameDataIsNotMissing(unittest.TestCase): "in_repo": False, "category": "game_data"}, ]} with contextlib.redirect_stdout(io.StringIO()) as out: - verify._print_undeclared_section(result, verbose=True) + report._print_undeclared_section(result, verbose=True) self.assertIn("Game data: 0 in pack, 1 missing", out.getvalue()) self.assertNotIn("needs abuse.lsp", out.getvalue()) self.assertIn("Bundled with their emulator, not collected: 1 (abuse.lsp)", @@ -244,7 +246,7 @@ class TheBundledLineSaysWhatItLeavesOut(unittest.TestCase): import contextlib import io - import verify + from packs import report result = {"undeclared_files": [ {"name": name, "emulator": "e", "required": required, "in_repo": False, @@ -252,21 +254,21 @@ class TheBundledLineSaysWhatItLeavesOut(unittest.TestCase): for name, required in (("fw.bin", True), ("a.frag", False), ("b.dll", False)) ]} with contextlib.redirect_stdout(io.StringIO()) as quiet: - verify._print_undeclared_section(result, verbose=False) + report._print_undeclared_section(result, verbose=False) self.assertIn( "Bundled with their emulator, not collected: 3 " "(fw.bin, 2 more, --verbose lists them)", quiet.getvalue(), ) with contextlib.redirect_stdout(io.StringIO()) as verbose: - verify._print_undeclared_section(result, verbose=True) + report._print_undeclared_section(result, verbose=True) self.assertIn( "Bundled with their emulator, not collected: 3 (a.frag, b.dll, fw.bin)", verbose.getvalue(), ) result["undeclared_files"] = result["undeclared_files"][1:] with contextlib.redirect_stdout(io.StringIO()) as unnamed: - verify._print_undeclared_section(result, verbose=False) + report._print_undeclared_section(result, verbose=False) self.assertIn("Bundled with their emulator, not collected: 2 (--verbose lists them)", unnamed.getvalue()) @@ -279,11 +281,11 @@ class TheCheckLineSaysWhatItIs(unittest.TestCase): import contextlib import io - import verify + from packs import report entry = {"name": "FBASIC30.ROM", "emulator": "XM7", "checks": ["size"]} with contextlib.redirect_stdout(io.StringIO()) as out: - verify._print_undeclared_entry(entry, "MISSING (required)", False, set()) + report._print_undeclared_entry(entry, "MISSING (required)", False, set()) self.assertEqual(out.getvalue().splitlines(), [ " MISSING (required): XM7 needs FBASIC30.ROM", " validates size", @@ -300,20 +302,20 @@ class CoreCopiesWithoutAGapEntryAreCounted(unittest.TestCase): import contextlib import io - import verify + from packs import report for packed, expected in (({"bios": 6, "game_data": 0}, "Core files: 6 in pack"), ({"bios": 0, "game_data": 3}, "Game data: 3 in pack")): out = io.StringIO() with contextlib.redirect_stdout(out): - verify._print_undeclared_section( + report._print_undeclared_section( {"undeclared_files": [], "packed_extras": packed}, verbose=False ) with self.subTest(packed=packed): self.assertIn(expected, out.getvalue()) out = io.StringIO() with contextlib.redirect_stdout(out): - verify._print_undeclared_section( + report._print_undeclared_section( {"undeclared_files": [], "packed_extras": {"bios": 0, "game_data": 0}}, False ) self.assertEqual(out.getvalue(), "") diff --git a/tests/test_verify_pack_choice.py b/tests/test_verify_pack_choice.py index 8db4b7970..9c1ce80e2 100644 --- a/tests/test_verify_pack_choice.py +++ b/tests/test_verify_pack_choice.py @@ -15,6 +15,8 @@ import json import os import tempfile import unittest +import generate_pack +from packs import naming from pathlib import Path from unittest import mock @@ -27,9 +29,7 @@ def _ok_result() -> tuple: class VerifyPackChoice(unittest.TestCase): def setUp(self): - import generate_pack - - self.gp = generate_pack + from packs import naming previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) @@ -38,7 +38,7 @@ class VerifyPackChoice(unittest.TestCase): self.out = Path(self.tmp.name) self.db = self.out / "db.json" self.db.write_text(json.dumps({"files": {}})) - self.stem = generate_pack._platform_pack_stem( + self.stem = naming._platform_pack_stem( ["retroarch"], "retroarch", "platforms" ) @@ -70,7 +70,7 @@ class VerifyPackChoice(unittest.TestCase): self.variants: list[tuple[str, bool]] = [] with mock.patch.object(self.gp, "verify_pack_against_platform", record): - self.gp._run_verify_packs(args) + generate_pack._run_verify_packs(args) return checked def _touch(self, name: str) -> None: @@ -80,7 +80,7 @@ class VerifyPackChoice(unittest.TestCase): from model import region regions = region.parse_requested("us") - tag = self.gp._narrowings("full", regions, None, False, False)[0][0] + tag = naming._narrowings("full", regions, None, False, False)[0][0] self._touch(f"{self.stem}_BIOS_Pack.zip") self._touch(f"{self.stem}{tag}_BIOS_Pack.zip") checked = self._run(self._args(regions=regions)) @@ -104,9 +104,9 @@ class VerifyPackChoice(unittest.TestCase): one missing a file its narrowed list requires passed. Each is now held to the platform's list narrowed the same way.""" names = {} - for source, required in self.gp.ALL_VARIANTS: + for source, required in generate_pack.ALL_VARIANTS: tags = "".join( - tag for tag, _ in self.gp._narrowings(source, None, None, False, required) + tag for tag, _ in naming._narrowings(source, None, None, False, required) ) names[f"{self.stem}{tags}_BIOS_Pack.zip"] = (source, required) self._touch(f"{self.stem}{tags}_BIOS_Pack.zip") @@ -121,7 +121,7 @@ class VerifyPackChoice(unittest.TestCase): import contextlib import io - bizhawk = self.gp._platform_pack_stem(["bizhawk"], "bizhawk", "platforms") + bizhawk = naming._platform_pack_stem(["bizhawk"], "bizhawk", "platforms") self._touch(f"{bizhawk}_BIOS_Pack.zip") self._touch(f"{self.stem}_BIOS_Pack.zip") for platform, target in (("bizhawk", "rpi4typo"), ("retroarch", "swich")): @@ -147,7 +147,7 @@ class VerifyPackChoice(unittest.TestCase): return_value=failed), \ contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ self.assertRaises(SystemExit): - self.gp._run_verify_packs(self._args()) + generate_pack._run_verify_packs(self._args()) self.assertEqual( err.getvalue().strip().splitlines()[-1], f"ERROR: packs failed verification: retroarch ({pack})", @@ -161,7 +161,7 @@ class VerifyPackChoice(unittest.TestCase): """--all checks the packs a release publishes (release_pack): the RetroPie pack, served by the installer, is left to a check that names it.""" - stem = self.gp._platform_pack_stem(["retropie"], "retropie", "platforms") + stem = naming._platform_pack_stem(["retropie"], "retropie", "platforms") self._touch(f"{stem}_BIOS_Pack.zip") self._touch(f"{self.stem}_BIOS_Pack.zip") checked = self._run( @@ -176,6 +176,9 @@ class VerifyPackChoice(unittest.TestCase): class GroupRenameKeepsSystemTag(unittest.TestCase): def test_single_system_pack_does_not_take_the_full_name(self): import generate_pack as gp + from packs import finalize + from packs import naming + from packs import platformpack previous = os.getcwd() os.chdir(REPO_ROOT) @@ -184,7 +187,7 @@ class GroupRenameKeepsSystemTag(unittest.TestCase): def fake_generate(*a, pack_name=None, **kw): # The group's name is handed in: nothing is renamed afterwards. built = Path(tmp) / ( - pack_name or f"RetroArch_x_BIOS_Pack{gp._system_tag(['atari-lynx'])}.zip" + pack_name or f"RetroArch_x_BIOS_Pack{naming._system_tag(['atari-lynx'])}.zip" ) built.write_bytes(b"") return str(built) @@ -196,14 +199,14 @@ class GroupRenameKeepsSystemTag(unittest.TestCase): one_per_slot=False, offline=True, bios_dir="bios", output_dir=tmp, ) - with mock.patch.object(gp, "generate_pack", fake_generate), \ - mock.patch.object(gp, "verify_and_finalize_packs", return_value=True): + with mock.patch.object(platformpack, "generate_pack", fake_generate), \ + mock.patch.object(finalize, "verify_and_finalize_packs", return_value=True): gp._run_platform_packs( args, [(["retroarch", "lakka"], "retroarch")], {}, {}, {}, {}, {}, ["atari-lynx"], ) names = os.listdir(tmp) - stem = gp._platform_pack_stem(["retroarch", "lakka"], "retroarch", "platforms") + stem = naming._platform_pack_stem(["retroarch", "lakka"], "retroarch", "platforms") self.assertEqual(names, [f"{stem}_BIOS_Pack_Lynx.zip"]) diff --git a/tests/test_verify_release_asset.py b/tests/test_verify_release_asset.py index d29bd85f8..720ec675a 100644 --- a/tests/test_verify_release_asset.py +++ b/tests/test_verify_release_asset.py @@ -26,9 +26,13 @@ import yaml from model.platforms import _platform_config_cache from model.profiles import _emulator_profiles_cache import generate_db -import generate_pack as builder -import packresolve -from verify import Status, verify_emulator, verify_platform +from packs import archive +from packs import emulatorpack +from packs import platformpack +from resolve import packfiles as packresolve +from packs.verdicts import Status +from packs.emulatorcheck import verify_emulator +from packs.coverage import verify_platform REPO_ROOT = Path(__file__).resolve().parent.parent @@ -111,7 +115,7 @@ class ReleaseAssetNotCached(unittest.TestCase): with mock.patch.object( packresolve, "fetch_large_file", return_value=str(cache) ): - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "big", "platforms", self.db, "bios", "out", emulators_dir="emulators", emu_profiles={}, offline=False, ) @@ -157,7 +161,7 @@ class CoreExtraReleaseAssetNotCached(ReleaseAssetNotCached): with mock.patch.object( packresolve, "fetch_large_file", return_value=str(cache) ): - zip_path = builder.generate_pack( + zip_path = platformpack.generate_pack( "big", "platforms", self.db, "bios", "out", emulators_dir="emulators", emu_profiles=self.profiles, offline=False, ) @@ -225,11 +229,11 @@ class EmulatorReleaseAssetNotCached(ReleaseAssetNotCached): cache = Path("cache/big.bin") cache.parent.mkdir() cache.write_bytes(PAYLOAD) - record = builder.PackRecord() + record = archive.PackRecord() with mock.patch.object( packresolve, "fetch_large_file", return_value=str(cache) ): - builder.generate_emulator_pack( + emulatorpack.generate_emulator_pack( ["bigcore"], "emulators", self.db, "bios", "out", offline=False, platforms_dir="platforms", record=record, ) diff --git a/tests/test_zipped_member.py b/tests/test_zipped_member.py index 32dc94b9c..54c498e1f 100644 --- a/tests/test_zipped_member.py +++ b/tests/test_zipped_member.py @@ -17,7 +17,7 @@ from pathlib import Path import yaml from core.ziptools import build_zip_contents_index -from generate_pack import generate_pack +from packs.platformpack import generate_pack REPO_ROOT = Path(__file__).resolve().parent.parent