diff --git a/scripts/scraper/arcade_parent_importer.py b/scripts/scraper/arcade_parent_importer.py index cbdd7276d..3b6f559fc 100644 --- a/scripts/scraper/arcade_parent_importer.py +++ b/scripts/scraper/arcade_parent_importer.py @@ -53,7 +53,7 @@ from typing import IO from model.database import load_database from core.artifacts import write_if_changed from model.profiles import load_emulator_profiles -from core.cli import run_cli +from core.cli import add_repo_inputs, run_cli from core.hashing import compute_hashes from core.upstream import parse_repo from .base_scraper import download @@ -1113,10 +1113,8 @@ def declared_archives(profile: dict) -> set[str]: return names -def collection_names(database: Path) -> set[str]: - if not database.is_file(): - return set() - db = load_database(str(database)) +def collection_names(database: str) -> set[str]: + db = load_database(database) return {n.lower() for n in db.get("indexes", {}).get("by_name", {})} @@ -1134,10 +1132,7 @@ def main() -> int: which.add_argument("--profile", action="append", choices=sorted(PROFILES), help="profile to import (repeatable)") which.add_argument("--all", action="store_true", help="every profile with an arcade source") - parser.add_argument("--emulators-dir", default="emulators", - help="profiles whose BIOS sets are read (default emulators)") - parser.add_argument("--db", default="database.json", - help="collection index, to name BIOS sets the collection lacks") + add_repo_inputs(parser, "emulators", "db") parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT, help=f"where the parent maps are written (default {DEFAULT_OUTPUT})") parser.add_argument("--cache-dir", type=Path, default=DEFAULT_CACHE, @@ -1147,7 +1142,7 @@ def main() -> int: args = parser.parse_args() profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False) - names = collection_names(Path(args.db)) + names = collection_names(args.db) failed = False for profile in sorted(PROFILES) if args.all else args.profile: if profile not in profiles: @@ -1167,7 +1162,7 @@ def main() -> int: roots = bios_roots(doc) declared = declared_archives(profiles[profile]) undeclared = [r for r in roots if f"{r}.zip" not in declared] - absent = [r for r in roots if names and f"{r}.zip" not in names] + absent = [r for r in roots if f"{r}.zip" not in names] print( f"{profile}: {counts['games']} games, {counts['games_with_bios']} with a BIOS set, " f"{counts['bios_roots_used']} BIOS sets used, " diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index 4e089e349..dc1951ff3 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -32,7 +32,6 @@ from __future__ import annotations import argparse import hashlib import json -import re import sys import urllib.parse import zipfile @@ -46,7 +45,9 @@ from model.registry import list_registered_platforms from model.profiles import load_emulator_profiles from model.platforms import load_platform_config from core.cli import add_repo_inputs, run_cli +from model.database import load_database from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot +from resolve.localfile import variant_base_name from .base_scraper import download, fetch_github_latest_version, github_json from .listxml import Opener, iter_elements, open_listxml, rom_members, xml_members from .logiqx_parser import LogiqxDat, parse_logiqx @@ -84,9 +85,6 @@ Targets = dict[tuple[str, int], set[str]] MemberList = tuple[tuple[str, str], ...] ByMembers = dict[MemberList, set[str]] -_VARIANT_TAG = re.compile(r"\.[0-9a-f]{8}$") - - def member_list(members: list[dict]) -> MemberList: """Sorted (name, crc32) of a recipe, the key an archive is matched on.""" return tuple( @@ -94,7 +92,7 @@ def member_list(members: list[dict]) -> MemberList: ) -def collection_archives(db_path: str) -> tuple[set[str], ByMembers]: +def collection_archives(db: dict) -> tuple[set[str], ByMembers]: """Names and member lists of every archive the collection holds. A set the collection keeps under another name is still that set: @@ -102,13 +100,11 @@ def collection_archives(db_path: str) -> tuple[set[str], ByMembers]: ``votrsc01a``. Matched by name alone, neither ever entered the snapshot. A ``.variants/`` copy stands for the name its tag is cut from. """ - with open(db_path, encoding="utf-8") as handle: - files = json.load(handle).get("files", {}) names: set[str] = set() by_members: ByMembers = {} - for entry in files.values(): + for entry in db.get("files", {}).values(): path = Path(entry.get("path", "")) - name = _VARIANT_TAG.sub("", path.name) + name = variant_base_name(path.name) if not name.lower().endswith(".zip") or not path.is_file(): continue try: @@ -160,15 +156,14 @@ def named_entries( ] -def catalog_targets(provenance_dir: str, db_path: str) -> Targets: +def catalog_targets(provenance_dir: str, db: dict) -> Targets: """(crc32, size) -> sha1 of each dump-catalog entry the collection lacks. fm7740sx carries DICROM.rom, EXTSUB.rom and KANJI2.rom, which No-Intro lists and the collection misses: filtered on archive names alone, the snapshot never held the set and the missing report named no source. """ - with open(db_path, encoding="utf-8") as handle: - held = set(json.load(handle).get("files", {})) + held = set(db.get("files", {})) targets: Targets = {} for snapshot in load_provenance_snapshots(provenance_dir).values(): for entry in snapshot.get("entries", []): @@ -540,7 +535,7 @@ def _parser() -> argparse.ArgumentParser: "--output", default="", help="snapshot to write (default: recipes/.json)", ) - add_repo_inputs(parser, "emulators", "platforms") + add_repo_inputs(parser, "emulators", "platforms", "db") parser.add_argument( "--all", action="store_true", help="keep every set, not only referenced ones" ) @@ -549,10 +544,6 @@ def _parser() -> argparse.ArgumentParser: help="dump catalogs whose missing entries keep the sets holding them " "(default: %(default)s)", ) - parser.add_argument( - "--db", default="database.json", - help="collection database the catalogs are compared with (default: %(default)s)", - ) parser.add_argument( "--dry-run", action="store_true", help="print what would change and write nothing", @@ -572,9 +563,10 @@ class _Selection: def _selection(args: argparse.Namespace) -> _Selection: if args.all: return _Selection() - held, by_members = collection_archives(args.db) + db = load_database(args.db) + held, by_members = collection_archives(db) keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held - targets = catalog_targets(args.provenance_dir, args.db) + targets = catalog_targets(args.provenance_dir, db) return _Selection(keep, targets, by_members) diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index 9e40ced08..a2ade0e5c 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -512,13 +512,27 @@ class ListXmlRecipes(unittest.TestCase): db.write_text(json.dumps({"files": { str(i): {"path": str(path)} for i, path in enumerate((plain, variant, loose)) }}), encoding="utf-8") - names, by_members = collection_archives(str(db)) + names, by_members = collection_archives(json.loads(db.read_text(encoding="utf-8"))) self.assertEqual(names, {"set.zip", "other.zip"}) self.assertEqual( by_members, {member_list([{"name": "a.rom", "crc32": _crc(ROM_A)}]): {"set.zip", "other.zip"}}, ) + def test_a_missing_database_stops_both_importers(self): + """A mistyped --db ended on a traceback in one importer and passed + the other's absent-set check without reading anything.""" + from argparse import Namespace + + from model.database import DatabaseUnreadable + from scripts.scraper import arcade_parent_importer, romset_dat_importer + + args = Namespace(all=False, db=str(TMP_ROOT / "nosuch.json")) + with self.assertRaises(DatabaseUnreadable): + romset_dat_importer._selection(args) + with self.assertRaises(DatabaseUnreadable): + arcade_parent_importer.collection_names(args.db) + def test_a_set_holding_a_missing_catalog_dump_is_kept(self): """fm7740sx carries three No-Intro dumps the collection lacks. No profile names it, so the missing report named no place to find them.""" @@ -541,8 +555,7 @@ class ListXmlRecipes(unittest.TestCase): {"name": "held.rom", "crc32": "1", "size": 4, "sha1": "a" * 40}, {"name": "lacked.rom", "crc32": "2", "size": 4, "sha1": "b" * 40}, ]})) - (root / "db.json").write_text(json.dumps({"files": {"a" * 40: {}}})) - targets = catalog_targets(str(root / "prov"), str(root / "db.json")) + targets = catalog_targets(str(root / "prov"), {"files": {"a" * 40: {}}}) self.assertEqual(targets, {("00000002", 4): {"b" * 40}}) def test_upstream_blobs_are_recorded_and_replaced(self):