From a60ec786b6eeebfd343037ebabdb2769d5b735d6 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:15:00 +0100 Subject: [PATCH] refactor: move the games commands into games/ --- scripts/game_rules.py | 217 +-------- scripts/games/__init__.py | 2 +- scripts/games/arcadesets.py | 18 + scripts/games/changes.py | 48 ++ scripts/games/coverage.py | 43 ++ scripts/games/fallback.py | 125 +++++ scripts/games/folders.py | 98 ++++ scripts/games/headerreaders.py | 32 ++ scripts/games/inputs.py | 45 ++ scripts/games/profileindex.py | 100 ++++ scripts/games/publish.py | 23 + scripts/games/render.py | 75 +++ scripts/games/rulecheck.py | 125 +++++ scripts/games/rulesummary.py | 21 + scripts/games/setups.py | 125 +++++ scripts/games/systems.py | 112 +++++ scripts/generate_games_index.py | 692 +--------------------------- tests/sources.py | 7 + tests/test_game_regions.py | 34 +- tests/test_games_index.py | 56 ++- tests/test_layers.py | 1 + tests/test_optional_dependencies.py | 2 +- wiki/architecture.md | 1 + wiki/tools.md | 1 + 24 files changed, 1062 insertions(+), 941 deletions(-) create mode 100644 scripts/games/arcadesets.py create mode 100644 scripts/games/changes.py create mode 100644 scripts/games/coverage.py create mode 100644 scripts/games/fallback.py create mode 100644 scripts/games/folders.py create mode 100644 scripts/games/headerreaders.py create mode 100644 scripts/games/inputs.py create mode 100644 scripts/games/profileindex.py create mode 100644 scripts/games/publish.py create mode 100644 scripts/games/render.py create mode 100644 scripts/games/rulecheck.py create mode 100644 scripts/games/rulesummary.py create mode 100644 scripts/games/setups.py create mode 100644 scripts/games/systems.py diff --git a/scripts/game_rules.py b/scripts/game_rules.py index 8fc103e4c..aa2dd4b4b 100644 --- a/scripts/game_rules.py +++ b/scripts/game_rules.py @@ -15,224 +15,13 @@ from __future__ import annotations import argparse import json -import re -from dataclasses import dataclass from pathlib import Path from core.cli import add_repo_inputs +from games.inputs import EXTRAS_FILE, HEADERS_FILE, REGIONS_FILE, load_yaml +from games.rulecheck import check +from games.rulesummary import summary from model.profiles import load_emulator_profiles -from model.region import REGIONS, normalize_declared -from model.sources import source_yaml_file - -REGIONS_FILE = Path("games") / "regions.yml" -EXTRAS_FILE = Path("games") / "extras.yml" -HEADERS_FILE = Path("games") / "headers.yml" - -_REF_REPO = re.compile(r"(?:^|; )([\w.-]+/[\w.-]+)@([0-9a-f]{8,40}) ") - - -def load_yaml(path: Path) -> dict: - return source_yaml_file(path) or {} - - -def profile_pins(profile: dict) -> set[str]: - """Every commit a profile is pinned to, a build-mode dict included.""" - pins: set[str] = set() - for key in ("source_commit", "upstream_commit"): - value = profile.get(key) - values = value.values() if isinstance(value, dict) else [value] - pins.update(str(v) for v in values if v) - return pins - - -def declared_names(profile: dict) -> set[str]: - """The names and aliases a profile's files answer to.""" - names: set[str] = set() - for entry in profile.get("files") or []: - if isinstance(entry, dict) and entry.get("name"): - names.add(str(entry["name"])) - names.update(str(a) for a in entry.get("aliases") or []) - return names - - -def tagged_regions(profile: dict, name: str) -> set[str]: - """The regions a profile tags a file with, over all its declarations.""" - out: set[str] = set() - for entry in profile.get("files") or []: - if isinstance(entry, dict) and ( - entry.get("name") == name or name in (entry.get("aliases") or []) - ): - out |= normalize_declared(entry.get("region")) - return out - - -def every_tag(profile: dict) -> set[str]: - return { - region - for entry in profile.get("files") or [] - if isinstance(entry, dict) - for region in normalize_declared(entry.get("region")) - } - - -def header_readers(headers: dict) -> dict[str, dict]: - """Every reader of games/headers.yml by id, over all its systems.""" - readers: dict[str, dict] = {} - for system in (headers.get("systems") or {}).values(): - readers.update(system.get("readers") or {}) - return readers - - -def reader_answers(reader: dict, field: str | None = None) -> set[object] | None: - """The labels and values a reader can return, None when any string can - be (a serial or product id read as it stands).""" - if field: - spec = (reader.get("fields") or {}).get(field) or {} - return {v for k, v in spec.items() if k not in ("encoding",) and isinstance(v, str)} - decode = reader.get("decode") or {} - if decode.get("kind") == "serial": - return None - answers: set[object] = set() - for row in decode.get("values") or []: - answers.update(row[k] for k in ("value", "label") if k in row) - for key in ("then", "otherwise"): - branch = decode.get(key) - if isinstance(branch, dict) and "label" in branch: - answers.add(branch["label"]) - elif isinstance(branch, str): - answers.add(branch) - return answers - - -@dataclass -class Checker: - profiles: dict[str, dict] - readers: dict[str, dict] | None = None - - def __post_init__(self) -> None: - self.errors: list[str] = [] - - def _profile(self, where: str, name: str, system: str) -> dict | None: - profile = self.profiles.get(name) - if profile is None: - self.errors.append(f"{where}: no profile {name}") - return None - if system not in (profile.get("systems") or []): - self.errors.append(f"{where}: {name} does not declare system {system}") - return profile - - def _files(self, where: str, name: str, profile: dict, files: list[str]) -> None: - known = declared_names(profile) - for file in files: - if file not in known: - self.errors.append(f"{where}: {name} declares no file {file}") - - def _region(self, where: str, value: str) -> None: - if value not in REGIONS: - self.errors.append(f"{where}: unknown region {value}") - - def _ref(self, where: str, profile: dict, ref: str | None) -> None: - if not ref: - self.errors.append(f"{where}: no source_ref") - return - pins = profile_pins(profile) - cited = _REF_REPO.findall(ref) - if not cited: - self.errors.append(f"{where}: source_ref names no owner/repo@sha") - for repo, sha in cited: - if not any(pin.startswith(sha) for pin in pins): - self.errors.append(f"{where}: {repo}@{sha} is not a pin of the profile") - - def regions(self, doc: dict) -> None: - cases = doc.get("cases") or {} - for system, cores in (doc.get("systems") or {}).items(): - for name, rule in cores.items(): - where = f"regions {system}/{name}" - profile = self._profile(where, name, system) - if profile is None: - continue - self._ref(where, profile, rule.get("source_ref")) - tags = every_tag(profile) - for src, dst in (rule.get("routes") or {}).items(): - self._region(where, src) - self._region(where, dst) - if dst not in tags: - self.errors.append(f"{where}: route {src} -> {dst}, but no file is tagged {dst}") - for value in [rule.get("default_region"), *(rule.get("preference") or [])]: - if value: - self._region(where, value) - free = rule.get("region_free") or [] - self._files(where, name, profile, free) - for file in free: - specific = tagged_regions(profile, file) - {"world"} - if specific: - self.errors.append( - f"{where}: region_free {file} is tagged {sorted(specific)} in the profile" - ) - for keep in rule.get("keep_all_regions") or []: - kwhere = f"{where} case {keep.get('case')}" - if keep.get("case") not in cases: - self.errors.append(f"{kwhere}: case not described under cases") - self._ref(kwhere, profile, keep.get("source_ref")) - self._files(kwhere, name, profile, keep.get("files") or []) - - def extras(self, doc: dict) -> None: - for index, entry in enumerate(doc.get("extras") or []): - where = f"extras[{index}] {entry.get('system')}/{entry.get('profile')}" - profile = self._profile(where, entry["profile"], entry["system"]) - if profile is None: - continue - self._ref(where, profile, entry.get("source_ref")) - self._files(where, entry["profile"], profile, entry.get("files") or []) - header = (entry.get("trigger") or {}).get("header") - if header and self.readers is not None: - self._header(where, header, self.readers) - - def _header(self, where: str, header: dict, readers: dict[str, dict]) -> None: - reader = readers.get(header["reader"]) - if reader is None: - self.errors.append(f"{where}: games/headers.yml has no reader {header['reader']}") - return - field = header.get("field") - if field and field not in (reader.get("fields") or {}): - self.errors.append(f"{where}: reader {header['reader']} has no field {field}") - return - answers = reader_answers(reader, field) - if answers is None: - return - for value in header.get("values") or []: - if value not in answers: - self.errors.append( - f"{where}: reader {header['reader']} never returns {value!r}" - ) - - -def check( - regions: dict, extras: dict, profiles: dict[str, dict], headers: dict | None = None -) -> list[str]: - """Errors over both files. Without headers, header triggers go unchecked.""" - checker = Checker(profiles, header_readers(headers) if headers is not None else None) - checker.regions(regions) - checker.extras(extras) - return checker.errors - - -def summary(regions: dict, extras: dict) -> dict: - keeps = [ - {"case": keep["case"], "system": system, "profile": name, "condition": keep["condition"]} - for system, cores in sorted((regions.get("systems") or {}).items()) - for name, rule in sorted(cores.items()) - for keep in rule.get("keep_all_regions") or [] - ] - systems = regions.get("systems") or {} - return { - "region_systems": len(systems), - "region_cores": sum(len(c) for c in systems.values()), - "cases": sorted(regions.get("cases") or {}), - "case_entries": keeps, - "extras": len(extras.get("extras") or []), - "extra_systems": sorted({e["system"] for e in extras.get("extras") or []}), - } def main() -> int: diff --git a/scripts/games/__init__.py b/scripts/games/__init__.py index e3fa9e36a..8b43abb54 100644 --- a/scripts/games/__init__.py +++ b/scripts/games/__init__.py @@ -1 +1 @@ -"""Game catalogs, game rules and the published games index.""" +"""Games on a card: the region and extra-file rules, and the index the installer reads for them.""" diff --git a/scripts/games/arcadesets.py b/scripts/games/arcadesets.py new file mode 100644 index 000000000..d1e05aef8 --- /dev/null +++ b/scripts/games/arcadesets.py @@ -0,0 +1,18 @@ +"""The published arcade documents: each game set's BIOS parent and device sets.""" + +from __future__ import annotations + +from pathlib import Path + +from games.inputs import load_json + + +def build_arcade(directory: Path) -> dict[str, dict]: + if not directory.is_dir(): + return {} + # The driver sources and the clone parents place a search path's sets at + # build time (common.rom_search_sets): the installer reads none of them. + return { + path.stem: {k: v for k, v in load_json(path).items() if k not in ("sources", "parents")} + for path in sorted(directory.glob("*.json")) + } diff --git a/scripts/games/changes.py b/scripts/games/changes.py new file mode 100644 index 000000000..6733c0b02 --- /dev/null +++ b/scripts/games/changes.py @@ -0,0 +1,48 @@ +"""What differs between a published games-index document and the one rendered now.""" + +from __future__ import annotations + +import json + + +def _sample(items: list[str], limit: int = 3) -> str: + shown = ", ".join(items[:limit]) + return f"{shown}, +{len(items) - limit} more" if len(items) > limit else shown + + +def describe_change(old: str | None, new: str) -> list[str]: + """What differs between a published document and the one render() makes. + + The documents are single-line JSON of up to 550 KB: STALE alone left a + diff by hand to find that a manifest gained one file.""" + if old is None: + return ["not written yet"] + try: + before, after = json.loads(old), json.loads(new) + except ValueError: + return ["the published file is not valid JSON"] + if not (isinstance(before, dict) and isinstance(after, dict)): + return ["document changed"] + parts = [] + for key in sorted(set(before) | set(after)): + a, b = before.get(key), after.get(key) + if a == b: + continue + if isinstance(a, list) and isinstance(b, list): + olds = {json.dumps(x, sort_keys=True) for x in a} + news = {json.dumps(x, sort_keys=True) for x in b} + added = sorted(news - olds) + removed = sorted(olds - news) + change = [] + if added: + change.append(f"{len(added)} added ({_sample(added)})") + if removed: + change.append(f"{len(removed)} removed ({_sample(removed)})") + parts.append(f"{key}: {', '.join(change) or 'reordered'}") + elif isinstance(a, dict) and isinstance(b, dict): + changed = sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k)) + parts.append(f"{key}: {len(changed)} changed ({_sample(changed)})") + else: + parts.append(f"{key} changed" if key in before and key in after + else f"{key} {'added' if key in after else 'removed'}") + return parts or ["formatting changed"] diff --git a/scripts/games/coverage.py b/scripts/games/coverage.py new file mode 100644 index 000000000..69135899e --- /dev/null +++ b/scripts/games/coverage.py @@ -0,0 +1,43 @@ +"""The coverage of the games index: the floors it may not fall below and its printed table.""" + +from __future__ import annotations + +import gzip +from pathlib import Path + +# Coverage the published data may not fall below. A rescrape or a DAT import +# that loses rows fails the step instead of shipping a thinner index. +FLOORS = { + "folders_resolved_share": 0.84, + "catalog_systems": 30, + "arcade_profiles": 6, +} + + +def floor_failures(coverage: dict) -> list[str]: + total = sum(c["folders"] for c in coverage["setups"].values()) + resolved = sum(c["resolved"] for c in coverage["setups"].values()) + out = [] + share = resolved / total if total else 0.0 + if share < FLOORS["folders_resolved_share"]: + out.append(f"folders resolved {resolved}/{total} ({share:.1%}) under {FLOORS['folders_resolved_share']:.0%}") + catalogs = sum(1 for c in coverage["systems"].values() if c["games"]) + if catalogs < FLOORS["catalog_systems"]: + out.append(f"systems with a game catalog {catalogs} under {FLOORS['catalog_systems']}") + if len(coverage["arcade"]) < FLOORS["arcade_profiles"]: + out.append(f"arcade profiles {len(coverage['arcade'])} under {FLOORS['arcade_profiles']}") + return out + + +def print_coverage(coverage: dict, files: dict[Path, str]) -> None: + print("Setups (folders / resolved to a system / default core profiled / with a fallback set):") + for setup, c in coverage["setups"].items(): + print(f" {setup:16} {c['folders']:4} {c['resolved']:4} {c['profile']:4} {c['fallback']:4}") + print("Systems (games by hash / serials / header readers / profiles with region files / extras):") + for system, c in coverage["systems"].items(): + print(f" {system:28} {c['games']:6} {c['serials']:6} {c['header_readers']:3} " + f"{c['region_profiles']:3} {'yes' if c['extras'] else '-'}") + print(f"Arcade indexes: {', '.join(coverage['arcade']) or 'none'}") + raw = sum(len(t.encode()) for t in files.values()) + packed = sum(len(gzip.compress(t.encode(), 9, mtime=0)) for t in files.values()) + print(f"{len(files)} files, {raw:,} bytes, {packed:,} bytes gzip") diff --git a/scripts/games/fallback.py b/scripts/games/fallback.py new file mode 100644 index 000000000..fda4e9b38 --- /dev/null +++ b/scripts/games/fallback.py @@ -0,0 +1,125 @@ +"""The fallback sets: per system and default core, the install-list files an unrecognised game keeps.""" + +from __future__ import annotations + +import posixpath +from dataclasses import dataclass, field +from pathlib import Path + +from games.inputs import FORMAT_VERSION +from games.profileindex import Profiles +from model.platforms import load_platform_config, native_layer + +import install + + +def platform_required(platform: str, platforms_dir: str) -> dict[tuple[str, str], bool]: + """(system, file name) -> required, as the platform's own list declares it.""" + config = load_platform_config(platform, platforms_dir) + out: dict[tuple[str, str], bool] = {} + for sys_id, system in (native_layer(config) or config).get("systems", {}).items(): + for entry in system.get("files", []): + for name in {entry.get("name"), Path(str(entry.get("destination") or "")).name} - {None, ""}: + out[(sys_id, str(name).lower())] = entry.get("required") is not False + return out + + +def narrowed(manifest: dict, cores: list[str], cache: dict) -> list[tuple[dict, str]]: + """The install list under some cores, each file with its lowercased + base name. The answer depends on the cores alone, and a platform asks + it once per system they run.""" + key = (id(manifest), tuple(cores)) + if key not in cache: + files, _omitted = install.narrow( + manifest["files"], manifest.get("omitted_files", []), [], cores, []) + cache[key] = [(entry, posixpath.basename(entry["dest"]).lower()) for entry in files] + return cache[key] + + +def fallback_set( + manifest: dict, + platform_required: dict[tuple[str, str], bool], + profiles: Profiles, + system: str, + profile: str | None, + narrowed_cache: dict | None = None, +) -> dict: + """The files an unrecognised game of one system keeps on one platform. + + The platform's own files for the system, plus what the default core's + profile reads for it. The core step is the installer's own narrowing + (`install.narrow` with the designated cores). A core file the list does + not attribute to a platform system is kept when the profile entry that + declares it serves the system. + """ + wanted = profiles.resolver.equivalents(system) + cores = sorted(install.designated_cores(manifest, [profile])) if profile else [] + rows: list[list] = [] + for entry, base in narrowed(manifest, cores, {} if narrowed_cache is None else narrowed_cache): + systems = set(entry.get("systems") or []) + dest = entry["dest"] + if entry.get("cores") is None: + if not systems & wanted: + continue + required = any( + platform_required.get((s, base), True) for s in systems & wanted + ) + else: + if systems and not systems & wanted: + continue + declared = profiles.entries_named(profile or "", base) + if not systems and not any(profiles.serves(profile or "", e, system) for e in declared): + continue + required = any(e.get("required") is not False for e in declared) if declared else True + rows.append([dest, int(entry["size"]), required, entry.get("category") or "bios"]) + rows.sort() + return { + "files": rows, + "bytes": sum(r[1] for r in rows), + "required_bytes": sum(r[1] for r in rows if r[2]), + } + + +def shared_table(platform: str, sets: dict[str, dict]) -> dict: + """One row per install-list file, and each set as indices into it. + + The sets of the MAME-run systems hold the same thousand files: written + out per set, Batocera's table weighed half a megabyte compressed. + """ + rows = sorted({(r[0], r[1], r[3]) for body in sets.values() for r in body["files"]}) + position = {row: i for i, row in enumerate(rows)} + published = {} + for key, body in sorted(sets.items()): + published[key] = { + "files": [position[(r[0], r[1], r[3])] for r in body["files"]], + "optional": [position[(r[0], r[1], r[3])] for r in body["files"] if not r[2]], + "bytes": body["bytes"], + "required_bytes": body["required_bytes"], + } + return { + "format_version": FORMAT_VERSION, + "platform": platform, + "files": [list(r) for r in rows], + "sets": published, + } + + +@dataclass +class FallbackTables: + """The fallback sets of a folder's systems under one core, computed + once per platform.""" + + profiles: Profiles + tables: dict[str, dict[str, dict]] = field(default_factory=dict) + narrowed: dict = field(default_factory=dict) + + def keys(self, platform: str, manifest: dict, required: dict[tuple[str, str], bool], + systems: list[str], chosen: str | None) -> list[str]: + keys = [] + table = self.tables.setdefault(platform, {}) + for system in systems: + key = f"{system}|{chosen or ''}" + if key not in table: + table[key] = fallback_set(manifest, required, self.profiles, system, chosen, self.narrowed) + keys.append(key) + return keys diff --git a/scripts/games/folders.py b/scripts/games/folders.py new file mode 100644 index 000000000..e2cc74f10 --- /dev/null +++ b/scripts/games/folders.py @@ -0,0 +1,98 @@ +"""A rom folder resolved to the systems it holds and the profile of the program that runs it.""" + +from __future__ import annotations + +from pathlib import Path + +from games.profileindex import Profiles +from model.romfolders import ProfileResolver, Resolution, SystemResolver, folder_names + + +def arcade_profiles(directory: Path) -> set[str]: + return {p.stem for p in directory.glob("*.json")} if directory.is_dir() else set() + + +def resolve_folder( + row: dict, platform: str, profile: str | None, resolver: SystemResolver, profiles: Profiles, + arcade: frozenset[str] | set[str] = frozenset(), +) -> Resolution: + """The systems a folder holds: its names first, else its core's machines. + + A name nothing spells, run by a core of one machine, is that machine + (ECWolf's wolf3d folder, a port's own folder). Run by a core of several, + its games are one of them (theodore's thomson folder), and every one + is kept: left empty, the folder had no fallback and its games got no file. + An arcade core is the exception: the arcade index names each set's + files, and its hundred machines would make any unknown file a fallback + for all of them. + + A name that spells a machine its core does not run adds the core's + machines to it: the games run on that core. Mednafen's PC Engine core + lists nec-pc-engine, the CD folder resolved to nec-pc-engine-cd alone, + and an unrecognised CD game got no System Card. + """ + resolution = resolver.resolve(folder_names(row), platform) + own = [str(s) for s in profiles.profiles.get(profile or "", {}).get("systems") or []] + if resolution.systems and own and profile not in arcade: + runs = {sid for s in own for sid in resolver.equivalents(s)} + if not runs & set(resolution.systems): + systems = set(resolution.systems) | {resolver.canonical(s) for s in own} + return Resolution(sorted(systems), f"{resolution.basis}, and systems of {profile}") + if resolution.systems or not own: + return resolution + if len(own) == 1: + return Resolution([resolver.canonical(own[0])], f"only system of {profile}") + if profile in arcade: + return resolution + return Resolution(sorted({resolver.canonical(s) for s in own}), f"systems of {profile}") + + +# The emulator column of a row names the frontend or a launch mode, never +# a program whose files are read: these never answer for a core. +_NOT_PROGRAMS = frozenset({"retroarch", "retroarch32", "libretro", "external", "standalone", + "port", "ports", "native", "sh", "os-shell", "none"}) + + +def emulator_profile(row: dict, platform: str, cores: ProfileResolver, + resolver: SystemResolver, profiles: Profiles) -> str | None: + """The profile of the program a row's emulator column names, when its + core column names a mode, a machine or a plugin of that program: RetroBat + runs demul for core hikaru, AmberELEC MAME for core gamate, Batocera + mupen64plus for core glide64mk2. + + Kept only when that profile declares a system of the folder: MAME's + profile has no GameKing, and answering MAME for its folder would leave + out the ROM the core needs. Unresolved, the folder keeps the files of + every core of its systems, as it did. + """ + emulator = str(row.get("emulator") or "").strip() + if not emulator or emulator.lower() in _NOT_PROGRAMS or emulator.lower().startswith("standalone"): + return None + candidate = cores.resolve(emulator) + if not candidate: + return None + systems = resolver.resolve(folder_names(row), platform).systems + own = {str(s) for s in profiles.profiles.get(candidate, {}).get("systems") or []} + declared = {spelling for sid in own for spelling in resolver.equivalents(sid)} + return candidate if any(resolver.equivalents(sid) & declared for sid in systems) else None + + +def folder_systems(setups: dict[str, dict]) -> dict[str, list[str]]: + """Every folder name a setup gives a system, casefolded, with the systems + any setup reads there, and each system id under its own name. + + What a games folder on a computer is read with when its setup names no + folder of its own (RetroArch): a name two setups give two systems keeps + both. + """ + names: dict[str, set[str]] = {} + for doc in setups.values(): + for row in doc["folders"]: + systems = row["systems"] + if not systems: + continue + for name in [row["folder"], *(row.get("aliases") or [])]: + names.setdefault(str(name).casefold(), set()).update(systems) + for system in systems: + names.setdefault(system.casefold(), set()).add(system) + return {name: sorted(systems) for name, systems in sorted(names.items())} diff --git a/scripts/games/headerreaders.py b/scripts/games/headerreaders.py new file mode 100644 index 000000000..7216fb862 --- /dev/null +++ b/scripts/games/headerreaders.py @@ -0,0 +1,32 @@ +"""The readers of games/headers.yml and the values each can return.""" + +from __future__ import annotations + + +def header_readers(headers: dict) -> dict[str, dict]: + """Every reader of games/headers.yml by id, over all its systems.""" + readers: dict[str, dict] = {} + for system in (headers.get("systems") or {}).values(): + readers.update(system.get("readers") or {}) + return readers + + +def reader_answers(reader: dict, field: str | None = None) -> set[object] | None: + """The labels and values a reader can return, None when any string can + be (a serial or product id read as it stands).""" + if field: + spec = (reader.get("fields") or {}).get(field) or {} + return {v for k, v in spec.items() if k not in ("encoding",) and isinstance(v, str)} + decode = reader.get("decode") or {} + if decode.get("kind") == "serial": + return None + answers: set[object] = set() + for row in decode.get("values") or []: + answers.update(row[k] for k in ("value", "label") if k in row) + for key in ("then", "otherwise"): + branch = decode.get(key) + if isinstance(branch, dict) and "label" in branch: + answers.add(branch["label"]) + elif isinstance(branch, str): + answers.add(branch) + return answers diff --git a/scripts/games/inputs.py b/scripts/games/inputs.py new file mode 100644 index 000000000..5a8b8fda9 --- /dev/null +++ b/scripts/games/inputs.py @@ -0,0 +1,45 @@ +"""Where the games data is read from, and how its YAML and JSON files are loaded.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path + +from core.paths import EMULATORS_DIR, PLATFORMS_DIR +from model.sources import source_yaml_file + +FORMAT_VERSION = 1 +OUTPUT = Path("install") / "games" +GAMES = Path("games") + +REGIONS_FILE = GAMES / "regions.yml" +EXTRAS_FILE = GAMES / "extras.yml" +HEADERS_FILE = GAMES / "headers.yml" + + +@dataclass(frozen=True) +class Inputs: + """Where each source is read from. The defaults are the repository's.""" + + games: Path = GAMES + romfolders: Path = Path("platforms") / "romfolders" + install: Path = Path("install") + emulators: str = EMULATORS_DIR + platforms: str = PLATFORMS_DIR + + +def load_yaml(path: Path) -> dict: + return source_yaml_file(path) or {} + + +def load_optional_yaml(path: Path) -> dict: + """A YAML file of the games data, empty when it does not exist.""" + if not path.exists(): + return {} + return load_yaml(path) + + +def load_json(path: Path) -> dict: + with path.open(encoding="utf-8") as handle: + return json.load(handle) diff --git a/scripts/games/profileindex.py b/scripts/games/profileindex.py new file mode 100644 index 000000000..59a1069bf --- /dev/null +++ b/scripts/games/profileindex.py @@ -0,0 +1,100 @@ +"""What a profile declares, looked up for the game rules and the games index.""" + +from __future__ import annotations + +from pathlib import Path + +from model.profiles import entry_system_ids +from model.region import normalize_declared +from model.romfolders import SystemResolver + + +def profile_pins(profile: dict) -> set[str]: + """Every commit a profile is pinned to, a build-mode dict included.""" + pins: set[str] = set() + for key in ("source_commit", "upstream_commit"): + value = profile.get(key) + values = value.values() if isinstance(value, dict) else [value] + pins.update(str(v) for v in values if v) + return pins + + +def declared_names(profile: dict) -> set[str]: + """The names and aliases a profile's files answer to.""" + names: set[str] = set() + for entry in profile.get("files") or []: + if isinstance(entry, dict) and entry.get("name"): + names.add(str(entry["name"])) + names.update(str(a) for a in entry.get("aliases") or []) + return names + + +def tagged_regions(profile: dict, name: str) -> set[str]: + """The regions a profile tags a file with, over all its declarations.""" + out: set[str] = set() + for entry in profile.get("files") or []: + if isinstance(entry, dict) and ( + entry.get("name") == name or name in (entry.get("aliases") or []) + ): + out |= normalize_declared(entry.get("region")) + return out + + +def every_tag(profile: dict) -> set[str]: + return { + region + for entry in profile.get("files") or [] + if isinstance(entry, dict) + for region in normalize_declared(entry.get("region")) + } + + +def _entry_names(entry: dict) -> set[str]: + names = {str(entry.get("name") or "")} + names |= {str(a) for a in entry.get("aliases") or []} + for key in ("path", "standalone_path", "destination"): + if entry.get(key): + names.add(Path(str(entry[key])).name) + return {n.lower() for n in names if n} + + +class Profiles: + """Profile lookups the fallback and region sections share.""" + + def __init__(self, profiles: dict[str, dict], resolver: SystemResolver) -> None: + self.profiles = profiles + self.resolver = resolver + self._by_name: dict[str, dict[str, list[dict]]] = {} + + def entries_named(self, profile: str, name: str) -> list[dict]: + table = self._by_name.get(profile) + if table is None: + table = {} + for entry in self.profiles.get(profile, {}).get("files") or []: + if isinstance(entry, dict): + for n in _entry_names(entry): + table.setdefault(n, []).append(entry) + self._by_name[profile] = table + return table.get(name.lower(), []) + + def serves(self, profile: str, entry: dict, system: str) -> bool: + wanted = self.resolver.equivalents(system) + return bool(set(entry_system_ids(entry, self.profiles.get(profile, {}))) & wanted) + + def region_files(self, profile: str, system: str) -> dict[str, list[str]]: + """Region slug -> file names the profile tags for it, for one system. + + `any` holds the files declared with no region: those are installed + whatever the game's region. + """ + out: dict[str, set[str]] = {} + data = self.profiles.get(profile, {}) + for entry in data.get("files") or []: + if not isinstance(entry, dict) or not self.serves(profile, entry, system): + continue + if entry.get("category") == "game_data": + continue + regions = normalize_declared(entry.get("region")) or {"any"} + for region in regions: + out.setdefault(region, set()).add(str(entry["name"])) + return {k: sorted(v) for k, v in sorted(out.items())} diff --git a/scripts/games/publish.py b/scripts/games/publish.py new file mode 100644 index 000000000..cb54db115 --- /dev/null +++ b/scripts/games/publish.py @@ -0,0 +1,23 @@ +"""The rendered games index compared with install/games/ on disk, and written there.""" + +from __future__ import annotations + +from pathlib import Path + +from core.artifacts import write_text_atomic + + +def pending(files: dict[Path, str], output: Path) -> tuple[list[Path], list[Path]]: + """(files whose text would change, published files no longer generated).""" + stale = sorted(p for p in output.rglob("*.json") if p not in files) if output.is_dir() else [] + changed = [p for p, t in files.items() if not p.exists() or p.read_text(encoding="utf-8") != t] + return changed, stale + + +def write(files: dict[Path, str], changed: list[Path], stale: list[Path]) -> None: + """Remove the stale files and write the changed ones.""" + for path in stale: + path.unlink() + for path in changed: + path.parent.mkdir(parents=True, exist_ok=True) + write_text_atomic(str(path), files[path]) diff --git a/scripts/games/render.py b/scripts/games/render.py new file mode 100644 index 000000000..723c49b5d --- /dev/null +++ b/scripts/games/render.py @@ -0,0 +1,75 @@ +"""Every file of install/games/ rendered to its text, with index.json and the coverage.""" + +from __future__ import annotations + +import gzip +import hashlib +import json +from pathlib import Path + +from games.arcadesets import build_arcade +from games.folders import folder_systems +from games.inputs import FORMAT_VERSION, OUTPUT, Inputs, load_optional_yaml +from games.profileindex import Profiles +from games.setups import build_setups +from games.systems import build_systems +from model.profiles import load_emulator_profiles +from model.romfolders import ProfileResolver, SystemResolver, load_setups + + +def dumps(document: object) -> str: + return json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n" + + +def _entry(text: str) -> dict: + data = text.encode("utf-8") + return { + "size": len(data), + "gzip_size": len(gzip.compress(data, compresslevel=9, mtime=0)), + "sha256": hashlib.sha256(data).hexdigest(), + } + + +def render(output: Path = OUTPUT, inputs: Inputs | None = None) -> tuple[dict[Path, str], dict]: + """Every published file's text, keyed by its path, and the coverage.""" + inputs = inputs or Inputs() + resolver = SystemResolver.from_repo(inputs.emulators, inputs.platforms) + profiles = Profiles(load_emulator_profiles(inputs.emulators), resolver) + arcade = build_arcade(inputs.games / "arcade") + setups, fallbacks, setup_cov = build_setups( + load_setups(inputs.romfolders), resolver, ProfileResolver.from_repo(inputs.emulators), + profiles, set(arcade), inputs, + ) + used: dict[str, set[str]] = {} + for doc in setups.values(): + for row in doc["folders"]: + for system in row["systems"]: + if row.get("profile"): + used.setdefault(system, set()).add(row["profile"]) + systems, system_cov = build_systems(resolver, profiles, used, inputs.games) + + files: dict[Path, str] = {} + index: dict = {"format_version": FORMAT_VERSION, "setups": {}, "fallback": {}, "systems": {}, "arcade": {}} + for kind, docs in (("setups", setups), ("fallback", fallbacks), ("systems", systems), ("arcade", arcade)): + for key, doc in sorted(docs.items()): + rel = Path(kind) / f"{key}.json" + text = dumps(doc) + files[output / rel] = text + index[kind][key] = {"file": rel.as_posix(), **_entry(text)} + digest = hashlib.sha256( + "".join(f"{p.relative_to(output).as_posix()} {_entry(t)['sha256']}\n" for p, t in sorted(files.items())).encode() + ).hexdigest() + index["data_version"] = digest[:16] + index["licences"] = sorted( + {json.dumps(src.get("licence"), sort_keys=True) + for doc in systems.values() for src in doc.get("identify", {}).get("sources", []) + if src.get("licence")} + ) + index["licences"] = [json.loads(x) for x in index["licences"]] + containers = load_optional_yaml(inputs.games / "headers.yml").get("containers") + if containers: + index["containers"] = containers + index["folders"] = folder_systems(setups) + files[output / "index.json"] = dumps(index) + coverage = {"setups": setup_cov, "systems": system_cov, "arcade": sorted(arcade)} + return files, coverage diff --git a/scripts/games/rulecheck.py b/scripts/games/rulecheck.py new file mode 100644 index 000000000..54244ad72 --- /dev/null +++ b/scripts/games/rulecheck.py @@ -0,0 +1,125 @@ +"""The checks of games/regions.yml and games/extras.yml against the profiles and the header readers.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +from games.headerreaders import header_readers, reader_answers +from games.profileindex import declared_names, every_tag, profile_pins, tagged_regions +from model.region import REGIONS + +_REF_REPO = re.compile(r"(?:^|; )([\w.-]+/[\w.-]+)@([0-9a-f]{8,40}) ") + + +@dataclass +class Checker: + profiles: dict[str, dict] + readers: dict[str, dict] | None = None + + def __post_init__(self) -> None: + self.errors: list[str] = [] + + def _profile(self, where: str, name: str, system: str) -> dict | None: + profile = self.profiles.get(name) + if profile is None: + self.errors.append(f"{where}: no profile {name}") + return None + if system not in (profile.get("systems") or []): + self.errors.append(f"{where}: {name} does not declare system {system}") + return profile + + def _files(self, where: str, name: str, profile: dict, files: list[str]) -> None: + known = declared_names(profile) + for file in files: + if file not in known: + self.errors.append(f"{where}: {name} declares no file {file}") + + def _region(self, where: str, value: str) -> None: + if value not in REGIONS: + self.errors.append(f"{where}: unknown region {value}") + + def _ref(self, where: str, profile: dict, ref: str | None) -> None: + if not ref: + self.errors.append(f"{where}: no source_ref") + return + pins = profile_pins(profile) + cited = _REF_REPO.findall(ref) + if not cited: + self.errors.append(f"{where}: source_ref names no owner/repo@sha") + for repo, sha in cited: + if not any(pin.startswith(sha) for pin in pins): + self.errors.append(f"{where}: {repo}@{sha} is not a pin of the profile") + + def regions(self, doc: dict) -> None: + cases = doc.get("cases") or {} + for system, cores in (doc.get("systems") or {}).items(): + for name, rule in cores.items(): + where = f"regions {system}/{name}" + profile = self._profile(where, name, system) + if profile is None: + continue + self._ref(where, profile, rule.get("source_ref")) + tags = every_tag(profile) + for src, dst in (rule.get("routes") or {}).items(): + self._region(where, src) + self._region(where, dst) + if dst not in tags: + self.errors.append(f"{where}: route {src} -> {dst}, but no file is tagged {dst}") + for value in [rule.get("default_region"), *(rule.get("preference") or [])]: + if value: + self._region(where, value) + free = rule.get("region_free") or [] + self._files(where, name, profile, free) + for file in free: + specific = tagged_regions(profile, file) - {"world"} + if specific: + self.errors.append( + f"{where}: region_free {file} is tagged {sorted(specific)} in the profile" + ) + for keep in rule.get("keep_all_regions") or []: + kwhere = f"{where} case {keep.get('case')}" + if keep.get("case") not in cases: + self.errors.append(f"{kwhere}: case not described under cases") + self._ref(kwhere, profile, keep.get("source_ref")) + self._files(kwhere, name, profile, keep.get("files") or []) + + def extras(self, doc: dict) -> None: + for index, entry in enumerate(doc.get("extras") or []): + where = f"extras[{index}] {entry.get('system')}/{entry.get('profile')}" + profile = self._profile(where, entry["profile"], entry["system"]) + if profile is None: + continue + self._ref(where, profile, entry.get("source_ref")) + self._files(where, entry["profile"], profile, entry.get("files") or []) + header = (entry.get("trigger") or {}).get("header") + if header and self.readers is not None: + self._header(where, header, self.readers) + + def _header(self, where: str, header: dict, readers: dict[str, dict]) -> None: + reader = readers.get(header["reader"]) + if reader is None: + self.errors.append(f"{where}: games/headers.yml has no reader {header['reader']}") + return + field = header.get("field") + if field and field not in (reader.get("fields") or {}): + self.errors.append(f"{where}: reader {header['reader']} has no field {field}") + return + answers = reader_answers(reader, field) + if answers is None: + return + for value in header.get("values") or []: + if value not in answers: + self.errors.append( + f"{where}: reader {header['reader']} never returns {value!r}" + ) + + +def check( + regions: dict, extras: dict, profiles: dict[str, dict], headers: dict | None = None +) -> list[str]: + """Errors over both files. Without headers, header triggers go unchecked.""" + checker = Checker(profiles, header_readers(headers) if headers is not None else None) + checker.regions(regions) + checker.extras(extras) + return checker.errors diff --git a/scripts/games/rulesummary.py b/scripts/games/rulesummary.py new file mode 100644 index 000000000..985237008 --- /dev/null +++ b/scripts/games/rulesummary.py @@ -0,0 +1,21 @@ +"""What games/regions.yml and games/extras.yml hold, counted for a report.""" + +from __future__ import annotations + + +def summary(regions: dict, extras: dict) -> dict: + keeps = [ + {"case": keep["case"], "system": system, "profile": name, "condition": keep["condition"]} + for system, cores in sorted((regions.get("systems") or {}).items()) + for name, rule in sorted(cores.items()) + for keep in rule.get("keep_all_regions") or [] + ] + systems = regions.get("systems") or {} + return { + "region_systems": len(systems), + "region_cores": sum(len(c) for c in systems.values()), + "cases": sorted(regions.get("cases") or {}), + "case_entries": keeps, + "extras": len(extras.get("extras") or []), + "extra_systems": sorted({e["system"] for e in extras.get("extras") or []}), + } diff --git a/scripts/games/setups.py b/scripts/games/setups.py new file mode 100644 index 000000000..58333afcd --- /dev/null +++ b/scripts/games/setups.py @@ -0,0 +1,125 @@ +"""The published setup documents: each setup's rom folders with their systems, profile and fallback keys.""" + +from __future__ import annotations + +import functools +from collections.abc import Callable +from dataclasses import dataclass, field + +from games.fallback import FallbackTables, platform_required, shared_table +from games.folders import emulator_profile, resolve_folder +from games.inputs import FORMAT_VERSION, Inputs, load_json +from games.profileindex import Profiles +from model.romfolders import ProfileResolver, SystemResolver + + +@dataclass +class _SetupContext: + resolver: SystemResolver + cores: ProfileResolver + profiles: Profiles + arcade: set[str] + inputs: Inputs + fallbacks: FallbackTables + manifests: dict[str, dict] = field(default_factory=dict) + required: dict[str, dict[tuple[str, str], bool]] = field(default_factory=dict) + + def manifest(self, platform: str) -> dict | None: + if platform and platform not in self.manifests: + path = self.inputs.install / f"{platform}.json" + if path.exists(): + self.manifests[platform] = load_json(path) + self.required[platform] = platform_required(platform, self.inputs.platforms) + return self.manifests.get(platform) + + +def _board_defaults(ctx: _SetupContext, row: dict, + fallback_keys: Callable[[str | None], list[str]] | None) -> dict: + boards = {} + for board, spec in sorted((row.get("board_defaults") or {}).items()): + boards[board] = {"core": spec["core"]} + board_profile = ctx.cores.resolve(spec["core"]) + if board_profile: + boards[board]["profile"] = board_profile + if board_profile in ctx.arcade: + boards[board]["arcade"] = board_profile + if fallback_keys: + # A card moves between boards, and the installer reads + # it on a computer: each board's core has its set. + boards[board]["fallback"] = fallback_keys(board_profile) + return boards + + +def _publish_folder(ctx: _SetupContext, row: dict, platform: str, manifest: dict | None, + counts: dict[str, int]) -> dict: + counts["folders"] += 1 + profile = (ctx.cores.resolve(row.get("core")) + or emulator_profile(row, platform, ctx.cores, ctx.resolver, ctx.profiles)) + resolution = resolve_folder(row, platform, profile, ctx.resolver, ctx.profiles, ctx.arcade) + published: dict = { + "folder": row["folder"], + "systems": resolution.systems, + "basis": resolution.basis, + } + for key in ("name", "aliases", "extensions", "files", "core", "emulator", "note"): + if row.get(key): + published[key] = row[key] + if profile: + published["profile"] = profile + counts["profile"] += 1 + if resolution.systems: + counts["resolved"] += 1 + + fallback_keys = None + if manifest is not None and resolution.systems: + fallback_keys = functools.partial(ctx.fallbacks.keys, platform, manifest, ctx.required[platform], + resolution.systems) + boards = _board_defaults(ctx, row, fallback_keys) + if boards: + published["board_defaults"] = boards + if profile and profile in ctx.arcade: + published["arcade"] = profile + elif row.get("arcade"): + published["arcade"] = True + if fallback_keys: + keys = fallback_keys(profile) + published["fallback"] = keys + if any(ctx.fallbacks.tables[platform][k]["files"] for k in keys): + counts["fallback"] += 1 + published["source_ref"] = row["source_ref"] + return published + + +def build_setups( + setups: dict[str, dict], + resolver: SystemResolver, + cores: ProfileResolver, + profiles: Profiles, + arcade: set[str], + inputs: Inputs, +) -> tuple[dict[str, dict], dict[str, dict], dict]: + """Published setup documents, fallback tables per platform, coverage.""" + ctx = _SetupContext(resolver, cores, profiles, arcade, inputs, FallbackTables(profiles)) + out: dict[str, dict] = {} + coverage: dict[str, dict] = {} + for setup, doc in sorted(setups.items()): + platform = doc.get("platform") or "" + manifest = ctx.manifest(platform) + counts = {"folders": 0, "resolved": 0, "profile": 0, "fallback": 0} + folders = [_publish_folder(ctx, row, platform, manifest, counts) for row in doc.get("folders", [])] + out[setup] = { + "format_version": FORMAT_VERSION, + "setup": setup, + "name": doc["name"], + "platform": platform, + "sources": doc["sources"], + "roms_root": doc["roms_root"], + "case_sensitive": doc["case_sensitive"], + **{k: doc[k] for k in ("skip", "hidden", "media", "notes") if doc.get(k)}, + "folders": folders, + } + coverage[setup] = counts + published_fallbacks = { + platform: shared_table(platform, table) for platform, table in sorted(ctx.fallbacks.tables.items()) + } + return out, published_fallbacks, coverage diff --git a/scripts/games/systems.py b/scripts/games/systems.py new file mode 100644 index 000000000..e5f4f9e31 --- /dev/null +++ b/scripts/games/systems.py @@ -0,0 +1,112 @@ +"""The published system documents: game identification, header readers, region rules and extra files.""" + +from __future__ import annotations + +from collections.abc import Iterable +from pathlib import Path + +from games.inputs import FORMAT_VERSION, load_json, load_optional_yaml +from games.profileindex import Profiles +from model.romfolders import SystemResolver + + +def _catalogs(directory: Path) -> Iterable[dict]: + if directory.is_dir(): + for path in sorted(directory.glob("*/*.json")): + yield load_json(path) + + +def _add_catalog(doc: dict, catalog: dict) -> None: + regions_table = catalog["regions"] + fields = catalog["fields"] + col = {name: i for i, name in enumerate(fields)} + ident = doc.setdefault("identify", {"sources": [], "regions": [], "games": [], "serials": {}}) + region_index: dict[tuple[str, ...], int] = { + tuple(r): i for i, r in enumerate(ident["regions"]) + } + + def reindex(i: int) -> int: + value = tuple(regions_table[i]) if i is not None and i >= 0 else () + if value not in region_index: + region_index[value] = len(ident["regions"]) + ident["regions"].append(list(value)) + return region_index[value] + + ident["sources"].append({ + k: catalog[k] for k in ("source", "dat", "version", "fetched_from", "licence", "serial_note") if k in catalog + }) + for row in catalog["games"]: + region = reindex(row[col["region"]]) + ident["games"].append([row[col["crc32"]], row[col["size"]], region, row[col["title"]]]) + for serial in row[col["serials"]] if "serials" in col else []: + ident["serials"].setdefault(serial, set()).add(region) + + +def build_systems( + resolver: SystemResolver, + profiles: Profiles, + used: dict[str, set[str]], + games: Path, +) -> tuple[dict[str, dict], dict]: + """Published system documents and per-system coverage. + + `used` holds, per system, the profiles some setup starts for it: their + region files are published even without a rule of their own. + """ + headers = load_optional_yaml(games / "headers.yml").get("systems", {}) + extras: dict[str, list[dict]] = {} + for entry in load_optional_yaml(games / "extras.yml").get("extras", []): + extras.setdefault(entry["system"], []).append(entry) + rule_file = load_optional_yaml(games / "regions.yml") + cases = rule_file.get("cases", {}) + docs: dict[str, dict] = {} + + def doc_for(system: str) -> dict: + key = resolver.canonical(system) + return docs.setdefault(key, {"format_version": FORMAT_VERSION, "system": key}) + + for catalog in _catalogs(games / "catalogs"): + _add_catalog(doc_for(catalog["system"]), catalog) + for doc in docs.values(): + ident = doc.get("identify") + if ident: + ident["games"].sort() + ident["serials"] = {s: sorted(r) for s, r in sorted(ident["serials"].items())} + for system, spec in headers.items(): + doc_for(system)["headers"] = spec + for system, entries in extras.items(): + doc_for(system).setdefault("extras", []).extend(entries) + rule_profiles: dict[str, set[str]] = {} + for system, spec in rule_file.get("systems", {}).items(): + doc = doc_for(system) + rules = doc.setdefault("region_rules", {}) + rules.update(spec) + named = { + case["case"] for core in spec.values() + for case in (core.get("keep_all_regions") or []) if isinstance(case, dict) + } + if named: + doc.setdefault("cases", {}).update({c: cases[c] for c in sorted(named) if c in cases}) + rule_profiles.setdefault(doc["system"], set()).update(spec if isinstance(spec, dict) else ()) + for system, names in used.items(): + rule_profiles.setdefault(resolver.canonical(system), set()).update(names) + for system, names in rule_profiles.items(): + files = { + name: tagged for name in sorted(names) + if name in profiles.profiles + and (tagged := profiles.region_files(name, system)) + and set(tagged) - {"any"} + } + if files: + doc_for(system)["region_files"] = files + coverage = { + system: { + "games": len(doc.get("identify", {}).get("games", [])), + "serials": len(doc.get("identify", {}).get("serials", {})), + "header_readers": len((doc.get("headers") or {}).get("readers", {}) or []), + "region_profiles": len(doc.get("region_files", {})), + "extras": bool(doc.get("extras")), + } + for system, doc in sorted(docs.items()) + } + return docs, coverage diff --git a/scripts/generate_games_index.py b/scripts/generate_games_index.py index 1085c8495..23c885825 100644 --- a/scripts/generate_games_index.py +++ b/scripts/generate_games_index.py @@ -31,689 +31,18 @@ Nothing here is written by hand: a second run writes the same bytes. from __future__ import annotations import argparse -import functools -import gzip -import hashlib -import json -import posixpath import sys -from collections.abc import Callable, Iterable -from dataclasses import dataclass, field from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from core.paths import EMULATORS_DIR, PLATFORMS_DIR -from model.profiles import entry_system_ids, load_emulator_profiles -from model.platforms import load_platform_config, native_layer from core.artifacts import repository_output_lock from core.cli import run_cli -from model.region import normalize_declared -from model.romfolders import ProfileResolver, Resolution, SystemResolver, folder_names, load_setups -from core.artifacts import write_text_atomic -from model.sources import source_yaml_file - -import install - -FORMAT_VERSION = 1 -OUTPUT = Path("install") / "games" -GAMES = Path("games") - -# Coverage the published data may not fall below. A rescrape or a DAT import -# that loses rows fails the step instead of shipping a thinner index. -FLOORS = { - "folders_resolved_share": 0.84, - "catalog_systems": 30, - "arcade_profiles": 6, -} - - -@dataclass(frozen=True) -class Inputs: - """Where each source is read from. The defaults are the repository's.""" - - games: Path = GAMES - romfolders: Path = Path("platforms") / "romfolders" - install: Path = Path("install") - emulators: str = EMULATORS_DIR - platforms: str = PLATFORMS_DIR - - -def dumps(document: object) -> str: - return json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n" - - -def _load_yaml(path: Path) -> dict: - if not path.exists(): - return {} - return source_yaml_file(path) or {} - - -def _load_json(path: Path) -> dict: - with path.open(encoding="utf-8") as handle: - return json.load(handle) - - -# --- Profiles --------------------------------------------------------------- - - -def _entry_names(entry: dict) -> set[str]: - names = {str(entry.get("name") or "")} - names |= {str(a) for a in entry.get("aliases") or []} - for key in ("path", "standalone_path", "destination"): - if entry.get(key): - names.add(Path(str(entry[key])).name) - return {n.lower() for n in names if n} - - -class Profiles: - """Profile lookups the fallback and region sections share.""" - - def __init__(self, profiles: dict[str, dict], resolver: SystemResolver) -> None: - self.profiles = profiles - self.resolver = resolver - self._by_name: dict[str, dict[str, list[dict]]] = {} - - def entries_named(self, profile: str, name: str) -> list[dict]: - table = self._by_name.get(profile) - if table is None: - table = {} - for entry in self.profiles.get(profile, {}).get("files") or []: - if isinstance(entry, dict): - for n in _entry_names(entry): - table.setdefault(n, []).append(entry) - self._by_name[profile] = table - return table.get(name.lower(), []) - - def serves(self, profile: str, entry: dict, system: str) -> bool: - wanted = self.resolver.equivalents(system) - return bool(set(entry_system_ids(entry, self.profiles.get(profile, {}))) & wanted) - - def region_files(self, profile: str, system: str) -> dict[str, list[str]]: - """Region slug -> file names the profile tags for it, for one system. - - `any` holds the files declared with no region: those are installed - whatever the game's region. - """ - out: dict[str, set[str]] = {} - data = self.profiles.get(profile, {}) - for entry in data.get("files") or []: - if not isinstance(entry, dict) or not self.serves(profile, entry, system): - continue - if entry.get("category") == "game_data": - continue - regions = normalize_declared(entry.get("region")) or {"any"} - for region in regions: - out.setdefault(region, set()).add(str(entry["name"])) - return {k: sorted(v) for k, v in sorted(out.items())} - - -# --- Fallback sets ---------------------------------------------------------- - - -def _platform_required(platform: str, platforms_dir: str) -> dict[tuple[str, str], bool]: - """(system, file name) -> required, as the platform's own list declares it.""" - config = load_platform_config(platform, platforms_dir) - out: dict[tuple[str, str], bool] = {} - for sys_id, system in (native_layer(config) or config).get("systems", {}).items(): - for entry in system.get("files", []): - for name in {entry.get("name"), Path(str(entry.get("destination") or "")).name} - {None, ""}: - out[(sys_id, str(name).lower())] = entry.get("required") is not False - return out - - -def _narrowed(manifest: dict, cores: list[str], cache: dict) -> list[tuple[dict, str]]: - """The install list under some cores, each file with its lowercased - base name. The answer depends on the cores alone, and a platform asks - it once per system they run.""" - key = (id(manifest), tuple(cores)) - if key not in cache: - files, _omitted = install.narrow( - manifest["files"], manifest.get("omitted_files", []), [], cores, []) - cache[key] = [(entry, posixpath.basename(entry["dest"]).lower()) for entry in files] - return cache[key] - - -def fallback_set( - manifest: dict, - platform_required: dict[tuple[str, str], bool], - profiles: Profiles, - system: str, - profile: str | None, - narrowed: dict | None = None, -) -> dict: - """The files an unrecognised game of one system keeps on one platform. - - The platform's own files for the system, plus what the default core's - profile reads for it. The core step is the installer's own narrowing - (`install.narrow` with the designated cores). A core file the list does - not attribute to a platform system is kept when the profile entry that - declares it serves the system. - """ - wanted = profiles.resolver.equivalents(system) - cores = sorted(install.designated_cores(manifest, [profile])) if profile else [] - rows: list[list] = [] - for entry, base in _narrowed(manifest, cores, {} if narrowed is None else narrowed): - systems = set(entry.get("systems") or []) - dest = entry["dest"] - if entry.get("cores") is None: - if not systems & wanted: - continue - required = any( - platform_required.get((s, base), True) for s in systems & wanted - ) - else: - if systems and not systems & wanted: - continue - declared = profiles.entries_named(profile or "", base) - if not systems and not any(profiles.serves(profile or "", e, system) for e in declared): - continue - required = any(e.get("required") is not False for e in declared) if declared else True - rows.append([dest, int(entry["size"]), required, entry.get("category") or "bios"]) - rows.sort() - return { - "files": rows, - "bytes": sum(r[1] for r in rows), - "required_bytes": sum(r[1] for r in rows if r[2]), - } - - -def _shared_table(platform: str, sets: dict[str, dict]) -> dict: - """One row per install-list file, and each set as indices into it. - - The sets of the MAME-run systems hold the same thousand files: written - out per set, Batocera's table weighed half a megabyte compressed. - """ - rows = sorted({(r[0], r[1], r[3]) for body in sets.values() for r in body["files"]}) - position = {row: i for i, row in enumerate(rows)} - published = {} - for key, body in sorted(sets.items()): - published[key] = { - "files": [position[(r[0], r[1], r[3])] for r in body["files"]], - "optional": [position[(r[0], r[1], r[3])] for r in body["files"] if not r[2]], - "bytes": body["bytes"], - "required_bytes": body["required_bytes"], - } - return { - "format_version": FORMAT_VERSION, - "platform": platform, - "files": [list(r) for r in rows], - "sets": published, - } - - -# --- Setups ----------------------------------------------------------------- - - -def _arcade_profiles(directory: Path) -> set[str]: - return {p.stem for p in directory.glob("*.json")} if directory.is_dir() else set() - - -def resolve_folder( - row: dict, platform: str, profile: str | None, resolver: SystemResolver, profiles: Profiles, - arcade: frozenset[str] | set[str] = frozenset(), -) -> Resolution: - """The systems a folder holds: its names first, else its core's machines. - - A name nothing spells, run by a core of one machine, is that machine - (ECWolf's wolf3d folder, a port's own folder). Run by a core of several, - its games are one of them (theodore's thomson folder), and every one - is kept: left empty, the folder had no fallback and its games got no file. - An arcade core is the exception: the arcade index names each set's - files, and its hundred machines would make any unknown file a fallback - for all of them. - - A name that spells a machine its core does not run adds the core's - machines to it: the games run on that core. Mednafen's PC Engine core - lists nec-pc-engine, the CD folder resolved to nec-pc-engine-cd alone, - and an unrecognised CD game got no System Card. - """ - resolution = resolver.resolve(folder_names(row), platform) - own = [str(s) for s in profiles.profiles.get(profile or "", {}).get("systems") or []] - if resolution.systems and own and profile not in arcade: - runs = {sid for s in own for sid in resolver.equivalents(s)} - if not runs & set(resolution.systems): - systems = set(resolution.systems) | {resolver.canonical(s) for s in own} - return Resolution(sorted(systems), f"{resolution.basis}, and systems of {profile}") - if resolution.systems or not own: - return resolution - if len(own) == 1: - return Resolution([resolver.canonical(own[0])], f"only system of {profile}") - if profile in arcade: - return resolution - return Resolution(sorted({resolver.canonical(s) for s in own}), f"systems of {profile}") - - -# The emulator column of a row names the frontend or a launch mode, never -# a program whose files are read: these never answer for a core. -_NOT_PROGRAMS = frozenset({"retroarch", "retroarch32", "libretro", "external", "standalone", - "port", "ports", "native", "sh", "os-shell", "none"}) - - -def emulator_profile(row: dict, platform: str, cores: ProfileResolver, - resolver: SystemResolver, profiles: Profiles) -> str | None: - """The profile of the program a row's emulator column names, when its - core column names a mode, a machine or a plugin of that program: RetroBat - runs demul for core hikaru, AmberELEC MAME for core gamate, Batocera - mupen64plus for core glide64mk2. - - Kept only when that profile declares a system of the folder: MAME's - profile has no GameKing, and answering MAME for its folder would leave - out the ROM the core needs. Unresolved, the folder keeps the files of - every core of its systems, as it did. - """ - emulator = str(row.get("emulator") or "").strip() - if not emulator or emulator.lower() in _NOT_PROGRAMS or emulator.lower().startswith("standalone"): - return None - candidate = cores.resolve(emulator) - if not candidate: - return None - systems = resolver.resolve(folder_names(row), platform).systems - own = {str(s) for s in profiles.profiles.get(candidate, {}).get("systems") or []} - declared = {spelling for sid in own for spelling in resolver.equivalents(sid)} - return candidate if any(resolver.equivalents(sid) & declared for sid in systems) else None - - -@dataclass -class _FallbackTables: - """The fallback sets of a folder's systems under one core, computed - once per platform.""" - - profiles: Profiles - tables: dict[str, dict[str, dict]] = field(default_factory=dict) - narrowed: dict = field(default_factory=dict) - - def keys(self, platform: str, manifest: dict, required: dict[tuple[str, str], bool], - systems: list[str], chosen: str | None) -> list[str]: - keys = [] - table = self.tables.setdefault(platform, {}) - for system in systems: - key = f"{system}|{chosen or ''}" - if key not in table: - table[key] = fallback_set(manifest, required, self.profiles, system, chosen, self.narrowed) - keys.append(key) - return keys - - -@dataclass -class _SetupContext: - resolver: SystemResolver - cores: ProfileResolver - profiles: Profiles - arcade: set[str] - inputs: Inputs - fallbacks: _FallbackTables - manifests: dict[str, dict] = field(default_factory=dict) - required: dict[str, dict[tuple[str, str], bool]] = field(default_factory=dict) - - def manifest(self, platform: str) -> dict | None: - if platform and platform not in self.manifests: - path = self.inputs.install / f"{platform}.json" - if path.exists(): - self.manifests[platform] = _load_json(path) - self.required[platform] = _platform_required(platform, self.inputs.platforms) - return self.manifests.get(platform) - - -def _board_defaults(ctx: _SetupContext, row: dict, - fallback_keys: Callable[[str | None], list[str]] | None) -> dict: - boards = {} - for board, spec in sorted((row.get("board_defaults") or {}).items()): - boards[board] = {"core": spec["core"]} - board_profile = ctx.cores.resolve(spec["core"]) - if board_profile: - boards[board]["profile"] = board_profile - if board_profile in ctx.arcade: - boards[board]["arcade"] = board_profile - if fallback_keys: - # A card moves between boards, and the installer reads - # it on a computer: each board's core has its set. - boards[board]["fallback"] = fallback_keys(board_profile) - return boards - - -def _publish_folder(ctx: _SetupContext, row: dict, platform: str, manifest: dict | None, - counts: dict[str, int]) -> dict: - counts["folders"] += 1 - profile = (ctx.cores.resolve(row.get("core")) - or emulator_profile(row, platform, ctx.cores, ctx.resolver, ctx.profiles)) - resolution = resolve_folder(row, platform, profile, ctx.resolver, ctx.profiles, ctx.arcade) - published: dict = { - "folder": row["folder"], - "systems": resolution.systems, - "basis": resolution.basis, - } - for key in ("name", "aliases", "extensions", "files", "core", "emulator", "note"): - if row.get(key): - published[key] = row[key] - if profile: - published["profile"] = profile - counts["profile"] += 1 - if resolution.systems: - counts["resolved"] += 1 - - fallback_keys = None - if manifest is not None and resolution.systems: - fallback_keys = functools.partial(ctx.fallbacks.keys, platform, manifest, ctx.required[platform], - resolution.systems) - boards = _board_defaults(ctx, row, fallback_keys) - if boards: - published["board_defaults"] = boards - if profile and profile in ctx.arcade: - published["arcade"] = profile - elif row.get("arcade"): - published["arcade"] = True - if fallback_keys: - keys = fallback_keys(profile) - published["fallback"] = keys - if any(ctx.fallbacks.tables[platform][k]["files"] for k in keys): - counts["fallback"] += 1 - published["source_ref"] = row["source_ref"] - return published - - -def build_setups( - setups: dict[str, dict], - resolver: SystemResolver, - cores: ProfileResolver, - profiles: Profiles, - arcade: set[str], - inputs: Inputs, -) -> tuple[dict[str, dict], dict[str, dict], dict]: - """Published setup documents, fallback tables per platform, coverage.""" - ctx = _SetupContext(resolver, cores, profiles, arcade, inputs, _FallbackTables(profiles)) - out: dict[str, dict] = {} - coverage: dict[str, dict] = {} - for setup, doc in sorted(setups.items()): - platform = doc.get("platform") or "" - manifest = ctx.manifest(platform) - counts = {"folders": 0, "resolved": 0, "profile": 0, "fallback": 0} - folders = [_publish_folder(ctx, row, platform, manifest, counts) for row in doc.get("folders", [])] - out[setup] = { - "format_version": FORMAT_VERSION, - "setup": setup, - "name": doc["name"], - "platform": platform, - "sources": doc["sources"], - "roms_root": doc["roms_root"], - "case_sensitive": doc["case_sensitive"], - **{k: doc[k] for k in ("skip", "hidden", "media", "notes") if doc.get(k)}, - "folders": folders, - } - coverage[setup] = counts - published_fallbacks = { - platform: _shared_table(platform, table) for platform, table in sorted(ctx.fallbacks.tables.items()) - } - return out, published_fallbacks, coverage - - -# --- Systems ---------------------------------------------------------------- - - -def _catalogs(directory: Path) -> Iterable[dict]: - if directory.is_dir(): - for path in sorted(directory.glob("*/*.json")): - yield _load_json(path) - - -def _add_catalog(doc: dict, catalog: dict) -> None: - regions_table = catalog["regions"] - fields = catalog["fields"] - col = {name: i for i, name in enumerate(fields)} - ident = doc.setdefault("identify", {"sources": [], "regions": [], "games": [], "serials": {}}) - region_index: dict[tuple[str, ...], int] = { - tuple(r): i for i, r in enumerate(ident["regions"]) - } - - def reindex(i: int) -> int: - value = tuple(regions_table[i]) if i is not None and i >= 0 else () - if value not in region_index: - region_index[value] = len(ident["regions"]) - ident["regions"].append(list(value)) - return region_index[value] - - ident["sources"].append({ - k: catalog[k] for k in ("source", "dat", "version", "fetched_from", "licence", "serial_note") if k in catalog - }) - for row in catalog["games"]: - region = reindex(row[col["region"]]) - ident["games"].append([row[col["crc32"]], row[col["size"]], region, row[col["title"]]]) - for serial in row[col["serials"]] if "serials" in col else []: - ident["serials"].setdefault(serial, set()).add(region) - - -def build_systems( - resolver: SystemResolver, - profiles: Profiles, - used: dict[str, set[str]], - games: Path, -) -> tuple[dict[str, dict], dict]: - """Published system documents and per-system coverage. - - `used` holds, per system, the profiles some setup starts for it: their - region files are published even without a rule of their own. - """ - headers = _load_yaml(games / "headers.yml").get("systems", {}) - extras: dict[str, list[dict]] = {} - for entry in _load_yaml(games / "extras.yml").get("extras", []): - extras.setdefault(entry["system"], []).append(entry) - rule_file = _load_yaml(games / "regions.yml") - cases = rule_file.get("cases", {}) - docs: dict[str, dict] = {} - - def doc_for(system: str) -> dict: - key = resolver.canonical(system) - return docs.setdefault(key, {"format_version": FORMAT_VERSION, "system": key}) - - for catalog in _catalogs(games / "catalogs"): - _add_catalog(doc_for(catalog["system"]), catalog) - for doc in docs.values(): - ident = doc.get("identify") - if ident: - ident["games"].sort() - ident["serials"] = {s: sorted(r) for s, r in sorted(ident["serials"].items())} - for system, spec in headers.items(): - doc_for(system)["headers"] = spec - for system, entries in extras.items(): - doc_for(system).setdefault("extras", []).extend(entries) - rule_profiles: dict[str, set[str]] = {} - for system, spec in rule_file.get("systems", {}).items(): - doc = doc_for(system) - rules = doc.setdefault("region_rules", {}) - rules.update(spec) - named = { - case["case"] for core in spec.values() - for case in (core.get("keep_all_regions") or []) if isinstance(case, dict) - } - if named: - doc.setdefault("cases", {}).update({c: cases[c] for c in sorted(named) if c in cases}) - rule_profiles.setdefault(doc["system"], set()).update(spec if isinstance(spec, dict) else ()) - for system, names in used.items(): - rule_profiles.setdefault(resolver.canonical(system), set()).update(names) - for system, names in rule_profiles.items(): - files = { - name: tagged for name in sorted(names) - if name in profiles.profiles - and (tagged := profiles.region_files(name, system)) - and set(tagged) - {"any"} - } - if files: - doc_for(system)["region_files"] = files - coverage = { - system: { - "games": len(doc.get("identify", {}).get("games", [])), - "serials": len(doc.get("identify", {}).get("serials", {})), - "header_readers": len((doc.get("headers") or {}).get("readers", {}) or []), - "region_profiles": len(doc.get("region_files", {})), - "extras": bool(doc.get("extras")), - } - for system, doc in sorted(docs.items()) - } - return docs, coverage - - -# --- Arcade ----------------------------------------------------------------- - - -def build_arcade(directory: Path) -> dict[str, dict]: - if not directory.is_dir(): - return {} - # The driver sources and the clone parents place a search path's sets at - # build time (common.rom_search_sets): the installer reads none of them. - return { - path.stem: {k: v for k, v in _load_json(path).items() if k not in ("sources", "parents")} - for path in sorted(directory.glob("*.json")) - } - - -# --- Writing ---------------------------------------------------------------- - - -def _entry(text: str) -> dict: - data = text.encode("utf-8") - return { - "size": len(data), - "gzip_size": len(gzip.compress(data, compresslevel=9, mtime=0)), - "sha256": hashlib.sha256(data).hexdigest(), - } - - -def folder_systems(setups: dict[str, dict]) -> dict[str, list[str]]: - """Every folder name a setup gives a system, casefolded, with the systems - any setup reads there, and each system id under its own name. - - What a games folder on a computer is read with when its setup names no - folder of its own (RetroArch): a name two setups give two systems keeps - both. - """ - names: dict[str, set[str]] = {} - for doc in setups.values(): - for row in doc["folders"]: - systems = row["systems"] - if not systems: - continue - for name in [row["folder"], *(row.get("aliases") or [])]: - names.setdefault(str(name).casefold(), set()).update(systems) - for system in systems: - names.setdefault(system.casefold(), set()).add(system) - return {name: sorted(systems) for name, systems in sorted(names.items())} - - -def render(output: Path = OUTPUT, inputs: Inputs | None = None) -> tuple[dict[Path, str], dict]: - """Every published file's text, keyed by its path, and the coverage.""" - inputs = inputs or Inputs() - resolver = SystemResolver.from_repo(inputs.emulators, inputs.platforms) - profiles = Profiles(load_emulator_profiles(inputs.emulators), resolver) - arcade = build_arcade(inputs.games / "arcade") - setups, fallbacks, setup_cov = build_setups( - load_setups(inputs.romfolders), resolver, ProfileResolver.from_repo(inputs.emulators), - profiles, set(arcade), inputs, - ) - used: dict[str, set[str]] = {} - for doc in setups.values(): - for row in doc["folders"]: - for system in row["systems"]: - if row.get("profile"): - used.setdefault(system, set()).add(row["profile"]) - systems, system_cov = build_systems(resolver, profiles, used, inputs.games) - - files: dict[Path, str] = {} - index: dict = {"format_version": FORMAT_VERSION, "setups": {}, "fallback": {}, "systems": {}, "arcade": {}} - for kind, docs in (("setups", setups), ("fallback", fallbacks), ("systems", systems), ("arcade", arcade)): - for key, doc in sorted(docs.items()): - rel = Path(kind) / f"{key}.json" - text = dumps(doc) - files[output / rel] = text - index[kind][key] = {"file": rel.as_posix(), **_entry(text)} - digest = hashlib.sha256( - "".join(f"{p.relative_to(output).as_posix()} {_entry(t)['sha256']}\n" for p, t in sorted(files.items())).encode() - ).hexdigest() - index["data_version"] = digest[:16] - index["licences"] = sorted( - {json.dumps(src.get("licence"), sort_keys=True) - for doc in systems.values() for src in doc.get("identify", {}).get("sources", []) - if src.get("licence")} - ) - index["licences"] = [json.loads(x) for x in index["licences"]] - containers = _load_yaml(inputs.games / "headers.yml").get("containers") - if containers: - index["containers"] = containers - index["folders"] = folder_systems(setups) - files[output / "index.json"] = dumps(index) - coverage = {"setups": setup_cov, "systems": system_cov, "arcade": sorted(arcade)} - return files, coverage - - -def floor_failures(coverage: dict) -> list[str]: - total = sum(c["folders"] for c in coverage["setups"].values()) - resolved = sum(c["resolved"] for c in coverage["setups"].values()) - out = [] - share = resolved / total if total else 0.0 - if share < FLOORS["folders_resolved_share"]: - out.append(f"folders resolved {resolved}/{total} ({share:.1%}) under {FLOORS['folders_resolved_share']:.0%}") - catalogs = sum(1 for c in coverage["systems"].values() if c["games"]) - if catalogs < FLOORS["catalog_systems"]: - out.append(f"systems with a game catalog {catalogs} under {FLOORS['catalog_systems']}") - if len(coverage["arcade"]) < FLOORS["arcade_profiles"]: - out.append(f"arcade profiles {len(coverage['arcade'])} under {FLOORS['arcade_profiles']}") - return out - - -def print_coverage(coverage: dict, files: dict[Path, str]) -> None: - print("Setups (folders / resolved to a system / default core profiled / with a fallback set):") - for setup, c in coverage["setups"].items(): - print(f" {setup:16} {c['folders']:4} {c['resolved']:4} {c['profile']:4} {c['fallback']:4}") - print("Systems (games by hash / serials / header readers / profiles with region files / extras):") - for system, c in coverage["systems"].items(): - print(f" {system:28} {c['games']:6} {c['serials']:6} {c['header_readers']:3} " - f"{c['region_profiles']:3} {'yes' if c['extras'] else '-'}") - print(f"Arcade indexes: {', '.join(coverage['arcade']) or 'none'}") - raw = sum(len(t.encode()) for t in files.values()) - packed = sum(len(gzip.compress(t.encode(), 9, mtime=0)) for t in files.values()) - print(f"{len(files)} files, {raw:,} bytes, {packed:,} bytes gzip") - - -def _sample(items: list[str], limit: int = 3) -> str: - shown = ", ".join(items[:limit]) - return f"{shown}, +{len(items) - limit} more" if len(items) > limit else shown - - -def describe_change(old: str | None, new: str) -> list[str]: - """What differs between a published document and the one render() makes. - - The documents are single-line JSON of up to 550 KB: STALE alone left a - diff by hand to find that a manifest gained one file.""" - if old is None: - return ["not written yet"] - try: - before, after = json.loads(old), json.loads(new) - except ValueError: - return ["the published file is not valid JSON"] - if not (isinstance(before, dict) and isinstance(after, dict)): - return ["document changed"] - parts = [] - for key in sorted(set(before) | set(after)): - a, b = before.get(key), after.get(key) - if a == b: - continue - if isinstance(a, list) and isinstance(b, list): - olds = {json.dumps(x, sort_keys=True) for x in a} - news = {json.dumps(x, sort_keys=True) for x in b} - added = sorted(news - olds) - removed = sorted(olds - news) - change = [] - if added: - change.append(f"{len(added)} added ({_sample(added)})") - if removed: - change.append(f"{len(removed)} removed ({_sample(removed)})") - parts.append(f"{key}: {', '.join(change) or 'reordered'}") - elif isinstance(a, dict) and isinstance(b, dict): - changed = sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k)) - parts.append(f"{key}: {len(changed)} changed ({_sample(changed)})") - else: - parts.append(f"{key} changed" if key in before and key in after - else f"{key} {'added' if key in after else 'removed'}") - return parts or ["formatting changed"] +from games.changes import describe_change +from games.coverage import floor_failures, print_coverage +from games.inputs import OUTPUT +from games.publish import pending, write +from games.render import render def main() -> int: @@ -737,10 +66,7 @@ def _index(args: argparse.Namespace) -> int: failures = floor_failures(coverage) for failure in failures: print(f"FLOOR {failure}", file=sys.stderr) - stale = sorted( - p for p in args.output_dir.rglob("*.json") if p not in files - ) if args.output_dir.is_dir() else [] - changed = [p for p, t in files.items() if not p.exists() or p.read_text(encoding="utf-8") != t] + changed, stale = pending(files, args.output_dir) if args.check: for path in changed: print(f"STALE {path}", file=sys.stderr) @@ -753,11 +79,7 @@ def _index(args: argparse.Namespace) -> int: if changed or stale: print("Run python scripts/generate_games_index.py to write them.", file=sys.stderr) return 1 if changed or stale or failures else 0 - for path in stale: - path.unlink() - for path in changed: - path.parent.mkdir(parents=True, exist_ok=True) - write_text_atomic(str(path), files[path]) + write(files, changed, stale) print(f"{len(changed)} written, {len(stale)} removed") return 1 if failures else 0 diff --git a/tests/sources.py b/tests/sources.py index a144cab43..d0c6040fd 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -130,6 +130,13 @@ COMMANDS = { "orchestrate/build.py", "orchestrate/checks.py", "orchestrate/docs.py", "orchestrate/reports.py", "orchestrate/compare.py", "orchestrate/consistency.py", "orchestrate/emulatorpacks.py", "orchestrate/narrowed.py", "orchestrate/splitcheck.py", + "game_rules.py": ( + "games/inputs.py", "games/profileindex.py", "games/headerreaders.py", "games/rulecheck.py", + "games/rulesummary.py", + "generate_games_index.py": ( + "games/inputs.py", "games/profileindex.py", "games/fallback.py", "games/folders.py", + "games/setups.py", "games/systems.py", "games/arcadesets.py", "games/render.py", + "games/coverage.py", "games/changes.py", "games/publish.py", } diff --git a/tests/test_game_regions.py b/tests/test_game_regions.py index 91cd6f449..eb79c8973 100644 --- a/tests/test_game_regions.py +++ b/tests/test_game_regions.py @@ -15,7 +15,9 @@ import json import unittest from pathlib import Path -import game_rules +from games.inputs import EXTRAS_FILE, HEADERS_FILE, REGIONS_FILE, load_yaml +from games.rulecheck import check +from games.rulesummary import summary from model.profiles import load_emulator_profiles REPO_ROOT = Path(__file__).resolve().parents[1] @@ -46,11 +48,11 @@ def _schema_validator(name: str): class FixtureChecks(unittest.TestCase): def setUp(self) -> None: self.profiles = load_emulator_profiles(str(FIXTURES / "emulators")) - self.regions = game_rules.load_yaml(FIXTURES / "regions.yml") - self.extras = game_rules.load_yaml(FIXTURES / "extras.yml") + self.regions = load_yaml(FIXTURES / "regions.yml") + self.extras = load_yaml(FIXTURES / "extras.yml") def errors(self, regions=None, extras=None) -> list[str]: - return game_rules.check( + return check( regions if regions is not None else self.regions, extras if extras is not None else self.extras, self.profiles, @@ -115,8 +117,8 @@ class FixtureChecks(unittest.TestCase): def header_errors(self, header: dict) -> list[str]: extras = copy.deepcopy(self.extras) extras["extras"][0]["trigger"] = {"header": header} - headers = game_rules.load_yaml(FIXTURES / "headers.yml") - return game_rules.check(self.regions, extras, self.profiles, headers) + headers = load_yaml(FIXTURES / "headers.yml") + return check(self.regions, extras, self.profiles, headers) def test_header_trigger_takes_a_label_the_reader_returns(self) -> None: self.assertEqual(self.header_errors({"reader": "fds-image", "values": ["fds"]}), []) @@ -139,8 +141,8 @@ class FixtureChecks(unittest.TestCase): self.assertTrue(any("has no field area" in e for e in errors)) def test_summary_is_stable(self) -> None: - first = game_rules.summary(self.regions, self.extras) - second = game_rules.summary(copy.deepcopy(self.regions), copy.deepcopy(self.extras)) + first = summary(self.regions, self.extras) + second = summary(copy.deepcopy(self.regions), copy.deepcopy(self.extras)) self.assertEqual(json.dumps(first, sort_keys=True), json.dumps(second, sort_keys=True)) self.assertEqual(first["case_entries"][0]["case"], "psx-override-bios") @@ -150,17 +152,17 @@ class FixtureSchemas(unittest.TestCase): for name, schema in (("regions.yml", "game-regions.schema.json"), ("extras.yml", "game-extras.schema.json")): errors = list(_schema_validator(schema).iter_errors( - game_rules.load_yaml(FIXTURES / name))) + load_yaml(FIXTURES / name))) self.assertEqual(errors, [], name) def test_schema_refuses_an_option_case_without_its_option(self) -> None: - regions = game_rules.load_yaml(FIXTURES / "regions.yml") + regions = load_yaml(FIXTURES / "regions.yml") keep = regions["systems"]["sony-playstation"]["psxcore"]["keep_all_regions"][0] del keep["option"] self.assertTrue(list(_schema_validator("game-regions.schema.json").iter_errors(regions))) def test_schema_refuses_two_triggers(self) -> None: - extras = game_rules.load_yaml(FIXTURES / "extras.yml") + extras = load_yaml(FIXTURES / "extras.yml") extras["extras"][0]["trigger"]["every_game"] = True self.assertTrue(list(_schema_validator("game-extras.schema.json").iter_errors(extras))) @@ -170,13 +172,13 @@ class RepositoryRules(unittest.TestCase): @classmethod def setUpClass(cls) -> None: - cls.regions = game_rules.load_yaml(REPO_ROOT / game_rules.REGIONS_FILE) - cls.extras = game_rules.load_yaml(REPO_ROOT / game_rules.EXTRAS_FILE) + cls.regions = load_yaml(REPO_ROOT / REGIONS_FILE) + cls.extras = load_yaml(REPO_ROOT / EXTRAS_FILE) def test_every_rule_is_backed_by_its_profile(self) -> None: profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) - headers = game_rules.load_yaml(REPO_ROOT / game_rules.HEADERS_FILE) - self.assertEqual(game_rules.check(self.regions, self.extras, profiles, headers), []) + headers = load_yaml(REPO_ROOT / HEADERS_FILE) + self.assertEqual(check(self.regions, self.extras, profiles, headers), []) def test_files_match_the_schemas(self) -> None: self.assertEqual(list(_schema_validator("game-regions.schema.json").iter_errors(self.regions)), []) @@ -184,7 +186,7 @@ class RepositoryRules(unittest.TestCase): def test_the_fourteen_cases_are_encoded_and_used(self) -> None: self.assertEqual(set(self.regions["cases"]), EXPECTED_CASES) - used = {row["case"] for row in game_rules.summary(self.regions, self.extras)["case_entries"]} + used = {row["case"] for row in summary(self.regions, self.extras)["case_entries"]} self.assertEqual(used, EXPECTED_CASES) def test_region_free_files_never_carry_a_region(self) -> None: diff --git a/tests/test_games_index.py b/tests/test_games_index.py index 4b275c23a..5060679a0 100644 --- a/tests/test_games_index.py +++ b/tests/test_games_index.py @@ -17,6 +17,14 @@ import unittest from pathlib import Path import generate_games_index as gi +from games import fallback +from games import setups as setup_docs +from games.changes import describe_change +from games.coverage import FLOORS, floor_failures +from games.folders import arcade_profiles, emulator_profile, resolve_folder +from games.inputs import Inputs +from games.profileindex import Profiles +from games.render import render from model.romfolders import SystemResolver, load_setups ROOT = Path(__file__).resolve().parent.parent @@ -80,7 +88,7 @@ class GamesIndexFixture(unittest.TestCase): (catalogs / "sony-playstation.json").write_text(json.dumps(CATALOG), encoding="utf-8") (self.tmp / "games" / "arcade").mkdir() (self.tmp / "games" / "arcade" / "mame.json").write_text(json.dumps(ARCADE), encoding="utf-8") - self.inputs = gi.Inputs( + self.inputs = Inputs( games=self.tmp / "games", romfolders=self.tmp / "romfolders", install=self.tmp / "install", @@ -88,15 +96,15 @@ class GamesIndexFixture(unittest.TestCase): platforms=str(ROOT / "platforms"), ) # The fixture platform has no YAML of its own. - original = gi._platform_required - gi._platform_required = lambda platform, platforms_dir: {} - self.addCleanup(setattr, gi, "_platform_required", original) + original = setup_docs.platform_required + setup_docs.platform_required = lambda platform, platforms_dir: {} + self.addCleanup(setattr, setup_docs, "platform_required", original) def tearDown(self) -> None: shutil.rmtree(self.tmp, ignore_errors=True) def render(self) -> tuple[dict[Path, str], dict]: - return gi.render(self.tmp / "out", self.inputs) + return render(self.tmp / "out", self.inputs) def doc(self, files: dict[Path, str], rel: str) -> dict: return json.loads(files[self.tmp / "out" / rel]) @@ -170,7 +178,7 @@ class GamesIndexFixture(unittest.TestCase): def test_floor_names_what_fell_short(self) -> None: _, coverage = self.render() - failures = gi.floor_failures(coverage) + failures = floor_failures(coverage) self.assertTrue(any("catalog" in f for f in failures)) @@ -183,14 +191,14 @@ class CheckSaysWhatDiffers(unittest.TestCase): old = json.dumps({"files": [["a.bin", 1, "bios"]], "version": 1}) new = json.dumps({"files": [["a.bin", 1, "bios"], ["ide12.rom", 16384, "bios"]], "version": 1}) - lines = gi.describe_change(old, new) + lines = describe_change(old, new) self.assertEqual(len(lines), 1) self.assertIn("1 added", lines[0]) self.assertIn("ide12.rom", lines[0]) def test_new_and_unreadable_documents(self) -> None: - self.assertEqual(gi.describe_change(None, "{}"), ["not written yet"]) - self.assertIn("not valid JSON", gi.describe_change("{", "{}")[0]) + self.assertEqual(describe_change(None, "{}"), ["not written yet"]) + self.assertIn("not valid JSON", describe_change("{", "{}")[0]) def test_check_names_the_command_and_skips_coverage(self) -> None: import contextlib @@ -239,15 +247,15 @@ class CommittedData(unittest.TestCase): resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) cores = ProfileResolver.from_repo(str(ROOT / "emulators")) - profiles = gi.Profiles(load_emulator_profiles(str(ROOT / "emulators")), resolver) + profiles = Profiles(load_emulator_profiles(str(ROOT / "emulators")), resolver) total = unresolved = 0 for doc in setups.values(): for row in doc["folders"]: total += 1 profile = cores.resolve(row.get("core")) - if not gi.resolve_folder(row, doc["platform"], profile, resolver, profiles).systems: + if not resolve_folder(row, doc["platform"], profile, resolver, profiles).systems: unresolved += 1 - self.assertGreaterEqual((total - unresolved) / total, gi.FLOORS["folders_resolved_share"]) + self.assertGreaterEqual((total - unresolved) / total, FLOORS["folders_resolved_share"]) def test_a_folder_holds_a_machine_its_core_runs(self) -> None: """muOS names its GBA folder gameboyadvance first: it resolved to @@ -264,8 +272,8 @@ class CommittedData(unittest.TestCase): resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) cores = ProfileResolver.from_repo(str(ROOT / "emulators")) loaded = load_emulator_profiles(str(ROOT / "emulators")) - profiles = gi.Profiles(loaded, resolver) - arcade = gi._arcade_profiles(ROOT / "games" / "arcade") + profiles = Profiles(loaded, resolver) + arcade = arcade_profiles(ROOT / "games" / "arcade") apart = [] for key, doc in sorted(setups.items()): for row in doc["folders"]: @@ -274,7 +282,7 @@ class CommittedData(unittest.TestCase): continue runs = {sid for s in loaded[profile].get("systems") or [] for sid in resolver.equivalents(str(s))} - systems = gi.resolve_folder(row, doc["platform"], profile, resolver, + systems = resolve_folder(row, doc["platform"], profile, resolver, profiles, arcade).systems if runs and systems and not runs & set(systems): apart.append(f"{key}/{row['folder']} {systems} by {profile}") @@ -283,7 +291,7 @@ class CommittedData(unittest.TestCase): if row["folder"] == "nintendogameboyadvance") self.assertIn("gameboyadvance", folder_names(muos)) self.assertEqual( - gi.resolve_folder(muos, "retroarch", "mgba", resolver, profiles, arcade).systems, + resolve_folder(muos, "retroarch", "mgba", resolver, profiles, arcade).systems, ["nintendo-gba"]) def test_an_unrecognised_gba_game_on_muos_gets_the_gba_bios(self) -> None: @@ -302,11 +310,11 @@ class CommittedData(unittest.TestCase): from model.profiles import load_emulator_profiles resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) - profiles = gi.Profiles(load_emulator_profiles(str(ROOT / "emulators")), resolver) - thomson = gi.resolve_folder({"folder": "thomson"}, "recalbox", "theodore", resolver, profiles) + profiles = Profiles(load_emulator_profiles(str(ROOT / "emulators")), resolver) + thomson = resolve_folder({"folder": "thomson"}, "recalbox", "theodore", resolver, profiles) self.assertIn("thomson-to8", thomson.systems) self.assertEqual(thomson.basis, "systems of theodore") - lcd = gi.resolve_folder({"folder": "lcdgames"}, "batocera", "mame", resolver, profiles, {"mame"}) + lcd = resolve_folder({"folder": "lcdgames"}, "batocera", "mame", resolver, profiles, {"mame"}) self.assertEqual(lcd.systems, []) @@ -347,11 +355,11 @@ class EveryCoreResolvesOrIsExplained(unittest.TestCase): self.resolver = SystemResolver.from_repo(str(ROOT / "emulators"), str(ROOT / "platforms")) self.cores = ProfileResolver.from_repo(str(ROOT / "emulators")) - self.profiles = gi.Profiles(load_emulator_profiles(str(ROOT / "emulators")), self.resolver) + self.profiles = Profiles(load_emulator_profiles(str(ROOT / "emulators")), self.resolver) def profile(self, row: dict, platform: str) -> str | None: return (self.cores.resolve(row.get("core")) - or gi.emulator_profile(row, platform, self.cores, self.resolver, self.profiles)) + or emulator_profile(row, platform, self.cores, self.resolver, self.profiles)) def test_either_separator_resolves(self) -> None: self.assertEqual(self.cores.resolve("flycast_xtreme"), "flycast2021") @@ -391,11 +399,11 @@ class OneNarrowingPerCoreList(unittest.TestCase): manifest = {"files": [{"dest": "dir/SCPH5501.BIN"}, {"dest": "b.rom"}]} cache: dict = {} - with mock.patch.object(gi.install, "narrow", + with mock.patch.object(fallback.install, "narrow", return_value=(manifest["files"], [])) as narrow: for _system in ("sony-playstation", "sony-playstation-2"): - rows = gi._narrowed(manifest, ["core"], cache) - gi._narrowed(manifest, ["other"], cache) + rows = fallback.narrowed(manifest, ["core"], cache) + fallback.narrowed(manifest, ["other"], cache) self.assertEqual(narrow.call_count, 2) self.assertEqual([base for _entry, base in rows], ["scph5501.bin", "b.rom"]) diff --git a/tests/test_layers.py b/tests/test_layers.py index d607f9882..9660d21d7 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -56,6 +56,7 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { # Step 5 builds the packs in memory, and the offline export refusal asks # the exporters which ones patch a cached original. "orchestrate": frozenset({"packs", "exporter"}), + "games": frozenset(), } # Top-level files that stay whole at their path although packages import them: diff --git a/tests/test_optional_dependencies.py b/tests/test_optional_dependencies.py index 43dfcef62..c2b771814 100644 --- a/tests/test_optional_dependencies.py +++ b/tests/test_optional_dependencies.py @@ -126,7 +126,7 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase): p.name for p in scripts.iterdir() if p.is_dir() } | {"scripts", "__future__"} # install.py is the repository's own single file, stdlib only (its - # tests hold it to that): generate_games_index reads its narrowing. + # tests hold it to that): games.fallback reads its narrowing. local.add("install") found = [ f"{path.relative_to(scripts)}: {name}" diff --git a/wiki/architecture.md b/wiki/architecture.md index 4d4fc6a94..7a8a565a7 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -44,6 +44,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c collection/ the scan of bios/ into database.json: digests, aliases, indexes romrecipes/ romset identification, rebuilt pinned archives, each archive's recipe acquire/ catalog coverage and the searches for a missing file + games/ the games-on-card rules and the index the installer reads for them scraper/ upstream scrapers (libretro, batocera, recalbox...) scraper/targets/ hardware target scrapers (one *_targets_scraper.py per platform) exporter/ native format exporters (batocera, recalbox, emudeck...) diff --git a/wiki/tools.md b/wiki/tools.md index 83cabc8e7..97941ea3a 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -1369,6 +1369,7 @@ before a release (wiki/release-process.md). Its lines stay in | `profiling/` | What `profile_sync.py` runs: citations, anchoring, the report and its forms, version checks, detection, triage, and the guarded writes (recale, bump, prose realignment, `version_basis`) | | `romrecipes/` | What `romset_recipes.py` runs: romset recipes from profiles and DATs, the ROM pool addressed by crc32, identification and rebuilt pins, and the recipe of every archive held (`recipes/archives.json`: capture, member lookup by sha1, verified build) | | `acquire/` | What `provenance_report.py`, `auto_fetch.py`, `find_embedded.py` and `find_pinned_revision.py` run: dump-catalog coverage, dumps a held file already contains, the searches by hash, the rolling crc32 window, the walk of a file's upstream history | +| `games/` | What `game_rules.py` and `generate_games_index.py` run: the checks of the region and extra-file rules against the profiles and header readers, and each part of `install/games/` (setups, fallback sets, systems, arcade, the index and its coverage floors) | | `retired_files.py` | The record of files that left the collection, `retired.json`, which `generate_db.py` appends to and the site's lookup reads. `--backfill` rebuilds it from the history of `database.json` since content addresses were published (`--output` names another file) | | `dedup.py` | Deduplicate `bios/` (`--dry-run`, `--bios-dir`): byte-identical copies are deleted and one kept. Identical MAME sets under other names stay one file, named in `_mame_clones.json`. Trees addressed by path are left alone (`NODEDUP_DIRS`), under a folder of that name at any depth: BBK, Bungie, C-Dogs SDL, Ikemen GO, mame, PinMAME, RPG Maker, ScummVM, Softdisk, TheXTech, splitwolf, Theme Hospital, c64-emu, opentyrian, tzdata | | `identity.py` | One content filed under two identities: groups `bios/` by content and reports a group that crosses manufacturers outside `KNOWN_SHARED` (`--strict` exits 1, pipeline step 3a) |