From c764d9abf110c295125f2d61436c501d55695167 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:39:47 +0100 Subject: [PATCH] refactor: split the leaf modules libraries use model.region holds the region vocabulary, resolve.regions the selection that needs the cores a platform runs. The libraries behind identity.py, retired_files.py and torrentzip.py move to resolve.identity, model.retired and core.torrentzip, with their long docstrings; the commands stay where they are run from. The source_ref parts that cite a config or feature file move from scraper.shell_launchers to resolve.launcherrefs, so resolve no longer imports the scraper package. --- scripts/archive_build.py | 4 +- scripts/core/torrentzip.py | 207 ++++++++++++++++++++++ scripts/game_rules.py | 2 +- scripts/generate_db.py | 8 +- scripts/generate_games_index.py | 2 +- scripts/generate_pack.py | 17 +- scripts/generate_site.py | 10 +- scripts/identity.py | 115 +----------- scripts/manifestselect.py | 6 +- scripts/model/region.py | 196 ++++++++++++++++++++ scripts/model/retired.py | 101 +++++++++++ scripts/packextras.py | 8 +- scripts/packreadme.py | 2 +- scripts/packverify.py | 6 +- scripts/pipeline.py | 8 +- scripts/region_audit.py | 2 +- scripts/resolve/identity.py | 117 ++++++++++++ scripts/resolve/launcherrefs.py | 47 +++++ scripts/resolve/launchers.py | 6 +- scripts/{region.py => resolve/regions.py} | 197 +------------------- scripts/retired_files.py | 93 +--------- scripts/romset_recipes.py | 4 +- scripts/scraper/amberelec_launchers.py | 2 +- scripts/scraper/emudeck_launchers.py | 2 +- scripts/scraper/emudeck_scraper.py | 2 +- scripts/scraper/emuelec_launchers.py | 2 +- scripts/scraper/emuelec_scraper.py | 2 +- scripts/scraper/game_dat_importer.py | 2 +- scripts/scraper/knulli_launchers.py | 2 +- scripts/scraper/retrobat_launchers.py | 2 +- scripts/scraper/rocknix_launchers.py | 4 +- scripts/scraper/rocknix_scraper.py | 2 +- scripts/scraper/shell_launchers.py | 42 ----- scripts/torrentzip.py | 202 +-------------------- scripts/validate_schemas.py | 2 +- scripts/verify.py | 12 +- tests/test_archive_build.py | 2 +- tests/test_audit_regressions.py | 14 +- tests/test_doc_pages.py | 3 +- tests/test_game_catalogs.py | 2 +- tests/test_game_headers.py | 2 +- tests/test_identity.py | 2 +- tests/test_install_selection.py | 19 +- tests/test_launcher_evidence.py | 9 +- tests/test_pack_grouping.py | 4 +- tests/test_profile_checks.py | 6 +- tests/test_region.py | 79 +++++---- tests/test_region_agnostic_scan.py | 6 +- tests/test_region_groups.py | 6 +- tests/test_region_platform_index.py | 6 +- tests/test_retired_files.py | 20 +-- tests/test_romset_recipes.py | 4 +- tests/test_site_exports.py | 2 +- tests/test_torrentzip.py | 13 +- tests/test_verify_pack_choice.py | 4 +- wiki/profiling.md | 2 +- 56 files changed, 839 insertions(+), 804 deletions(-) create mode 100644 scripts/core/torrentzip.py create mode 100644 scripts/model/region.py create mode 100644 scripts/model/retired.py create mode 100644 scripts/resolve/identity.py create mode 100644 scripts/resolve/launcherrefs.py rename scripts/{region.py => resolve/regions.py} (64%) diff --git a/scripts/archive_build.py b/scripts/archive_build.py index 33a72922f..60597b30b 100644 --- a/scripts/archive_build.py +++ b/scripts/archive_build.py @@ -45,8 +45,8 @@ from typing import BinaryIO sys.path.insert(0, str(Path(__file__).resolve().parent)) -from torrentzip import Source as Readable -from torrentzip import write_torrentzip, zlib_ng_version +from core.torrentzip import Source as Readable +from core.torrentzip import write_torrentzip, zlib_ng_version REPO_ROOT = Path(__file__).resolve().parent.parent ARCHIVES_FILE = REPO_ROOT / "recipes" / "archives.json" diff --git a/scripts/core/torrentzip.py b/scripts/core/torrentzip.py new file mode 100644 index 000000000..693ccdce5 --- /dev/null +++ b/scripts/core/torrentzip.py @@ -0,0 +1,207 @@ +"""TorrentZip archive builder for MAME/FBNeo ROM sets. + +TorrentZip is the archive format MAME romset distributions use. It fixes +every non-content variable (member order, timestamps, compression level, +extra fields, attributes), so the archive bytes are a pure function of the +member names and their contents. + +That property makes it possible to rebuild a romset ZIP that matches an +upstream-published hash exactly, and to identify which romset revision a +published hash refers to. + +Usage: + from core.torrentzip import build_torrentzip, identify_romset + + data = build_torrentzip([("sp-s2.sp1", rom_bytes), ...]) + md5 = hashlib.md5(data).hexdigest() + +Command line: scripts/torrentzip.py. +""" + +from __future__ import annotations + +import functools +import hashlib +import io +import struct +import zipfile +import zlib +from collections.abc import Callable, Iterable +from pathlib import Path +from typing import Any, NamedTuple, Protocol + + +class Source(Protocol): + """An open member: read in chunks, closed by its ``with`` block.""" + + def read(self, size: int = -1, /) -> bytes: ... + def __enter__(self) -> Source: ... + def __exit__(self, *exc: Any) -> Any: ... + + +class Sink(Protocol): + def write(self, data: bytes | bytearray, /) -> int: ... + +# TorrentZip constants: 1996-12-24 23:32:00, deflate level 9 +_DOS_DATE = ((1996 - 1980) << 9) | (12 << 5) | 24 +_DOS_TIME = (23 << 11) | (32 << 5) | 0 +_COMMENT_PREFIX = "TORRENTZIPPED-" +# Members are read and deflated this much at a time. Deflate output does not +# depend on how its input is cut, so a 2 GiB disk image streams through in +# the same bytes a one-shot compression gives. +CHUNK = 16 * 1024 * 1024 +# A size or offset that does not fit 32 bits takes a ZIP64 field. No +# TorrentZip-conformant archive needs one, so their layout is untouched. +ZIP32_LIMIT = 0xFFFFFFFF +_ZIP64_MARK = 0xFFFFFFFF + + +class Written(NamedTuple): + """A member as the writer read it from its source.""" + + name: str + size: int + crc32: str + sha1: str + + +def zlib_ng_version(module: object = zlib) -> str | None: + """The zlib-ng version this interpreter deflates with, None for zlib. + + TorrentZip bytes are the output of zlib's level-9 deflate. Stock zlib + 1.2.13 to 1.3.2 reproduces every TorrentZip archive in the collection. + zlib-ng 2.2.4 (python.org 3.14 on Windows) reproduces 479 of 1,561 and + 2.3.3 545, and the two disagree with each other. + """ + version = getattr(module, "ZLIBNG_VERSION", None) + if version: + return str(version) + runtime = str(getattr(module, "ZLIB_RUNTIME_VERSION", "") or "") + return runtime if "zlib-ng" in runtime.lower() else None + + +def _deflate(stream: Source) -> tuple[bytes, Written]: + compressor = zlib.compressobj(9, zlib.DEFLATED, -15) + blob = bytearray() + crc, size, sha1 = 0, 0, hashlib.sha1() + while chunk := stream.read(CHUNK): + crc = zlib.crc32(chunk, crc) + size += len(chunk) + sha1.update(chunk) + blob += compressor.compress(chunk) + blob += compressor.flush() + return bytes(blob), Written("", size, f"{crc & 0xFFFFFFFF:08x}", sha1.hexdigest()) + + +def write_torrentzip( + sink: Sink, members: Iterable[tuple[str, Callable[[], Source]]] +) -> list[Written]: + """Write a TorrentZip archive to *sink*, one member in memory at a time. + + *members* pairs each name with a callable opening its bytes. Members are + sorted case-insensitively by name, as the format requires. Returns what + was read, in archive order, so a caller can check every member. + """ + ordered = sorted(members, key=lambda m: m[0].lower()) + central = bytearray() + offset = 0 + written: list[Written] = [] + for name, opener in ordered: + raw = name.encode("ascii") + with opener() as stream: + blob, read = _deflate(stream) + crc = int(read.crc32, 16) + written.append(read._replace(name=name)) + wide = read.size >= ZIP32_LIMIT or len(blob) >= ZIP32_LIMIT + far = offset >= ZIP32_LIMIT + local_extra = struct.pack("= ZIP32_LIMIT or len(central) >= ZIP32_LIMIT or count >= 0xFFFF: + end64 = cd_offset + len(central) + sink.write(struct.pack( + " bytes: + """Build a TorrentZip archive from (name, data) members. + + Members are sorted case-insensitively by name, as the format requires. + Returns the complete archive bytes. + """ + sink = io.BytesIO() + write_torrentzip( + sink, [(name, functools.partial(io.BytesIO, data)) for name, data in members] + ) + return sink.getvalue() + + +def rebuild_torrentzip(source: str | Path) -> bytes: + """Read an archive and return its TorrentZip normalization.""" + with zipfile.ZipFile(source) as zf: + members = [ + (info.filename, zf.read(info.filename)) + for info in zf.infolist() + if not info.is_dir() + ] + return build_torrentzip(members) + + +def is_torrentzip(source: str | Path) -> bool: + """Report whether an archive already carries the TorrentZip signature.""" + with zipfile.ZipFile(source) as zf: + return zf.comment.decode("ascii", "replace").startswith(_COMMENT_PREFIX) + + +def identify_romset( + recipes: dict[str, list[tuple[str, str]]], + atoms: dict[str, bytes], + target_md5: str, +) -> str | None: + """Find which recipe rebuilds to a target archive MD5. + + recipes maps a label (e.g. a MAME version) to a list of + (member name, CRC32 hex) pairs, and atoms maps CRC32 hex to ROM bytes. + Returns the matching label, or None when no recipe reproduces the hash. + """ + target = target_md5.lower() + for label, recipe in recipes.items(): + if any(crc.lower() not in atoms for _, crc in recipe): + continue + members = [(name, atoms[crc.lower()]) for name, crc in recipe] + if hashlib.md5(build_torrentzip(members)).hexdigest() == target: + return label + return None diff --git a/scripts/game_rules.py b/scripts/game_rules.py index f42565fd4..8de00e260 100644 --- a/scripts/game_rules.py +++ b/scripts/game_rules.py @@ -20,7 +20,7 @@ from dataclasses import dataclass from pathlib import Path from model.profiles import load_emulator_profiles -from region import REGIONS, normalize_declared +from model.region import REGIONS, normalize_declared from model.safeparse import yaml_load REGIONS_FILE = Path("games") / "regions.yml" diff --git a/scripts/generate_db.py b/scripts/generate_db.py index f705debb8..042757d52 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -33,7 +33,7 @@ from core.artifacts import ( from model.safeparse import require_yaml, yaml_load from model.profiles import source_yaml_paths from resolve.localfile import variant_base_name -import retired_files +from model import retired # Platform and profile aliases are read from YAML: without pyyaml the # database lost every one of them and the run still exited 0. @@ -542,13 +542,13 @@ def _generate(args: argparse.Namespace) -> int: output = Path(args.output) if output.is_file(): previous = json.loads(output.read_text(encoding="utf-8")) - left = retired_files.update( - retired_files.retired_path(output), previous, database, + left = retired.update( + retired.retired_path(output), previous, database, database["generated_at"][:10], ) if left: print(f" Left the collection: {left} files, recorded in " - f"{retired_files.retired_path(output)}") + f"{retired.retired_path(output)}") new_content = json.dumps(database, indent=2) written = write_if_changed(args.output, new_content) diff --git a/scripts/generate_games_index.py b/scripts/generate_games_index.py index 9ccd486a5..20beeb499 100644 --- a/scripts/generate_games_index.py +++ b/scripts/generate_games_index.py @@ -47,7 +47,7 @@ from model.profiles import load_emulator_profiles from model.platforms import load_platform_config, native_layer from core.artifacts import repository_output_lock from core.cli import run_cli -from region import normalize_declared +from model.region import normalize_declared from romfolders import ( ProfileResolver, Resolution, diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index a7409396b..daab4f2df 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -110,7 +110,8 @@ from resolve.standalone import platform_layouts, standalone_set from core.paths import sanitize_pack_path import packresolve from refresh_data_dirs import cache_lock, hold_data_dirs -import region as region_mod +from model import region +from resolve import regions as resolve_regions from manifestselect import SelectionIndex from resolve import slot as slot_mod import slots @@ -339,7 +340,7 @@ def _narrowings( " ".join(w.title() for w in slug.split("-")) for slug in regions ) applied.append( - (f"_{region_mod.region_tag(regions)}", f"region priority {pretty}") + (f"_{region.region_tag(regions)}", f"region priority {pretty}") ) if target_name: applied.append( @@ -841,13 +842,13 @@ def _select_variants( slot_overrides=options.get("slot_overrides"), ) if regions: - region_index = region_mod.platform_region_index( + region_index = resolve_regions.platform_region_index( config, emu_profiles or {}, target_cores ) - region_drops = region_mod.resolve_region_drops( + region_drops = resolve_regions.resolve_region_drops( region_groups, region_index, regions, held ) - region_fallbacks = region_mod.fallback_groups( + region_fallbacks = resolve_regions.fallback_groups( region_groups, region_index, regions ) @@ -3903,7 +3904,7 @@ def _refuse_unapplied_flags(args: argparse.Namespace, parser: argparse.ArgumentP args.regions = [] if args.region: try: - args.regions = region_mod.parse_requested(args.region) + args.regions = region.parse_requested(args.region) except ValueError as exc: parser.error(str(exc)) if args.manifest_targets: @@ -5225,11 +5226,11 @@ def _manifest_selection( data_registry=options.get("data_registry"), slot_overrides=options.get("slot_overrides"), ) - region_index = region_mod.platform_region_index( + region_index = resolve_regions.platform_region_index( config, emu_profiles, target_cores ) drops = ( - region_mod.resolve_region_drops(region_groups, region_index, regions, held) + resolve_regions.resolve_region_drops(region_groups, region_index, regions, held) if regions else set() ) diff --git a/scripts/generate_site.py b/scripts/generate_site.py index 4a5152aea..07dcd6ac3 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -88,7 +88,7 @@ from provenance_report import build_report, distinct_missing, profile_needs import sitemarkup as markup import siteentries import siteinputs -import retired_files +from model import retired as model_retired import siteagents import sitediagrams import sitestarlight @@ -1697,7 +1697,7 @@ def generate_data_exports( } write_lookup_shards( api, file_lookup_records(db, coverages, profiles, locations, members, consumers, - retired_files.load(_REPO_ROOT / "retired.json"), wanted), + model_retired.load(_REPO_ROOT / "retired.json"), wanted), generated_at, commit, ) for filename, (kind, items) in envelopes.items(): @@ -6814,7 +6814,7 @@ def _region_order() -> dict[str, int]: for every region is a region-free stand-in for the BIOS of each one: the PlayStation section opened on psxonpsp660.bin, which one emulator requires among the BIOS it accepts, above the scph files most read.""" - from region import REGION_TREE, WORLD + from model.region import REGION_TREE, WORLD ordered = [] for parent, members in REGION_TREE.items(): @@ -7460,7 +7460,7 @@ def _runs_without(words: _GroupWords) -> list[tuple[str, str]]: def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str], set[str]]: """The lines of the files picked by region, the emulators they answer and the names they give.""" - from region import _PARENT + from model.region import _PARENT group = words.group order = _region_order() @@ -8250,7 +8250,7 @@ def _region_words(value: object, most: int = 0) -> str: """A region: value in words. ``most`` caps the regions named, the rest counted: one Saturn BIOS serves seven.""" raw = value if isinstance(value, list) else [value] if value else [] - from region import label + from model.region import label words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw] if most and len(words) > most: diff --git a/scripts/identity.py b/scripts/identity.py index c2894fd2e..f24ebda8c 100644 --- a/scripts/identity.py +++ b/scripts/identity.py @@ -1,119 +1,8 @@ -"""Files whose bytes contradict the identity they are stored under. - -The collection is indexed by content, so one sha1 keeps one path. A file -copied into a second system's directory under a second name therefore becomes -invisible: the index answers with whichever path was recorded, and every -consumer of that name is served bytes belonging to another machine. That is -how the Amiga Kickstart came to be served as a Saturn cartridge firmware, and -nothing in the pipeline could see it, because on paper both names resolved. - -This walks the tree rather than the index, groups by content, and reports a -group whose paths sit under different manufacturers. A dump legitimately -shared by two systems of the same maker is common, one shared across makers -almost never is. -""" +"""Report one content stored under identities that disagree (resolve/identity.py).""" from __future__ import annotations -import hashlib -from dataclasses import dataclass -from pathlib import Path - -# A manufacturer directory holding files that genuinely belong to several -# machines, where a shared dump says nothing about a misfiling. -SHARED_TREES = frozenset({"Arcade", "Other"}) - -# One dump, two machines that really did share it. Each entry names the makers -# whose directories may hold it and the reason they do, so a crossing that is -# not on this list, or a further copy under a third maker, is a finding rather -# than noise. -KNOWN_SHARED: dict[str, tuple[frozenset[str], str]] = { - "45bedc4cbdeac66c7df59e9e599195c778d86a92": ( - frozenset({"Coleco", "Microsoft"}), - "ColecoVision BIOS, carried by MSX emulators for their ColecoVision " - "machine", - ), - "286b2e1fb21cc79851da01666db6c0b0e88f25e3": ( - frozenset({"Infocom", "ZC"}), - "one soundfont shipped by two interpreters", - ), -} - -CHUNK = 1 << 20 - - -@dataclass -class Duplicate: - """One content, stored under paths that disagree about what it is.""" - - sha1: str - size: int - paths: list[str] - manufacturers: list[str] - - @property - def names(self) -> list[str]: - return sorted({Path(p).name for p in self.paths}) - - -def _manufacturer(path: Path, root: Path) -> str: - """The vendor directory a path sits under, relative to the scanned root.""" - parts = path.relative_to(root).parts - return parts[0] if len(parts) > 1 else "" - - -def _sha1(path: Path) -> str: - digest = hashlib.sha1() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(CHUNK), b""): - digest.update(chunk) - return digest.hexdigest() - - -def scan(bios_dir: str = "bios") -> list[Duplicate]: - """Group the tree by content and keep the groups that cross makers. - - Only files that share a size can share a content, so a size held by one - file is never read: hashing the whole tree read 18 GB on every pipeline. - """ - by_size: dict[int, list[Path]] = {} - root = Path(bios_dir) - for path in sorted(root.rglob("*")): - if path.is_file(): - by_size.setdefault(path.stat().st_size, []).append(path) - by_content: dict[str, list[Path]] = {} - for paths in by_size.values(): - if len(paths) < 2: - continue - for path in paths: - by_content.setdefault(_sha1(path), []).append(path) - - found: list[Duplicate] = [] - for sha1, paths in by_content.items(): - if len(paths) < 2: - continue - makers = {_manufacturer(p, root) for p in paths} - SHARED_TREES - if sha1 in KNOWN_SHARED and makers <= KNOWN_SHARED[sha1][0]: - continue - names = {p.name for p in paths} - if len(makers) > 1 and len(names) > 1: - found.append( - Duplicate( - sha1=sha1, - size=paths[0].stat().st_size, - paths=[str(p) for p in paths], - manufacturers=sorted(makers), - ) - ) - return sorted(found, key=lambda d: d.paths[0]) - - -def format_duplicate(duplicate: Duplicate) -> str: - """One line naming the content and every identity it answers to.""" - return ( - f"{duplicate.sha1[:12]} ({duplicate.size} bytes) is stored as " - + " and as ".join(duplicate.paths) - ) +from resolve.identity import format_duplicate, scan def main() -> int: diff --git a/scripts/manifestselect.py b/scripts/manifestselect.py index 8e8a5c481..31bef99af 100644 --- a/scripts/manifestselect.py +++ b/scripts/manifestselect.py @@ -17,7 +17,7 @@ from __future__ import annotations from dataclasses import dataclass -import region as region_mod +from resolve import regions as resolve_regions from resolve import slot as slot_mod from model.systems import _norm_system_id from core.paths import sanitize_pack_path @@ -117,7 +117,7 @@ class SelectionIndex: return out if dest in self.slots: out["slot"] = self.slots[dest] - regions = region_mod.lookup_regions(self.region_index, dest, name) + regions = resolve_regions.lookup_regions(self.region_index, dest, name) if not regions: return out out["regions"] = sorted(regions) @@ -129,7 +129,7 @@ class SelectionIndex: out["region_system_groups"] = sorted(declared) # The code's search rank decides whether a world file may withdraw # this one when no region matches. - priority = region_mod.lookup_priority(self.region_index, dest, name) + priority = resolve_regions.lookup_priority(self.region_index, dest, name) if priority is not None: out["priority"] = priority return out diff --git a/scripts/model/region.py b/scripts/model/region.py new file mode 100644 index 000000000..62273fa64 --- /dev/null +++ b/scripts/model/region.py @@ -0,0 +1,196 @@ +"""Region vocabulary: territories, aliases, labels and their order.""" + +from __future__ import annotations + + + + +WORLD = "world" + +# Two levels only: super-region -> member territories. +REGION_TREE: dict[str, frozenset[str]] = { + "north-america": frozenset({"canada"}), + "latin-america": frozenset({"brazil", "mexico", "argentina"}), + "europe": frozenset( + { + "uk", + "france", + "germany", + "italy", + "spain", + "netherlands", + "portugal", + "greece", + "poland", + "russia", + "sweden", + "norway", + "denmark", + "finland", + } + ), + "asia": frozenset( + { + "japan", + "south-korea", + "china", + "taiwan", + "hong-kong", + "singapore", + "india", + "asia-ntsc", + "asia-pal", + } + ), + "oceania": frozenset({"australia", "new-zealand"}), +} + +# Hardware areas that fuse territory and signal standard, with the territories +# the code serves through them. Mednafen's Saturn SMPC area 0x2 is "For TAIWAN +# and PHILIPINES" and its area option offers it as "Taiwan", area 0xA as +# "China" (mednafen/ss/ss.cpp:1119, 2363-2364 in the mednafen_stv port). +# kronos tags the ST-V BIOS epr-19854.ic8 taiwan and mednafen_stv tags it +# asia-ntsc: a request in either spelling has to reach the other. +AREA_TERRITORIES: dict[str, frozenset[str]] = { + "asia-ntsc": frozenset({"taiwan"}), + "asia-pal": frozenset({"china"}), +} + +_PARENT: dict[str, str] = { + member: parent for parent, members in REGION_TREE.items() for member in members +} + +REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(_PARENT)) + +# Accepted on the CLI and for legacy profile values. Every territory also +# answers to its ISO 3166-1 code: `au` alone was unknown, and the closest +# spelling offered first was `auto`, which means world. +ALIASES: dict[str, str] = { + "jp": "japan", + "ntsc-j": "japan", + "us": "north-america", + "usa": "north-america", + "na": "north-america", + "ntsc-u": "north-america", + "eu": "europe", + "pal": "europe", + "kr": "south-korea", + "korea": "south-korea", + "auto": WORLD, + "gb": "uk", + "ca": "canada", + "br": "brazil", + "mx": "mexico", + "ar": "argentina", + "fr": "france", + "de": "germany", + "it": "italy", + "es": "spain", + "nl": "netherlands", + "pt": "portugal", + "gr": "greece", + "pl": "poland", + "ru": "russia", + "se": "sweden", + "no": "norway", + "dk": "denmark", + "fi": "finland", + "cn": "china", + "tw": "taiwan", + "hk": "hong-kong", + "sg": "singapore", + "in": "india", + "au": "australia", + "nz": "new-zealand", +} + + +# Slugs a person does not write title-cased: "Asia Ntsc" read as machine text. +LABELS: dict[str, str] = { + "uk": "UK", + "asia-ntsc": "Asia (NTSC)", + "asia-pal": "Asia (PAL)", +} + + +def label(slug: str) -> str: + """A region slug in words: north-america as North America.""" + return LABELS.get(slug) or " ".join(word.title() for word in slug.split("-")) + + +def unknown_region_message(raw: str, aliases: dict[str, str], regions: frozenset[str]) -> str: + """What to type instead: the closest spellings, then every short form. + + `unknown region: 'uss'` left the user to read the source for `us`. + """ + import difflib + + spelled = raw.strip() + close = difflib.get_close_matches(spelled.lower(), [*aliases, *regions], n=3, cutoff=0.5) + hint = f" Close matches: {', '.join(close)}." if close else "" + return ( + f"unknown region: {spelled}.{hint} Short forms: {', '.join(aliases)}; " + f"regions: {', '.join(sorted(regions))}" + ) + + +def _canonical(raw: str) -> str: + """Map one token to a canonical region slug.""" + key = raw.strip().lower() + key = ALIASES.get(key, key) + if key not in REGIONS: + raise ValueError(unknown_region_message(raw, ALIASES, REGIONS)) + return key + + +def comparable(a: str, b: str) -> bool: + """True when two regions are equal, parent and child, or an area and a + territory it serves.""" + return ( + a == b + or _PARENT.get(a) == b + or _PARENT.get(b) == a + or a in AREA_TERRITORIES.get(b, ()) + or b in AREA_TERRITORIES.get(a, ()) + ) + + +def normalize_declared(raw: str | list | None) -> set[str]: + """Normalise a profile region: value to canonical slugs.""" + if raw is None: + return set() + values = raw if isinstance(raw, list) else [raw] + return {_canonical(str(v)) for v in values} + + +def parse_requested(raw: str) -> list[str]: + """Parse a comma-separated --region value into an ordered priority list.""" + out: list[str] = [] + for part in raw.split(","): + if not part.strip(): + continue + slug = _canonical(part) + if slug not in out: + out.append(slug) + if not out: + raise ValueError("--region requires at least one region") + return out + + +def rank(file_regions: set[str], requested: list[str]) -> int: + """Priority index of a file, lower is better. + + Returns len(requested) when no requested region is comparable, the implicit + lowest rank that keeps a group from ever being emptied. + """ + for i, req in enumerate(requested): + if any(comparable(req, fr) for fr in file_regions): + return i + return len(requested) + + +def region_tag(requested: list[str]) -> str: + """Pack filename tag for a requested priority list.""" + return "_".join( + "".join(part.title() for part in slug.split("-")) for slug in requested + ) diff --git a/scripts/model/retired.py b/scripts/model/retired.py new file mode 100644 index 000000000..a6ba0a252 --- /dev/null +++ b/scripts/model/retired.py @@ -0,0 +1,101 @@ +"""Files that left the collection, and the file that took their place. + +A file's content address (files/?sha1=, #sha1-<12> on its card) is +published, and a published address never stops answering. When a rebuild +of database.json drops a sha1, the file it named is recorded here: its +name, its last path, its hashes, the day it left and the sha1 the +collection now holds at that path, or under that name in that folder. +The site's lookup reads the record and answers with it. + +The record is append-only, written by generate_db.py beside the database. +A sha1 that comes back leaves it. `--backfill` rebuilds it from the +history of database.json since content addresses were published. + +The command (`--backfill`) is scripts/retired_files.py. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from core.artifacts import write_if_changed +from core.paths import REPO_ROOT + + +RETIRED_FILE = REPO_ROOT / "retired.json" +# The commit that published content addresses: 0d586ef6b, 2026-10-19. +FIRST_ADDRESSED = "0d586ef6b" +KEPT_FIELDS = ("name", "path", "size", "md5", "crc32", "sha256") + + +def retired_path(database: str | Path) -> Path: + """The record kept beside a database file.""" + return Path(database).with_name("retired.json") + + +def _successor(entry: dict, by_path: dict[str, str], + by_name: dict[str, list[tuple[str, str]]]) -> str | None: + """The sha1 the new database holds at the entry's path, else under its + name in the same folder, else the one file of that name: a2diskiing.zip + was rebuilt from its recipe and filed under Apple II the same day.""" + path = str(entry.get("path", "")) + if path in by_path: + return by_path[path] + named = by_name.get(str(entry.get("name", "")), []) + folder = path.rsplit("/", 1)[0] + beside = [sha1 for sha1, other in named if other.rsplit("/", 1)[0] == folder] + for found in (beside, [sha1 for sha1, _other in named]): + if len(found) == 1: + return found[0] + return None + + +def retired_between(old: dict, new: dict, day: str) -> dict[str, dict]: + """sha1 -> record, for each file of *old* that *new* no longer holds.""" + old_files = old.get("files") or {} + new_files = new.get("files") or {} + by_path = {str(e.get("path", "")): sha1 for sha1, e in new_files.items()} + by_name: dict[str, list[tuple[str, str]]] = {} + for sha1, e in new_files.items(): + by_name.setdefault(str(e.get("name", "")), []).append((sha1, str(e.get("path", "")))) + records = {} + for sha1 in sorted(set(old_files) - set(new_files)): + entry = old_files[sha1] + record = {key: entry[key] for key in KEPT_FIELDS if entry.get(key) not in (None, "")} + record["left"] = day + successor = _successor(entry, by_path, by_name) + if successor: + record["successor"] = successor + records[sha1] = record + return records + + +def merge(record: dict[str, dict], left: dict[str, dict], new: dict) -> dict[str, dict]: + """The record with *left* added, first departure kept, and every sha1 + the new database holds again taken out.""" + held = set(new.get("files") or {}) + merged = {sha1: entry for sha1, entry in record.items() if sha1 not in held} + for sha1, entry in left.items(): + merged.setdefault(sha1, entry) + return dict(sorted(merged.items())) + + +def load(path: Path) -> dict[str, dict]: + if not path.is_file(): + return {} + return json.loads(path.read_text(encoding="utf-8")).get("files") or {} + + +def dump(records: dict[str, dict]) -> str: + return json.dumps({"schema_version": 1, "files": records}, indent=1, sort_keys=True) + "\n" + + +def update(path: Path, old: dict, new: dict, day: str) -> int: + """Records what *new* dropped from *old*. Returns how many left now.""" + left = retired_between(old, new, day) + record = load(path) + merged = merge(record, left, new) + if merged != record: + write_if_changed(str(path), dump(merged)) + return len(set(left) - set(record)) diff --git a/scripts/packextras.py b/scripts/packextras.py index 49be8ebed..716c42cac 100644 --- a/scripts/packextras.py +++ b/scripts/packextras.py @@ -27,7 +27,7 @@ from core.paths import sanitize_pack_path from resolve.content import declares_shape, shape_fits, size_fits from resolve.validation import deliverable, read_from_save_dir, read_from_system_dir from packpaths import libretro_systems, save_destination, save_layout -from region import FILE_GROUP +from resolve.regions import FILE_GROUP if TYPE_CHECKING: from typing_extensions import Unpack @@ -2321,11 +2321,11 @@ def emulator_region_drops( BIOS at all. ``zip_contents`` and ``data_registry`` are the ones the emulator pack resolves with. """ - import region as region_mod + from resolve import regions as resolve_regions from packpaths import _resolve_destination from resolve.validation import _build_validation_index, filter_files_by_mode - region_index = region_mod.build_region_index(dict(selected)) + region_index = resolve_regions.build_region_index(dict(selected)) region_groups: dict[str, list[tuple[str, str]]] = {} held: set[str] | None = set() if db is not None else None validation_index = _build_validation_index(dict(selected)) if db is not None else {} @@ -2345,7 +2345,7 @@ def emulator_region_drops( zip_contents, data_registry, ): held.add(dest) - return region_mod.resolve_region_drops(region_groups, region_index, regions, held) + return resolve_regions.resolve_region_drops(region_groups, region_index, regions, held) class SpareOptions(TypedDict, total=False): diff --git a/scripts/packreadme.py b/scripts/packreadme.py index 7a0716a09..040b70bdc 100644 --- a/scripts/packreadme.py +++ b/scripts/packreadme.py @@ -8,7 +8,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, TypedDict from packextras import reject_unknown -from region import label as region_label +from model.region import label as region_label from siteguides import INSTALL_PS1, INSTALL_SH, pack_manual if TYPE_CHECKING: diff --git a/scripts/packverify.py b/scripts/packverify.py index 6bab7cec8..4f7fd893f 100644 --- a/scripts/packverify.py +++ b/scripts/packverify.py @@ -31,7 +31,7 @@ import os from packextras import platform_region_groups from packpaths import _flat from resolve.nativemode import reads_file_contents -import region as region_mod +from resolve import regions as resolve_regions import slots from packresolve import resolve_declaration, resolve_file from resolve.categories import BIOS, EntryCategories @@ -776,7 +776,7 @@ def _region_drops( region_drops: set[str] = set() if not opts.regions: return region_drops - region_index = region_mod.platform_region_index( + region_index = resolve_regions.platform_region_index( config, emu_profiles, target_cores ) held: set[str] = set() @@ -800,7 +800,7 @@ def _region_drops( target_cores=target_cores, source=opts.source, ) if db is not None else None, ) - return region_mod.resolve_region_drops( + return resolve_regions.resolve_region_drops( region_groups, region_index, opts.regions, held ) diff --git a/scripts/pipeline.py b/scripts/pipeline.py index e4d71468d..2f71afc0a 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -552,11 +552,11 @@ def emulator_variants(profiles: list[dict], full: bool) -> list[tuple[str, dict] sampled as check_narrowed_packs samples them unless *full*. A profile without a regional file has nothing --region could withdraw. """ - import region as region_mod + from model import region regions = sorted({ r for profile in profiles for fe in profile.get("files") or [] - for r in region_mod.normalize_declared(fe.get("region")) + for r in region.normalize_declared(fe.get("region")) }) variants: list[tuple[str, dict]] = [("", {}), (" --required-only", {"required_only": True})] variants += [ @@ -701,11 +701,11 @@ def narrowed_variants( target, every system, --no-game-data and --required-only. Without *full*, regions, targets and systems are sampled (_matrix_coverage). """ - import region as region_mod + from resolve import regions as resolve_regions from model.targets import list_available_targets regions = sorted({ - r for entry in region_mod.platform_region_index(config, profiles).values() + r for entry in resolve_regions.platform_region_index(config, profiles).values() for r in entry["regions"] }) targets = [t["name"] for t in list_available_targets(platform, platforms_dir)] diff --git a/scripts/region_audit.py b/scripts/region_audit.py index 909edcac8..825e6d564 100644 --- a/scripts/region_audit.py +++ b/scripts/region_audit.py @@ -18,7 +18,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -import region +from model import region from model.database import load_database from model.profiles import load_emulator_profiles from resolve.localfile import resolve_local_file diff --git a/scripts/resolve/identity.py b/scripts/resolve/identity.py new file mode 100644 index 000000000..d33526ecc --- /dev/null +++ b/scripts/resolve/identity.py @@ -0,0 +1,117 @@ +"""Files whose bytes contradict the identity they are stored under. + +The collection is indexed by content, so one sha1 keeps one path. A file +copied into a second system's directory under a second name therefore becomes +invisible: the index answers with whichever path was recorded, and every +consumer of that name is served bytes belonging to another machine. That is +how the Amiga Kickstart came to be served as a Saturn cartridge firmware, and +nothing in the pipeline could see it, because on paper both names resolved. + +This walks the tree rather than the index, groups by content, and reports a +group whose paths sit under different manufacturers. A dump legitimately +shared by two systems of the same maker is common, one shared across makers +almost never is. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from pathlib import Path + + +# A manufacturer directory holding files that genuinely belong to several +# machines, where a shared dump says nothing about a misfiling. +SHARED_TREES = frozenset({"Arcade", "Other"}) + +# One dump, two machines that really did share it. Each entry names the makers +# whose directories may hold it and the reason they do, so a crossing that is +# not on this list, or a further copy under a third maker, is a finding rather +# than noise. +KNOWN_SHARED: dict[str, tuple[frozenset[str], str]] = { + "45bedc4cbdeac66c7df59e9e599195c778d86a92": ( + frozenset({"Coleco", "Microsoft"}), + "ColecoVision BIOS, carried by MSX emulators for their ColecoVision " + "machine", + ), + "286b2e1fb21cc79851da01666db6c0b0e88f25e3": ( + frozenset({"Infocom", "ZC"}), + "one soundfont shipped by two interpreters", + ), +} + +CHUNK = 1 << 20 + + +@dataclass +class Duplicate: + """One content, stored under paths that disagree about what it is.""" + + sha1: str + size: int + paths: list[str] + manufacturers: list[str] + + @property + def names(self) -> list[str]: + return sorted({Path(p).name for p in self.paths}) + + +def _manufacturer(path: Path, root: Path) -> str: + """The vendor directory a path sits under, relative to the scanned root.""" + parts = path.relative_to(root).parts + return parts[0] if len(parts) > 1 else "" + + +def _sha1(path: Path) -> str: + digest = hashlib.sha1() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(CHUNK), b""): + digest.update(chunk) + return digest.hexdigest() + + +def scan(bios_dir: str = "bios") -> list[Duplicate]: + """Group the tree by content and keep the groups that cross makers. + + Only files that share a size can share a content, so a size held by one + file is never read: hashing the whole tree read 18 GB on every pipeline. + """ + by_size: dict[int, list[Path]] = {} + root = Path(bios_dir) + for path in sorted(root.rglob("*")): + if path.is_file(): + by_size.setdefault(path.stat().st_size, []).append(path) + by_content: dict[str, list[Path]] = {} + for paths in by_size.values(): + if len(paths) < 2: + continue + for path in paths: + by_content.setdefault(_sha1(path), []).append(path) + + found: list[Duplicate] = [] + for sha1, paths in by_content.items(): + if len(paths) < 2: + continue + makers = {_manufacturer(p, root) for p in paths} - SHARED_TREES + if sha1 in KNOWN_SHARED and makers <= KNOWN_SHARED[sha1][0]: + continue + names = {p.name for p in paths} + if len(makers) > 1 and len(names) > 1: + found.append( + Duplicate( + sha1=sha1, + size=paths[0].stat().st_size, + paths=[str(p) for p in paths], + manufacturers=sorted(makers), + ) + ) + return sorted(found, key=lambda d: d.paths[0]) + + +def format_duplicate(duplicate: Duplicate) -> str: + """One line naming the content and every identity it answers to.""" + return ( + f"{duplicate.sha1[:12]} ({duplicate.size} bytes) is stored as " + + " and as ".join(duplicate.paths) + ) diff --git a/scripts/resolve/launcherrefs.py b/scripts/resolve/launcherrefs.py new file mode 100644 index 000000000..0a2956b36 --- /dev/null +++ b/scripts/resolve/launcherrefs.py @@ -0,0 +1,47 @@ +"""The parts of a launcher record's source_ref that cite a config or feature file.""" + +from __future__ import annotations + +import re + + +# The files a platform ships as configuration: an emulator reads them, the +# platform's code never runs them. Batocera's .yml lists and an EmuELEC .opt +# only offer the values a menu option takes. +_CONFIG_FILE = re.compile( + r"\.(?:ini|cfg|conf|rc|rc_\w+|opt|bml|toml|uae|template|yml|yaml)$", re.IGNORECASE +) +_FEATURE_FILE = re.compile(r"(?:^|/)es_features[^/]*$|\.opt$", re.IGNORECASE) + + +def split_ref(ref: str) -> list[str]: + """The parts of a source_ref, each "path:lines", a bare line span + continuing the path before it.""" + parts: list[str] = [] + for part in (p.strip() for p in ref.split(", ")): + if not part: + continue + if re.fullmatch(r"\d+(?:-\d+)?", part) and parts: + parts[-1] += f", {part}" + else: + parts.append(part) + return parts + + +def ref_path(part: str) -> str: + return part.rsplit(":", 1)[0] if re.search(r":\d", part) else part + + +def config_ref(ref: str) -> list[str]: + """The parts of a source_ref that cite a config, option or feature file. + + Such a part proves what the file says, never that an emulator reads it: + melonDS.ini keys are written on ROCKNIX for a build that reads them only + when another key is set. + """ + return [part for part in split_ref(ref) if _CONFIG_FILE.search(ref_path(part))] + + +def is_feature_ref(part: str) -> bool: + """Whether a source_ref part cites a file that lists a menu option's values.""" + return bool(_FEATURE_FILE.search(ref_path(part))) diff --git a/scripts/resolve/launchers.py b/scripts/resolve/launchers.py index 6d929eb84..a4ba962c4 100644 --- a/scripts/resolve/launchers.py +++ b/scripts/resolve/launchers.py @@ -288,7 +288,7 @@ def config_target(record: dict) -> tuple[str, list[str]]: if "." not in head or head.startswith("<"): # The file is the one the record installs, named by its path or, # when a variable spells the path, by the config file it cites. - from scraper.shell_launchers import config_ref, is_feature_ref, ref_path + from resolve.launcherrefs import config_ref, is_feature_ref, ref_path installed = str((record.get("installs") or {}).get("path") or "").rsplit("/", 1)[-1] cited = [ @@ -453,7 +453,7 @@ def config_evidence( values a menu offers: it goes in ``choices_from``, beside the code that writes the choice, and such a record needs (c) and (d) too. """ - from scraper.shell_launchers import config_ref, is_feature_ref + from resolve.launcherrefs import config_ref, is_feature_ref cited = config_ref(str(record.get("source_ref") or "")) choices = str(record.get("choices_from") or "") @@ -521,7 +521,7 @@ def _profiles_or_repo(profiles: Mapping[str, dict] | None) -> Mapping[str, dict] def _cites_config(record: dict) -> bool: - from scraper.shell_launchers import config_ref + from resolve.launcherrefs import config_ref return bool(record.get("choices_from")) or bool(config_ref(str(record.get("source_ref") or ""))) diff --git a/scripts/region.py b/scripts/resolve/regions.py similarity index 64% rename from scripts/region.py rename to scripts/resolve/regions.py index b826b00af..7cc271f48 100644 --- a/scripts/region.py +++ b/scripts/resolve/regions.py @@ -1,201 +1,8 @@ -"""Region vocabulary and ordered-priority selection for pack generation. - -A file's region: value is the region the emulator code selects it for, not the -region of the dump. Signal standard has no field of its own. It survives only -inside slugs whose hardware register fuses the two axes (Saturn SMPC areas). -""" +"""Region-ordered selection of the files a platform's cores declare.""" from __future__ import annotations -WORLD = "world" - -# Two levels only: super-region -> member territories. -REGION_TREE: dict[str, frozenset[str]] = { - "north-america": frozenset({"canada"}), - "latin-america": frozenset({"brazil", "mexico", "argentina"}), - "europe": frozenset( - { - "uk", - "france", - "germany", - "italy", - "spain", - "netherlands", - "portugal", - "greece", - "poland", - "russia", - "sweden", - "norway", - "denmark", - "finland", - } - ), - "asia": frozenset( - { - "japan", - "south-korea", - "china", - "taiwan", - "hong-kong", - "singapore", - "india", - "asia-ntsc", - "asia-pal", - } - ), - "oceania": frozenset({"australia", "new-zealand"}), -} - -# Hardware areas that fuse territory and signal standard, with the territories -# the code serves through them. Mednafen's Saturn SMPC area 0x2 is "For TAIWAN -# and PHILIPINES" and its area option offers it as "Taiwan", area 0xA as -# "China" (mednafen/ss/ss.cpp:1119, 2363-2364 in the mednafen_stv port). -# kronos tags the ST-V BIOS epr-19854.ic8 taiwan and mednafen_stv tags it -# asia-ntsc: a request in either spelling has to reach the other. -AREA_TERRITORIES: dict[str, frozenset[str]] = { - "asia-ntsc": frozenset({"taiwan"}), - "asia-pal": frozenset({"china"}), -} - -_PARENT: dict[str, str] = { - member: parent for parent, members in REGION_TREE.items() for member in members -} - -REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(_PARENT)) - -# Accepted on the CLI and for legacy profile values. Every territory also -# answers to its ISO 3166-1 code: `au` alone was unknown, and the closest -# spelling offered first was `auto`, which means world. -ALIASES: dict[str, str] = { - "jp": "japan", - "ntsc-j": "japan", - "us": "north-america", - "usa": "north-america", - "na": "north-america", - "ntsc-u": "north-america", - "eu": "europe", - "pal": "europe", - "kr": "south-korea", - "korea": "south-korea", - "auto": WORLD, - "gb": "uk", - "ca": "canada", - "br": "brazil", - "mx": "mexico", - "ar": "argentina", - "fr": "france", - "de": "germany", - "it": "italy", - "es": "spain", - "nl": "netherlands", - "pt": "portugal", - "gr": "greece", - "pl": "poland", - "ru": "russia", - "se": "sweden", - "no": "norway", - "dk": "denmark", - "fi": "finland", - "cn": "china", - "tw": "taiwan", - "hk": "hong-kong", - "sg": "singapore", - "in": "india", - "au": "australia", - "nz": "new-zealand", -} - - -# Slugs a person does not write title-cased: "Asia Ntsc" read as machine text. -LABELS: dict[str, str] = { - "uk": "UK", - "asia-ntsc": "Asia (NTSC)", - "asia-pal": "Asia (PAL)", -} - - -def label(slug: str) -> str: - """A region slug in words: north-america as North America.""" - return LABELS.get(slug) or " ".join(word.title() for word in slug.split("-")) - - -def unknown_region_message(raw: str, aliases: dict[str, str], regions: frozenset[str]) -> str: - """What to type instead: the closest spellings, then every short form. - - `unknown region: 'uss'` left the user to read the source for `us`. - """ - import difflib - - spelled = raw.strip() - close = difflib.get_close_matches(spelled.lower(), [*aliases, *regions], n=3, cutoff=0.5) - hint = f" Close matches: {', '.join(close)}." if close else "" - return ( - f"unknown region: {spelled}.{hint} Short forms: {', '.join(aliases)}; " - f"regions: {', '.join(sorted(regions))}" - ) - - -def _canonical(raw: str) -> str: - """Map one token to a canonical region slug.""" - key = raw.strip().lower() - key = ALIASES.get(key, key) - if key not in REGIONS: - raise ValueError(unknown_region_message(raw, ALIASES, REGIONS)) - return key - - -def comparable(a: str, b: str) -> bool: - """True when two regions are equal, parent and child, or an area and a - territory it serves.""" - return ( - a == b - or _PARENT.get(a) == b - or _PARENT.get(b) == a - or a in AREA_TERRITORIES.get(b, ()) - or b in AREA_TERRITORIES.get(a, ()) - ) - - -def normalize_declared(raw: str | list | None) -> set[str]: - """Normalise a profile region: value to canonical slugs.""" - if raw is None: - return set() - values = raw if isinstance(raw, list) else [raw] - return {_canonical(str(v)) for v in values} - - -def parse_requested(raw: str) -> list[str]: - """Parse a comma-separated --region value into an ordered priority list.""" - out: list[str] = [] - for part in raw.split(","): - if not part.strip(): - continue - slug = _canonical(part) - if slug not in out: - out.append(slug) - if not out: - raise ValueError("--region requires at least one region") - return out - - -def rank(file_regions: set[str], requested: list[str]) -> int: - """Priority index of a file, lower is better. - - Returns len(requested) when no requested region is comparable, the implicit - lowest rank that keeps a group from ever being emptied. - """ - for i, req in enumerate(requested): - if any(comparable(req, fr) for fr in file_regions): - return i - return len(requested) - - -def region_tag(requested: list[str]) -> str: - """Pack filename tag for a requested priority list.""" - return "_".join( - "".join(part.title() for part in slug.split("-")) for slug in requested - ) +from model.region import WORLD, normalize_declared, rank def platform_region_index( diff --git a/scripts/retired_files.py b/scripts/retired_files.py index 877215e83..27607ba7c 100644 --- a/scripts/retired_files.py +++ b/scripts/retired_files.py @@ -1,16 +1,5 @@ #!/usr/bin/env python3 -"""Files that left the collection, and the file that took their place. - -A file's content address (files/?sha1=, #sha1-<12> on its card) is -published, and a published address never stops answering. When a rebuild -of database.json drops a sha1, the file it named is recorded here: its -name, its last path, its hashes, the day it left and the sha1 the -collection now holds at that path, or under that name in that folder. -The site's lookup reads the record and answers with it. - -The record is append-only, written by generate_db.py beside the database. -A sha1 that comes back leaves it. `--backfill` rebuilds it from the -history of database.json since content addresses were published. +"""Rebuild retired.json from the history of database.json (model/retired.py). Usage: python scripts/retired_files.py --backfill @@ -27,84 +16,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from core.cli import run_cli from core.artifacts import write_if_changed - -REPO_ROOT = Path(__file__).resolve().parents[1] -RETIRED_FILE = REPO_ROOT / "retired.json" -# The commit that published content addresses: 0d586ef6b, 2026-10-19. -FIRST_ADDRESSED = "0d586ef6b" -KEPT_FIELDS = ("name", "path", "size", "md5", "crc32", "sha256") - - -def retired_path(database: str | Path) -> Path: - """The record kept beside a database file.""" - return Path(database).with_name("retired.json") - - -def _successor(entry: dict, by_path: dict[str, str], - by_name: dict[str, list[tuple[str, str]]]) -> str | None: - """The sha1 the new database holds at the entry's path, else under its - name in the same folder, else the one file of that name: a2diskiing.zip - was rebuilt from its recipe and filed under Apple II the same day.""" - path = str(entry.get("path", "")) - if path in by_path: - return by_path[path] - named = by_name.get(str(entry.get("name", "")), []) - folder = path.rsplit("/", 1)[0] - beside = [sha1 for sha1, other in named if other.rsplit("/", 1)[0] == folder] - for found in (beside, [sha1 for sha1, _other in named]): - if len(found) == 1: - return found[0] - return None - - -def retired_between(old: dict, new: dict, day: str) -> dict[str, dict]: - """sha1 -> record, for each file of *old* that *new* no longer holds.""" - old_files = old.get("files") or {} - new_files = new.get("files") or {} - by_path = {str(e.get("path", "")): sha1 for sha1, e in new_files.items()} - by_name: dict[str, list[tuple[str, str]]] = {} - for sha1, e in new_files.items(): - by_name.setdefault(str(e.get("name", "")), []).append((sha1, str(e.get("path", "")))) - records = {} - for sha1 in sorted(set(old_files) - set(new_files)): - entry = old_files[sha1] - record = {key: entry[key] for key in KEPT_FIELDS if entry.get(key) not in (None, "")} - record["left"] = day - successor = _successor(entry, by_path, by_name) - if successor: - record["successor"] = successor - records[sha1] = record - return records - - -def merge(record: dict[str, dict], left: dict[str, dict], new: dict) -> dict[str, dict]: - """The record with *left* added, first departure kept, and every sha1 - the new database holds again taken out.""" - held = set(new.get("files") or {}) - merged = {sha1: entry for sha1, entry in record.items() if sha1 not in held} - for sha1, entry in left.items(): - merged.setdefault(sha1, entry) - return dict(sorted(merged.items())) - - -def load(path: Path) -> dict[str, dict]: - if not path.is_file(): - return {} - return json.loads(path.read_text(encoding="utf-8")).get("files") or {} - - -def dump(records: dict[str, dict]) -> str: - return json.dumps({"schema_version": 1, "files": records}, indent=1, sort_keys=True) + "\n" - - -def update(path: Path, old: dict, new: dict, day: str) -> int: - """Records what *new* dropped from *old*. Returns how many left now.""" - left = retired_between(old, new, day) - record = load(path) - merged = merge(record, left, new) - if merged != record: - write_if_changed(str(path), dump(merged)) - return len(set(left) - set(record)) +from core.paths import REPO_ROOT +from model.retired import FIRST_ADDRESSED, RETIRED_FILE, dump, merge, retired_between def _git(*args: str) -> str: diff --git a/scripts/romset_recipes.py b/scripts/romset_recipes.py index 820a59d9c..b4845d796 100644 --- a/scripts/romset_recipes.py +++ b/scripts/romset_recipes.py @@ -57,7 +57,7 @@ from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config from model.registry import list_registered_platforms -from torrentzip import build_torrentzip, is_torrentzip +from core.torrentzip import build_torrentzip, is_torrentzip ARCHIVES_FILE = Path(__file__).resolve().parent.parent / "recipes" / "archives.json" @@ -232,7 +232,7 @@ DIGEST_CACHE = Path(__file__).resolve().parent.parent / ".cache" / "romset_diges # The writer's own source is part of every key: a change to how TorrentZip # bytes are laid out invalidates every digest it produced. _WRITER = hashlib.sha256( - (Path(__file__).resolve().parent / "torrentzip.py").read_bytes() + (Path(__file__).resolve().parent / "core" / "torrentzip.py").read_bytes() ).hexdigest()[:16] diff --git a/scripts/scraper/amberelec_launchers.py b/scripts/scraper/amberelec_launchers.py index feeb59230..d13630539 100644 --- a/scripts/scraper/amberelec_launchers.py +++ b/scripts/scraper/amberelec_launchers.py @@ -22,7 +22,7 @@ from collections.abc import Callable from typing import Any from .configgen_launchers import Launcher, Source -from .shell_launchers import ( +from scraper.shell_launchers import ( LauncherPatternMissing, Script, config_placement, diff --git a/scripts/scraper/emudeck_launchers.py b/scripts/scraper/emudeck_launchers.py index 0c3b5faff..59f9a4e16 100644 --- a/scripts/scraper/emudeck_launchers.py +++ b/scripts/scraper/emudeck_launchers.py @@ -15,7 +15,7 @@ import re from collections.abc import Callable from .configgen_launchers import Launcher -from .shell_launchers import ( +from scraper.shell_launchers import ( LauncherPatternMissing, RepoTree, Script, diff --git a/scripts/scraper/emudeck_scraper.py b/scripts/scraper/emudeck_scraper.py index f6f3d7f9b..f1acd4209 100644 --- a/scripts/scraper/emudeck_scraper.py +++ b/scripts/scraper/emudeck_scraper.py @@ -26,7 +26,7 @@ from .base_scraper import ( requirement_entry, ) from .emudeck_launchers import emulator_of_script, extract_launchers -from .shell_launchers import RepoTree +from scraper.shell_launchers import RepoTree PLATFORM_NAME = "emudeck" diff --git a/scripts/scraper/emuelec_launchers.py b/scripts/scraper/emuelec_launchers.py index b26365884..8ec89c378 100644 --- a/scripts/scraper/emuelec_launchers.py +++ b/scripts/scraper/emuelec_launchers.py @@ -19,7 +19,7 @@ from dataclasses import dataclass, field from .configgen_launchers import Launcher from .rocknix_launchers import fixed_paths -from .shell_launchers import ( +from scraper.shell_launchers import ( LauncherPatternMissing, Link, config_placement, diff --git a/scripts/scraper/emuelec_scraper.py b/scripts/scraper/emuelec_scraper.py index d678a0251..6d87d4ad9 100644 --- a/scripts/scraper/emuelec_scraper.py +++ b/scripts/scraper/emuelec_scraper.py @@ -51,7 +51,7 @@ from .es_emulators import ( json_systems, system_cores, ) -from .shell_launchers import RepoTree +from scraper.shell_launchers import RepoTree PLATFORM_NAME = "emuelec" diff --git a/scripts/scraper/game_dat_importer.py b/scripts/scraper/game_dat_importer.py index 2952d7d2c..7eb51d80c 100644 --- a/scripts/scraper/game_dat_importer.py +++ b/scripts/scraper/game_dat_importer.py @@ -41,7 +41,7 @@ if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path: from core.artifacts import copy_stream_atomic, write_if_changed, write_text_atomic from model.safeparse import parse_untrusted_xml -from region import REGIONS, WORLD +from model.region import REGIONS, WORLD from region_audit import NOINTRO from .base_scraper import github_headers diff --git a/scripts/scraper/knulli_launchers.py b/scripts/scraper/knulli_launchers.py index 983af3c49..98039c91c 100644 --- a/scripts/scraper/knulli_launchers.py +++ b/scripts/scraper/knulli_launchers.py @@ -53,7 +53,7 @@ from .configgen_launchers import ( _assigned_name, end_line, ) -from .shell_launchers import LauncherPatternMissing, Script, source_ref +from scraper.shell_launchers import LauncherPatternMissing, Script, source_ref CONFIGGEN = "package/system/knulli-configgen/configgen/configgen" GENERATORS = f"{CONFIGGEN}/generators" diff --git a/scripts/scraper/retrobat_launchers.py b/scripts/scraper/retrobat_launchers.py index 924e7b577..621a8c201 100644 --- a/scripts/scraper/retrobat_launchers.py +++ b/scripts/scraper/retrobat_launchers.py @@ -14,7 +14,7 @@ import bisect import re from collections.abc import Callable, Iterator -from .shell_launchers import is_feature_ref, split_ref +from resolve.launcherrefs import is_feature_ref, split_ref GENERATORS = "emulatorLauncher/Generators" FEATURES = ".emulationstation/es_features.cfg" diff --git a/scripts/scraper/rocknix_launchers.py b/scripts/scraper/rocknix_launchers.py index 209aeb5dc..c8e21ea78 100644 --- a/scripts/scraper/rocknix_launchers.py +++ b/scripts/scraper/rocknix_launchers.py @@ -18,8 +18,8 @@ from dataclasses import dataclass from typing import TypeVar from .configgen_launchers import Launcher -from .shell_launchers import config_placement, evidence_fields -from .shell_launchers import ( +from scraper.shell_launchers import config_placement, evidence_fields +from scraper.shell_launchers import ( LauncherPatternMissing, Link, RepoTree, diff --git a/scripts/scraper/rocknix_scraper.py b/scripts/scraper/rocknix_scraper.py index a21c15273..ce9f7d09a 100644 --- a/scripts/scraper/rocknix_scraper.py +++ b/scripts/scraper/rocknix_scraper.py @@ -25,7 +25,7 @@ from .base_scraper import ( requirement_entry, ) from .rocknix_launchers import extract_launchers -from .shell_launchers import RepoTree +from scraper.shell_launchers import RepoTree PLATFORM_NAME = "rocknix" diff --git a/scripts/scraper/shell_launchers.py b/scripts/scraper/shell_launchers.py index e882ce77a..d31193925 100644 --- a/scripts/scraper/shell_launchers.py +++ b/scripts/scraper/shell_launchers.py @@ -59,48 +59,6 @@ def source_ref(parts: Iterable[tuple[str, Iterable[int]]]) -> str: ) -# The files a platform ships as configuration: an emulator reads them, the -# platform's code never runs them. Batocera's .yml lists and an EmuELEC .opt -# only offer the values a menu option takes. -_CONFIG_FILE = re.compile( - r"\.(?:ini|cfg|conf|rc|rc_\w+|opt|bml|toml|uae|template|yml|yaml)$", re.IGNORECASE -) -_FEATURE_FILE = re.compile(r"(?:^|/)es_features[^/]*$|\.opt$", re.IGNORECASE) - - -def split_ref(ref: str) -> list[str]: - """The parts of a source_ref, each "path:lines", a bare line span - continuing the path before it.""" - parts: list[str] = [] - for part in (p.strip() for p in ref.split(", ")): - if not part: - continue - if re.fullmatch(r"\d+(?:-\d+)?", part) and parts: - parts[-1] += f", {part}" - else: - parts.append(part) - return parts - - -def ref_path(part: str) -> str: - return part.rsplit(":", 1)[0] if re.search(r":\d", part) else part - - -def config_ref(ref: str) -> list[str]: - """The parts of a source_ref that cite a config, option or feature file. - - Such a part proves what the file says, never that an emulator reads it: - melonDS.ini keys are written on ROCKNIX for a build that reads them only - when another key is set. - """ - return [part for part in split_ref(ref) if _CONFIG_FILE.search(ref_path(part))] - - -def is_feature_ref(part: str) -> bool: - """Whether a source_ref part cites a file that lists a menu option's values.""" - return bool(_FEATURE_FILE.search(ref_path(part))) - - @dataclass class Word: """A shell word: as written, and with quotes removed.""" diff --git a/scripts/torrentzip.py b/scripts/torrentzip.py index 696d2e932..932ef2e79 100644 --- a/scripts/torrentzip.py +++ b/scripts/torrentzip.py @@ -1,213 +1,17 @@ #!/usr/bin/env python3 -"""TorrentZip archive builder for MAME/FBNeo ROM sets. +"""Check or normalize a TorrentZip archive. -TorrentZip is the archive format MAME romset distributions use. It fixes -every non-content variable (member order, timestamps, compression level, -extra fields, attributes), so the archive bytes are a pure function of the -member names and their contents. - -That property makes it possible to rebuild a romset ZIP that matches an -upstream-published hash exactly, and to identify which romset revision a -published hash refers to. - -Usage: - from torrentzip import build_torrentzip, identify_romset - - data = build_torrentzip([("sp-s2.sp1", rom_bytes), ...]) - md5 = hashlib.md5(data).hexdigest() - -CLI: python scripts/torrentzip.py --check bios/Arcade/Arcade/naomi2.zip python scripts/torrentzip.py --rebuild in.zip --output out.zip """ + from __future__ import annotations import argparse -import functools import hashlib -import io -import struct -import zipfile -import zlib -from collections.abc import Callable, Iterable from pathlib import Path -from typing import Any, NamedTuple, Protocol - -class Source(Protocol): - """An open member: read in chunks, closed by its ``with`` block.""" - - def read(self, size: int = -1, /) -> bytes: ... - def __enter__(self) -> Source: ... - def __exit__(self, *exc: Any) -> Any: ... - - -class Sink(Protocol): - def write(self, data: bytes | bytearray, /) -> int: ... - -# TorrentZip constants: 1996-12-24 23:32:00, deflate level 9 -_DOS_DATE = ((1996 - 1980) << 9) | (12 << 5) | 24 -_DOS_TIME = (23 << 11) | (32 << 5) | 0 -_COMMENT_PREFIX = "TORRENTZIPPED-" -# Members are read and deflated this much at a time. Deflate output does not -# depend on how its input is cut, so a 2 GiB disk image streams through in -# the same bytes a one-shot compression gives. -CHUNK = 16 * 1024 * 1024 -# A size or offset that does not fit 32 bits takes a ZIP64 field. No -# TorrentZip-conformant archive needs one, so their layout is untouched. -ZIP32_LIMIT = 0xFFFFFFFF -_ZIP64_MARK = 0xFFFFFFFF - - -class Written(NamedTuple): - """A member as the writer read it from its source.""" - - name: str - size: int - crc32: str - sha1: str - - -def zlib_ng_version(module: object = zlib) -> str | None: - """The zlib-ng version this interpreter deflates with, None for zlib. - - TorrentZip bytes are the output of zlib's level-9 deflate. Stock zlib - 1.2.13 to 1.3.2 reproduces every TorrentZip archive in the collection. - zlib-ng 2.2.4 (python.org 3.14 on Windows) reproduces 479 of 1,561 and - 2.3.3 545, and the two disagree with each other. - """ - version = getattr(module, "ZLIBNG_VERSION", None) - if version: - return str(version) - runtime = str(getattr(module, "ZLIB_RUNTIME_VERSION", "") or "") - return runtime if "zlib-ng" in runtime.lower() else None - - -def _deflate(stream: Source) -> tuple[bytes, Written]: - compressor = zlib.compressobj(9, zlib.DEFLATED, -15) - blob = bytearray() - crc, size, sha1 = 0, 0, hashlib.sha1() - while chunk := stream.read(CHUNK): - crc = zlib.crc32(chunk, crc) - size += len(chunk) - sha1.update(chunk) - blob += compressor.compress(chunk) - blob += compressor.flush() - return bytes(blob), Written("", size, f"{crc & 0xFFFFFFFF:08x}", sha1.hexdigest()) - - -def write_torrentzip( - sink: Sink, members: Iterable[tuple[str, Callable[[], Source]]] -) -> list[Written]: - """Write a TorrentZip archive to *sink*, one member in memory at a time. - - *members* pairs each name with a callable opening its bytes. Members are - sorted case-insensitively by name, as the format requires. Returns what - was read, in archive order, so a caller can check every member. - """ - ordered = sorted(members, key=lambda m: m[0].lower()) - central = bytearray() - offset = 0 - written: list[Written] = [] - for name, opener in ordered: - raw = name.encode("ascii") - with opener() as stream: - blob, read = _deflate(stream) - crc = int(read.crc32, 16) - written.append(read._replace(name=name)) - wide = read.size >= ZIP32_LIMIT or len(blob) >= ZIP32_LIMIT - far = offset >= ZIP32_LIMIT - local_extra = struct.pack("= ZIP32_LIMIT or len(central) >= ZIP32_LIMIT or count >= 0xFFFF: - end64 = cd_offset + len(central) - sink.write(struct.pack( - " bytes: - """Build a TorrentZip archive from (name, data) members. - - Members are sorted case-insensitively by name, as the format requires. - Returns the complete archive bytes. - """ - sink = io.BytesIO() - write_torrentzip( - sink, [(name, functools.partial(io.BytesIO, data)) for name, data in members] - ) - return sink.getvalue() - - -def rebuild_torrentzip(source: str | Path) -> bytes: - """Read an archive and return its TorrentZip normalization.""" - with zipfile.ZipFile(source) as zf: - members = [ - (info.filename, zf.read(info.filename)) - for info in zf.infolist() - if not info.is_dir() - ] - return build_torrentzip(members) - - -def is_torrentzip(source: str | Path) -> bool: - """Report whether an archive already carries the TorrentZip signature.""" - with zipfile.ZipFile(source) as zf: - return zf.comment.decode("ascii", "replace").startswith(_COMMENT_PREFIX) - - -def identify_romset( - recipes: dict[str, list[tuple[str, str]]], - atoms: dict[str, bytes], - target_md5: str, -) -> str | None: - """Find which recipe rebuilds to a target archive MD5. - - recipes maps a label (e.g. a MAME version) to a list of - (member name, CRC32 hex) pairs, and atoms maps CRC32 hex to ROM bytes. - Returns the matching label, or None when no recipe reproduces the hash. - """ - target = target_md5.lower() - for label, recipe in recipes.items(): - if any(crc.lower() not in atoms for _, crc in recipe): - continue - members = [(name, atoms[crc.lower()]) for name, crc in recipe] - if hashlib.md5(build_torrentzip(members)).hexdigest() == target: - return label - return None +from core.torrentzip import is_torrentzip, rebuild_torrentzip def main() -> int: diff --git a/scripts/validate_schemas.py b/scripts/validate_schemas.py index ef2150895..f720fab00 100644 --- a/scripts/validate_schemas.py +++ b/scripts/validate_schemas.py @@ -134,7 +134,7 @@ def _config_records_without_evidence(path: Path, document: object) -> list[str]: """ if not isinstance(document, dict): return [] - from scraper.shell_launchers import config_ref, is_feature_ref + from resolve.launcherrefs import config_ref, is_feature_ref out: list[str] = [] for index, record in enumerate(document.get("launchers") or []): diff --git a/scripts/verify.py b/scripts/verify.py index 97fe6bc9b..db85cf144 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -1652,7 +1652,7 @@ def _region_pass( ) -> tuple[set[str], list[str], dict[tuple[str, str, str], str]]: """The destinations a region run withdraws, the groups no file answers, and the destination of each core extra.""" - import region as region_mod + from resolve import regions as resolve_regions # The builder owns pack composition, so it owns the grouping the region # pass reads. Grouping the platform files here and the core extras @@ -1676,14 +1676,14 @@ def _region_pass( data_registry=run.data_dir_registry, slot_overrides=pack_overrides, ) - region_index = region_mod.platform_region_index(config, run.profiles, run.target_cores) - region_drops = region_mod.resolve_region_drops( + region_index = resolve_regions.platform_region_index(config, run.profiles, run.target_cores) + region_drops = resolve_regions.resolve_region_drops( region_groups, region_index, regions, held, ) # The pack README names these: no file answers the request, so every # candidate stays. Reported here too, or verify reads all OK for a # system that has no BIOS for the region asked. - region_fallbacks = region_mod.fallback_groups( + region_fallbacks = resolve_regions.fallback_groups( region_groups, region_index, regions ) return region_drops, region_fallbacks, region_extra_dests @@ -3528,10 +3528,10 @@ def _build_parser() -> argparse.ArgumentParser: def _requested_regions(args: argparse.Namespace, parser: argparse.ArgumentParser) -> list[str]: requested_regions: list[str] = [] if getattr(args, "region", None): - import region as region_mod + from model import region try: - requested_regions = region_mod.parse_requested(args.region) + requested_regions = region.parse_requested(args.region) except ValueError as exc: parser.error(str(exc)) return requested_regions diff --git a/tests/test_archive_build.py b/tests/test_archive_build.py index 321642c3d..f5543e1b5 100644 --- a/tests/test_archive_build.py +++ b/tests/test_archive_build.py @@ -19,7 +19,7 @@ from pathlib import Path from unittest import mock import archive_build -from torrentzip import build_torrentzip +from core.torrentzip import build_torrentzip ROOT = Path(__file__).resolve().parent.parent TMP_ROOT = ROOT / "tmp" / "tests" diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 64df90823..ba5eef1d0 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -29,7 +29,7 @@ except ImportError: jsonschema = None import install from scripts import pipeline, region_audit -from scripts import region +from scripts.resolve import regions from scripts.resolve.localfile import resolve_local_file from scripts.core.ziptools import safe_extract_zip from scripts.generate_pack import ( @@ -1814,9 +1814,9 @@ class RegionRegressions(unittest.TestCase): "files": [{"name": "bios.bin", "path": "sys/bios.bin"}], }, } - index = region.build_region_index(profiles) - self.assertEqual(region.lookup_regions(index, "sys/bios.bin", "bios.bin"), set()) - drops = region.resolve_region_drops( + index = regions.build_region_index(profiles) + self.assertEqual(regions.lookup_regions(index, "sys/bios.bin", "bios.bin"), set()) + drops = regions.resolve_region_drops( {"system": [("sys/bios.bin", "bios.bin")]}, index, ["north-america"], @@ -1833,13 +1833,13 @@ class RegionRegressions(unittest.TestCase): ], } } - index = region.build_region_index(profiles) + index = regions.build_region_index(profiles) groups = {"system": [("ntsc.bin", "ntsc.bin"), ("pal.bin", "pal.bin")]} self.assertEqual( - region.resolve_region_drops(groups, index, ["north-america"]), + regions.resolve_region_drops(groups, index, ["north-america"]), {"pal.bin"}, ) - self.assertEqual(region.resolve_region_drops(groups, index, ["europe"]), set()) + self.assertEqual(regions.resolve_region_drops(groups, index, ["europe"]), set()) def test_multi_system_emulator_uses_separate_region_groups(self): profile = {"systems": ["odyssey2", "videopac"]} diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index e04d87896..eee225085 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -2030,7 +2030,8 @@ class RegionFreeRuleNamesWhereItDoesNotHold(unittest.TestCase): from model.registry import list_registered_platforms from model.profiles import load_emulator_profiles from model.platforms import load_platform_config - from region import WORLD, platform_region_index + from model.region import WORLD + from resolve.regions import platform_region_index section = _section(_page("advanced-usage.md"), "Region filtering") bullet = next(p for p in section.split("\n- ") if "Region-free" in p) diff --git a/tests/test_game_catalogs.py b/tests/test_game_catalogs.py index 638c3fa1a..bb71d8de6 100644 --- a/tests/test_game_catalogs.py +++ b/tests/test_game_catalogs.py @@ -11,7 +11,7 @@ import tempfile import unittest from pathlib import Path -from region import REGIONS +from model.region import REGIONS from scripts.scraper import game_dat_importer as importer ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_game_headers.py b/tests/test_game_headers.py index 7d62b3640..df1c70c88 100644 --- a/tests/test_game_headers.py +++ b/tests/test_game_headers.py @@ -12,7 +12,7 @@ from pathlib import Path import yaml from model.profiles import load_emulator_profiles -from region import REGIONS +from model.region import REGIONS ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_identity.py b/tests/test_identity.py index 6f09dde75..14d0e8dce 100644 --- a/tests/test_identity.py +++ b/tests/test_identity.py @@ -9,7 +9,7 @@ import tempfile import unittest from pathlib import Path -import identity +from resolve import identity class TestCrossVendorDuplicates(unittest.TestCase): diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 1477a4a48..4c8a19fb4 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -30,7 +30,8 @@ import unittest from unittest import mock from pathlib import Path -import region +from model import region +from resolve import regions as resolve_regions REPO_ROOT = Path(__file__).resolve().parent.parent @@ -48,7 +49,7 @@ class OneRegionVocabulary(unittest.TestCase): self.assertEqual(install.REGION_ALIASES, region.ALIASES) self.assertEqual(install.WORLD_REGION, region.WORLD) self.assertEqual(install.REGIONS, region.REGIONS) - self.assertEqual(install.FILE_GROUP, region.FILE_GROUP) + self.assertEqual(install.FILE_GROUP, resolve_regions.FILE_GROUP) class TheRegionRuleIsTheBuilders(unittest.TestCase): @@ -80,7 +81,7 @@ class TheRegionRuleIsTheBuilders(unittest.TestCase): "has_untagged": not regions, "emulators": [], "priorities": {priority}} # A lone core file no system names gets a group of its own. - group = f"g{g}" if rng.random() < 0.85 else f"e{region.FILE_GROUP}{dest}" + group = f"g{g}" if rng.random() < 0.85 else f"e{resolve_regions.FILE_GROUP}{dest}" groups.setdefault(group, []).append((dest, dest)) if group not in entries[dest]["region_groups"]: entries[dest]["region_groups"].append(group) @@ -101,11 +102,11 @@ class TheRegionRuleIsTheBuilders(unittest.TestCase): with self.subTest(trial=trial): self.assertEqual( install.region_drops(entries, requested), - region.resolve_region_drops(groups, index, requested), + resolve_regions.resolve_region_drops(groups, index, requested), ) self.assertEqual( install.region_drops(entries, requested, held=held), - region.resolve_region_drops(groups, index, requested, held), + resolve_regions.resolve_region_drops(groups, index, requested, held), ) def test_narrow_passes_the_installable_files_as_held(self): @@ -117,7 +118,7 @@ class TheRegionRuleIsTheBuilders(unittest.TestCase): files = [dict(e, size=1, cores=None) for e in entries if e["dest"] in held] omitted = [dict(e, cores=None) for e in entries if e["dest"] not in held] kept, still_omitted = install.narrow(files, omitted, [], [], requested) - drops = region.resolve_region_drops(groups, index, requested, held) + drops = resolve_regions.resolve_region_drops(groups, index, requested, held) with self.subTest(trial=trial): self.assertEqual( {f["dest"] for f in kept}, @@ -143,8 +144,8 @@ class TheRegionRuleIsTheBuilders(unittest.TestCase): omitted = [dict(e, cores=None, **({"held": True} if e["dest"] in pack_only else {})) for e in entries if e["dest"] not in held - pack_only] kept, still_omitted = install.narrow(files, omitted, [], [], requested) - drops = region.resolve_region_drops(groups, index, requested, held) - unheld = region.resolve_region_drops( + drops = resolve_regions.resolve_region_drops(groups, index, requested, held) + unheld = resolve_regions.resolve_region_drops( groups, index, requested, held - pack_only ) replayed += drops != unheld @@ -175,7 +176,7 @@ class TheRegionRuleIsTheBuilders(unittest.TestCase): {"dest": "GC/USA/IPL.bin", "regions": ["north-america"], "region_system_groups": ["nintendo-gamecube"]}, {"dest": "GC/EUR/IPL.bin", "regions": ["europe"], - "region_groups": [f"dolphin{region.FILE_GROUP}GC/EUR/IPL.bin"], + "region_groups": [f"dolphin{resolve_regions.FILE_GROUP}GC/EUR/IPL.bin"], "region_system_groups": ["nintendo-gamecube"]}, ] self.assertEqual( diff --git a/tests/test_launcher_evidence.py b/tests/test_launcher_evidence.py index 01f4a9bb3..0ea963bd2 100644 --- a/tests/test_launcher_evidence.py +++ b/tests/test_launcher_evidence.py @@ -25,13 +25,8 @@ from resolve.launchers import ( ) from profile_sync import _check_build_refs, shipped_build_holders from scraper.retrobat_launchers import _choices_apart -from scraper.shell_launchers import ( - LauncherPatternMissing, - Script, - config_placement, - config_ref, - is_feature_ref, -) +from scraper.shell_launchers import LauncherPatternMissing, Script, config_placement +from resolve.launcherrefs import config_ref, is_feature_ref REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_pack_grouping.py b/tests/test_pack_grouping.py index 5c53ed9a9..6e189b9eb 100644 --- a/tests/test_pack_grouping.py +++ b/tests/test_pack_grouping.py @@ -57,7 +57,7 @@ class VariantGroupSpansSystems(unittest.TestCase): if not (REPO_ROOT / "database.json").is_file(): self.skipTest("database.json not built") import generate_pack as gp - import region as region_mod + from model import region from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -71,7 +71,7 @@ class VariantGroupSpansSystems(unittest.TestCase): drops, _fallbacks, _undecided = gp._select_variants( config, config["systems"], "emulators", db, config.get("base_destination", ""), profiles, None, "full", - regions=region_mod.parse_requested("us"), one_per_slot=False, + regions=region.parse_requested("us"), one_per_slot=False, ) names = {os.path.basename(d) for d in drops} for name in ("jp_mcd1_9111.bin", "eu_mcd2_9306.bin"): diff --git a/tests/test_profile_checks.py b/tests/test_profile_checks.py index d4c7fef4c..22615d913 100644 --- a/tests/test_profile_checks.py +++ b/tests/test_profile_checks.py @@ -352,12 +352,12 @@ class ClkMasterSystemBios(unittest.TestCase): and europe only, a Brazilian pack dropped it for the Japanese one.""" def test_brazil_keeps_the_western_bios(self): - import region + from resolve import regions - index = region.build_region_index({"clk": _profile("clk")}) + index = regions.build_region_index({"clk": _profile("clk")}) group = {"sms": [("MasterSystem/bios.sms", "bios.sms"), ("MasterSystem/japanese-bios.sms", "japanese-bios.sms")]} - drops = region.resolve_region_drops(group, index, ["brazil"]) + drops = regions.resolve_region_drops(group, index, ["brazil"]) self.assertEqual(drops, {"MasterSystem/japanese-bios.sms"}) diff --git a/tests/test_region.py b/tests/test_region.py index eef654e99..2a6deadcf 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -13,7 +13,8 @@ from pathlib import Path from model import profiles as model_profiles from model.profiles import _emulator_profiles_cache -import region +from model import region +from resolve import regions as resolve_regions from packextras import emulator_region_drops @@ -193,27 +194,27 @@ class TestRegionIndex(unittest.TestCase): "files": [{"name": "ignored.bin", "region": ["japan"]}], }, } - self.index = region.build_region_index(self.profiles) + self.index = resolve_regions.build_region_index(self.profiles) def test_path_keyed_entries_stay_separate(self): self.assertEqual( - region.lookup_regions(self.index, "GC/USA/IPL.bin", "IPL.bin"), + resolve_regions.lookup_regions(self.index, "GC/USA/IPL.bin", "IPL.bin"), {"north-america"}, ) self.assertEqual( - region.lookup_regions(self.index, "GC/JAP/IPL.bin", "IPL.bin"), + resolve_regions.lookup_regions(self.index, "GC/JAP/IPL.bin", "IPL.bin"), {"japan"}, ) def test_bare_name_lookup_unions_ambiguous_entries(self): self.assertEqual( - region.lookup_regions(self.index, "", "IPL.bin"), + resolve_regions.lookup_regions(self.index, "", "IPL.bin"), {"north-america", "europe", "japan"}, ) def test_destination_suffix_bridges_platform_entry(self): self.assertEqual( - region.lookup_regions( + resolve_regions.lookup_regions( self.index, "dolphin-emu/GC/EUR/IPL.bin", "IPL.bin" ), {"europe"}, @@ -221,21 +222,21 @@ class TestRegionIndex(unittest.TestCase): def test_untagged_file_has_no_regions(self): self.assertEqual( - region.lookup_regions(self.index, "dsp_rom.bin", "dsp_rom.bin"), set() + resolve_regions.lookup_regions(self.index, "dsp_rom.bin", "dsp_rom.bin"), set() ) def test_unknown_file_has_no_regions(self): self.assertEqual( - region.lookup_regions(self.index, "nope.bin", "nope.bin"), set() + resolve_regions.lookup_regions(self.index, "nope.bin", "nope.bin"), set() ) def test_legacy_string_values_are_normalised(self): self.assertEqual( - region.lookup_regions(self.index, "scph5501.bin", "scph5501.bin"), + resolve_regions.lookup_regions(self.index, "scph5501.bin", "scph5501.bin"), {"north-america"}, ) self.assertEqual( - region.lookup_regions(self.index, "psxonpsp660.bin", "psxonpsp660.bin"), + resolve_regions.lookup_regions(self.index, "psxonpsp660.bin", "psxonpsp660.bin"), {region.WORLD}, ) @@ -246,12 +247,12 @@ class TestRegionIndex(unittest.TestCase): def test_launcher_profiles_are_skipped(self): self.assertEqual( - region.lookup_regions(self.index, "ignored.bin", "ignored.bin"), set() + resolve_regions.lookup_regions(self.index, "ignored.bin", "ignored.bin"), set() ) def test_unknown_value_names_the_profile_and_file(self): with self.assertRaises(ValueError) as ctx: - region.build_region_index( + resolve_regions.build_region_index( {"badcore": {"files": [{"name": "x.bin", "region": ["atlantis"]}]}} ) self.assertIn("badcore", str(ctx.exception)) @@ -272,26 +273,26 @@ class TestStandaloneLayoutIsIndexed(unittest.TestCase): {"name": "IPL.bin", "path": "dolphin-emu/Sys/GC/EUR/IPL.bin", "standalone_path": "GC/EUR/IPL.bin", "region": ["europe"]}, ]}} - index = region.build_region_index(profiles) - self.assertEqual(region.lookup_regions(index, "GC/EUR/IPL.bin", "IPL.bin"), {"europe"}) + index = resolve_regions.build_region_index(profiles) + self.assertEqual(resolve_regions.lookup_regions(index, "GC/EUR/IPL.bin", "IPL.bin"), {"europe"}) self.assertIn("GC/EUR/IPL.bin", slot.build_slot_index(profiles)) def test_an_alias_carries_the_region_of_its_file(self): """scph5552.bin, the name beetle_psx also opens for its European BIOS, stayed in a --region jp pack once scph5502.bin went.""" - index = region.build_region_index({"beetle_psx": {"files": [ + index = resolve_regions.build_region_index({"beetle_psx": {"files": [ {"name": "scph5502.bin", "aliases": ["scph5552.bin"], "region": ["europe", "oceania"]}, ]}}) self.assertEqual( - region.lookup_regions(index, "scph5552.bin", "scph5552.bin"), + resolve_regions.lookup_regions(index, "scph5552.bin", "scph5552.bin"), {"europe", "oceania"}, ) class TestResolveRegionDrops(unittest.TestCase): def setUp(self): - self.index = region.build_region_index( + self.index = resolve_regions.build_region_index( { "psx": { "files": [ @@ -308,7 +309,7 @@ class TestResolveRegionDrops(unittest.TestCase): ) def _drops(self, groups, requested): - return region.resolve_region_drops(groups, self.index, requested) + return resolve_regions.resolve_region_drops(groups, self.index, requested) def test_a_lone_file_never_vetoes_its_system(self): """Dolphin's GC/EUR/IPL.bin came back as a core extra alone in its @@ -329,7 +330,7 @@ class TestResolveRegionDrops(unittest.TestCase): groups = {"psx": [("scph5501.bin", "scph5501.bin"), ("scph5500.bin", "scph5500.bin")]} held = {"scph5501.bin"} - drop = region.resolve_region_drops + drop = resolve_regions.resolve_region_drops self.assertEqual(drop(groups, self.index, ["japan"], held), set()) self.assertEqual( drop(groups, self.index, ["japan", "north-america"], held), set() @@ -343,7 +344,7 @@ class TestResolveRegionDrops(unittest.TestCase): groups = {"psx": [("scph5500.bin", "scph5500.bin"), ("psxonpsp660.bin", "psxonpsp660.bin")]} self.assertEqual( - region.resolve_region_drops( + resolve_regions.resolve_region_drops( groups, self.index, ["europe"], {"scph5500.bin"} ), set(), @@ -352,7 +353,7 @@ class TestResolveRegionDrops(unittest.TestCase): def test_a_world_file_the_code_ranks_lower_keeps_the_regional_ones(self): """DuckStation looks for its PS1 images (5) before the world PS2 ones (100): asked for Brazil, it kept only the PS2 fallbacks.""" - index = region.build_region_index({"duckstation": {"files": [ + index = resolve_regions.build_region_index({"duckstation": {"files": [ {"name": "scph5501.bin", "region": ["north-america"], "priority": 5}, {"name": "ps2_scph30001.bin", "region": ["north-america"], "priority": 150}, {"name": "ps2_scph10000.bin", "region": ["world"], "priority": 100}, @@ -360,7 +361,7 @@ class TestResolveRegionDrops(unittest.TestCase): groups = {"psx": [(n, n) for n in ("scph5501.bin", "ps2_scph30001.bin", "ps2_scph10000.bin")]} self.assertEqual( - region.resolve_region_drops(groups, index, ["brazil"]), {"ps2_scph30001.bin"} + resolve_regions.resolve_region_drops(groups, index, ["brazil"]), {"ps2_scph30001.bin"} ) def test_without_ranks_the_world_file_still_wins(self): @@ -438,7 +439,7 @@ class TestResolveRegionDrops(unittest.TestCase): class TestFallbackGroups(unittest.TestCase): def setUp(self): - self.index = region.build_region_index( + self.index = resolve_regions.build_region_index( { "psx": { "files": [ @@ -455,14 +456,14 @@ class TestFallbackGroups(unittest.TestCase): "fds": [("disksys.rom", "disksys.rom")], } self.assertEqual( - region.fallback_groups(groups, self.index, ["north-america"]), ["fds"] + resolve_regions.fallback_groups(groups, self.index, ["north-america"]), ["fds"] ) def test_an_untagged_bios_answers_every_region(self): """VICE's generic kernal is untagged beside its Japanese one: the C64 was reported as having no BIOS for North America.""" groups = {"fds": [("disksys.rom", "disksys.rom"), ("generic.rom", "generic.rom")]} - self.assertEqual(region.fallback_groups(groups, self.index, ["north-america"]), []) + self.assertEqual(resolve_regions.fallback_groups(groups, self.index, ["north-america"]), []) def test_a_file_no_system_claims_is_no_fallback(self): """Dolphin's GC/EUR/IPL.bin, alone in its group, named the GameCube @@ -470,7 +471,7 @@ class TestFallbackGroups(unittest.TestCase): groups = {"Dolphin:file:GC/EUR/IPL.bin": [("GC/EUR/IPL.bin", "IPL.bin")], "fds": [("disksys.rom", "disksys.rom")]} self.assertEqual( - region.fallback_groups(groups, self.index, ["north-america"]), ["fds"] + resolve_regions.fallback_groups(groups, self.index, ["north-america"]), ["fds"] ) def test_the_readme_names_a_slot_as_a_reader_does(self): @@ -481,7 +482,7 @@ class TestFallbackGroups(unittest.TestCase): def test_no_requested_regions_reports_nothing(self): groups = {"fds": [("disksys.rom", "disksys.rom")]} - self.assertEqual(region.fallback_groups(groups, self.index, []), []) + self.assertEqual(resolve_regions.fallback_groups(groups, self.index, []), []) class OneCodeOneRegionAnswer(unittest.TestCase): @@ -581,7 +582,7 @@ class TestProfileConformance(unittest.TestCase): for path in self.repo_profiles: with open(path, encoding="utf-8") as fh: profiles[os.path.basename(path)[:-4]] = self.yaml.safe_load(fh) or {} - index = region.build_region_index(profiles) + index = resolve_regions.build_region_index(profiles) self.assertGreater(len(index), 0) @@ -708,8 +709,8 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase): config, config["systems"], str(root / "emulators"), db, "", profiles, ) - drops = region.resolve_region_drops( - groups, region.build_region_index(profiles), ["north-america"] + drops = resolve_regions.resolve_region_drops( + groups, resolve_regions.build_region_index(profiles), ["north-america"] ) self.assertEqual( {d for d in drops}, {"jp.bin"}, @@ -1038,7 +1039,7 @@ class UnknownRegionSaysWhatToType(unittest.TestCase): """`unknown region: 'uss'` named nothing to type instead.""" def test_the_build_scripts_suggest_and_list_short_forms(self): - import region + from model import region with self.assertRaises(ValueError) as caught: region.parse_requested("uss") @@ -1088,7 +1089,8 @@ class GenesisPlusGxUsBiosServesEurope(unittest.TestCase): from pathlib import Path from model.profiles import load_emulator_profiles - from region import build_region_index, parse_requested, resolve_region_drops + from resolve.regions import build_region_index, resolve_region_drops + from model.region import parse_requested root = Path(__file__).resolve().parents[1] profiles = load_emulator_profiles(str(root / "emulators")) @@ -1109,7 +1111,8 @@ def _real_drops(profile: str, members: list[str], requested: str) -> set[str]: from pathlib import Path from model.profiles import load_emulator_profiles - from region import build_region_index, parse_requested, resolve_region_drops + from resolve.regions import build_region_index, resolve_region_drops + from model.region import parse_requested root = Path(__file__).resolve().parents[1] profiles = load_emulator_profiles(str(root / "emulators")) @@ -1427,14 +1430,14 @@ class UsaRegionServesTheAmericas(unittest.TestCase): import yaml profile = yaml.safe_load(self.PROFILE.read_text(encoding="utf-8")) - index = region.build_region_index({"citra-mmj": profile}) + index = resolve_regions.build_region_index({"citra-mmj": profile}) requested = region.parse_requested("br,cn") for destination, name in ( (self.FONT, "00000000.app.romfs"), ("sysdata/cbf_std.bcfnt", "cbf_std.bcfnt"), ): with self.subTest(file=destination): - regions = region.lookup_regions(index, destination, name) + regions = resolve_regions.lookup_regions(index, destination, name) self.assertEqual(region.rank(regions, requested), 0) def test_brazil_ranks_the_usa_dsi_nand_before_the_japanese_one(self): @@ -1444,10 +1447,10 @@ class UsaRegionServesTheAmericas(unittest.TestCase): bizhawk = self.PROFILE.with_name("bizhawk.yml") profile = yaml.safe_load(bizhawk.read_text(encoding="utf-8")) - index = region.build_region_index({"bizhawk": profile}) + index = resolve_regions.build_region_index({"bizhawk": profile}) requested = region.parse_requested("br,jp") - usa = region.lookup_regions(index, "", "DSi_Nand_USA.bin") - jpn = region.lookup_regions(index, "", "DSi_Nand_JPN.bin") + usa = resolve_regions.lookup_regions(index, "", "DSi_Nand_USA.bin") + jpn = resolve_regions.lookup_regions(index, "", "DSi_Nand_JPN.bin") self.assertEqual(region.rank(usa, requested), 0) self.assertEqual(region.rank(jpn, requested), 1) diff --git a/tests/test_region_agnostic_scan.py b/tests/test_region_agnostic_scan.py index 3d3ffe272..2efa728da 100644 --- a/tests/test_region_agnostic_scan.py +++ b/tests/test_region_agnostic_scan.py @@ -25,7 +25,7 @@ class ScanCopiesStay(unittest.TestCase): previous = os.getcwd() os.chdir(REPO_ROOT) self.addCleanup(os.chdir, previous) - import region as region_mod + from resolve import regions as resolve_regions from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -45,10 +45,10 @@ class ScanCopiesStay(unittest.TestCase): } if not scanned: self.skipTest("no agnostic scan copy in the RetroArch pack") - index = region_mod.platform_region_index(config, profiles) + index = resolve_regions.platform_region_index(config, profiles) for regions in (["europe"], ["japan"], ["north-america"]): with self.subTest(regions=regions): - drops = region_mod.resolve_region_drops(groups, index, regions) + drops = resolve_regions.resolve_region_drops(groups, index, regions) self.assertEqual(sorted(drops & scanned), []) diff --git a/tests/test_region_groups.py b/tests/test_region_groups.py index 56b7e7efe..dcaa40774 100644 --- a/tests/test_region_groups.py +++ b/tests/test_region_groups.py @@ -46,7 +46,7 @@ class TheEnterpriseKeepsItsRom(unittest.TestCase): def test_retrodeck_keeps_brd_rom_under_a_region(self): if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not built") - import region + from resolve import regions from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -59,8 +59,8 @@ class TheEnterpriseKeepsItsRom(unittest.TestCase): config, config["systems"], str(REPO_ROOT / "emulators"), db, config.get("base_destination", ""), profiles, ) - drops = region.resolve_region_drops( - groups, region.build_region_index(profiles), ["north-america"] + drops = regions.resolve_region_drops( + groups, regions.build_region_index(profiles), ["north-america"] ) self.assertNotIn("bios/brd.rom", drops) diff --git a/tests/test_region_platform_index.py b/tests/test_region_platform_index.py index 51b7cb5b8..2240746f0 100644 --- a/tests/test_region_platform_index.py +++ b/tests/test_region_platform_index.py @@ -13,7 +13,7 @@ import tests import unittest from pathlib import Path -import region as region_mod +from resolve import regions REPO_ROOT = Path(__file__).resolve().parents[1] @@ -28,9 +28,9 @@ PROFILES = { class OnlyThePlatformsCores(unittest.TestCase): def test_a_foreign_untagged_entry_does_not_void_the_tag(self): config = {"cores": ["gpgx"], "systems": {"sega-mega-cd": {"files": []}}} - index = region_mod.platform_region_index(config, PROFILES) + index = regions.platform_region_index(config, PROFILES) self.assertFalse(index["bios_CD_E.bin"]["has_untagged"]) - self.assertTrue(region_mod.build_region_index(PROFILES)["bios_CD_E.bin"]["has_untagged"]) + self.assertTrue(regions.build_region_index(PROFILES)["bios_CD_E.bin"]["has_untagged"]) def test_every_platform_site_reads_it(self): for module in ("verify.py", "generate_pack.py", "packverify.py"): diff --git a/tests/test_retired_files.py b/tests/test_retired_files.py index 98744ef11..adfe2e06d 100644 --- a/tests/test_retired_files.py +++ b/tests/test_retired_files.py @@ -15,7 +15,7 @@ import tempfile import unittest from pathlib import Path -import retired_files +from model import retired as model_retired REPO_ROOT = Path(__file__).resolve().parents[1] @@ -40,30 +40,30 @@ class WhatLeftIsRecorded(unittest.TestCase): }) def test_the_departure_and_the_file_in_its_place(self): - left = retired_files.retired_between(self.old, self.new, "2026-10-22") + left = model_retired.retired_between(self.old, self.new, "2026-10-22") self.assertEqual(list(left), [OLD]) self.assertEqual(left[OLD]["left"], "2026-10-22") self.assertEqual(left[OLD]["successor"], NEW) self.assertEqual(left[OLD]["md5"], "43" * 16) def test_the_first_departure_stays_and_a_return_leaves_the_record(self): - first = retired_files.merge({}, retired_files.retired_between(self.old, self.new, "2026-10-22"), + first = model_retired.merge({}, model_retired.retired_between(self.old, self.new, "2026-10-22"), self.new) - again = retired_files.merge(first, {OLD: {"left": "2026-11-01"}}, self.new) + again = model_retired.merge(first, {OLD: {"left": "2026-11-01"}}, self.new) self.assertEqual(again[OLD]["left"], "2026-10-22") - self.assertEqual(retired_files.merge(again, {}, self.old), {}) + self.assertEqual(model_retired.merge(again, {}, self.old), {}) def test_generate_db_writes_it_beside_the_database(self): with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: database = Path(tmp) / "database.json" - path = retired_files.retired_path(database) + path = model_retired.retired_path(database) self.assertEqual(path, Path(tmp) / "retired.json") - self.assertEqual(retired_files.update(path, self.old, self.new, "2026-10-22"), 1) - self.assertEqual(retired_files.update(path, self.old, self.new, "2026-10-23"), 0) + self.assertEqual(model_retired.update(path, self.old, self.new, "2026-10-22"), 1) + self.assertEqual(model_retired.update(path, self.old, self.new, "2026-10-23"), 0) record = json.loads(path.read_text())["files"] self.assertEqual(record[OLD]["left"], "2026-10-22") source = (REPO_ROOT / "scripts" / "generate_db.py").read_text(encoding="utf-8") - self.assertIn("retired_files.update(", source) + self.assertIn("retired.update(", source) class TheLookupAnswersForIt(unittest.TestCase): @@ -86,7 +86,7 @@ class TheLookupAnswersForIt(unittest.TestCase): self.assertEqual(found[(OLD, "sha1")]["left"], "2026-10-22") def test_the_committed_record_holds_the_reported_file(self): - record = retired_files.load(REPO_ROOT / "retired.json") + record = model_retired.load(REPO_ROOT / "retired.json") if not record: self.skipTest("retired.json is not written") self.assertIn("bd02f6a0ce8accba7ea5415fd22c2e8f23ec4b10", record) diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index d1bd3e5b3..08cd75fd3 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -34,7 +34,7 @@ from scripts.scraper.romset_dat_importer import ( recipe_entries, ) from scripts.scraper.logiqx_parser import parse_logiqx -from torrentzip import build_torrentzip, is_torrentzip +from core.torrentzip import build_torrentzip, is_torrentzip ROOT = Path(__file__).resolve().parent.parent TMP_ROOT = ROOT / "tmp" / "tests" @@ -715,7 +715,7 @@ class IdentificationReadsTheDirectoryFirst(unittest.TestCase): whose members could never match.""" def test_a_recipe_with_other_members_is_never_built(self): - from torrentzip import build_torrentzip + from core.torrentzip import build_torrentzip import romset_recipes diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py index 4b3ad1f09..f66f648c2 100644 --- a/tests/test_site_exports.py +++ b/tests/test_site_exports.py @@ -863,7 +863,7 @@ class AWantedDumpIsFoundByItsHash(unittest.TestCase): self.assertIn('"wanted"', _json.dumps(schema)) self.assertIn("byLayer('wanted')", (root / "website" / "src" / "scripts" / "site.ts").read_text()) source = Path(generate_site.__file__).read_text(encoding="utf-8") - self.assertIn('retired_files.load(_REPO_ROOT / "retired.json"), wanted)', source) + self.assertIn('model_retired.load(_REPO_ROOT / "retired.json"), wanted)', source) class AMovedPartCardReachesItsPage(unittest.TestCase): diff --git a/tests/test_torrentzip.py b/tests/test_torrentzip.py index 88dc41b57..61b13372e 100644 --- a/tests/test_torrentzip.py +++ b/tests/test_torrentzip.py @@ -10,12 +10,7 @@ import tempfile import unittest import zipfile -from torrentzip import ( - build_torrentzip, - identify_romset, - is_torrentzip, - rebuild_torrentzip, -) +from core.torrentzip import build_torrentzip, identify_romset, is_torrentzip, rebuild_torrentzip REPO_ROOT = os.path.join(os.path.dirname(__file__), "..") @@ -166,7 +161,7 @@ class StreamingWriter(unittest.TestCase): def test_chunked_input_gives_the_one_shot_bytes(self): """Deflate output does not depend on how its input is cut.""" import io - import torrentzip + from core import torrentzip members = self._members() whole = torrentzip.build_torrentzip(members) @@ -190,7 +185,7 @@ class StreamingWriter(unittest.TestCase): def test_a_member_past_32_bits_takes_a_zip64_field(self): """cspect-next-8gb.zip holds an 8 GiB image: its size needs ZIP64.""" - import torrentzip + from core import torrentzip members = self._members() saved = torrentzip.ZIP32_LIMIT @@ -210,7 +205,7 @@ class StreamingWriter(unittest.TestCase): """python.org 3.14 on Windows links zlib-ng, which gives other bytes.""" from types import SimpleNamespace - from torrentzip import zlib_ng_version + from core.torrentzip import zlib_ng_version stock = SimpleNamespace(ZLIB_RUNTIME_VERSION="1.3.1") windows = SimpleNamespace(ZLIB_RUNTIME_VERSION="1.3.1.zlib-ng") diff --git a/tests/test_verify_pack_choice.py b/tests/test_verify_pack_choice.py index b87bee433..8db4b7970 100644 --- a/tests/test_verify_pack_choice.py +++ b/tests/test_verify_pack_choice.py @@ -77,9 +77,9 @@ class VerifyPackChoice(unittest.TestCase): (self.out / name).write_bytes(b"") def test_region_opens_the_regional_pack(self): - import region as region_mod + from model import region - regions = region_mod.parse_requested("us") + regions = region.parse_requested("us") tag = self.gp._narrowings("full", regions, None, False, False)[0][0] self._touch(f"{self.stem}_BIOS_Pack.zip") self._touch(f"{self.stem}{tag}_BIOS_Pack.zip") diff --git a/wiki/profiling.md b/wiki/profiling.md index 9bef1f731..60b2c10eb 100644 --- a/wiki/profiling.md +++ b/wiki/profiling.md @@ -209,7 +209,7 @@ What does not, and why each trap is easy to fall into: Saturn SMPC area codes behind `asia-ntsc` and `asia-pal`. Mednafen names them for Taiwan and China, so a `--region taiwan` request reaches an `asia-ntsc` file and a `--region china` request an `asia-pal` one, and the - other way round (`AREA_TERRITORIES` in `scripts/region.py`). + other way round (`AREA_TERRITORIES` in `scripts/model/region.py`). - **A single-region system.** When every file of a system shares one region, the pack filter keeps them all anyway, so annotating adds nothing. - **A language without a territory.** Arabic MSX variants, CJK fonts. The