diff --git a/scripts/collection/__init__.py b/scripts/collection/__init__.py index f600e850d..bf9136c5d 100644 --- a/scripts/collection/__init__.py +++ b/scripts/collection/__init__.py @@ -1 +1 @@ -"""The BIOS collection on disk: its database, duplicates and integrity.""" +"""The collection held in bios/: its scan, its database and the checks of its files.""" diff --git a/scripts/collection/aliases.py b/scripts/collection/aliases.py new file mode 100644 index 000000000..e2f9e5a68 --- /dev/null +++ b/scripts/collection/aliases.py @@ -0,0 +1,324 @@ +"""The alternate names platform YAMLs, emulator profiles and known groups give a held content.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path + +from collection.declared import hash_values +from core.cli import SourceUnreadable +from model.profiles import source_yaml_paths +from model.registry import list_registered_platforms +from model.sources import source_yaml_file +from resolve.localfile import variant_base_name + + +def _primary_names(entries: list) -> set[str]: + return {str(fe.get("name", "")).lower() for fe in entries if isinstance(fe, dict)} + + +def _own_aliases(file_entry: dict, primary_names: set[str]) -> list[str]: + """Aliases that name no other entry of the same profile.""" + name = str(file_entry.get("name", "")).lower() + return [ + alias for alias in file_entry.get("aliases") or [] + if str(alias).lower() == name or str(alias).lower() not in primary_names + ] + + +class UnreadableSource(Exception): + """Platform or profile files that do not parse, named one per line.""" + + def __init__(self, sources: list[str]) -> None: + super().__init__("\n".join(sources)) + self.sources = sources + + +@dataclass +class _AliasBook: + """The alternate names collected so far, and what designates a content.""" + + files: dict + md5_to_sha1: dict[str, str] + name_to_sha1: dict[str, str] + # The contents held under each name, every copy counted. + holders: dict[str, set[str]] + # The files a name designates once case is folded. + families: dict[str, set[str]] + # A name only .variants/ copies carry is not a primary's. + named_primaries: set[str] + aliases: dict[str, list[dict]] = field(default_factory=dict) + + def add(self, name: str, matched_sha1: str) -> None: + if not name or name in self.named_primaries: + return + if matched_sha1 not in self.aliases: + self.aliases[matched_sha1] = [] + existing = {a["name"] for a in self.aliases[matched_sha1]} + if name not in existing: + self.aliases[matched_sha1].append({"name": name, "path": ""}) + + +def _alias_book(files: dict, copies: dict | None) -> _AliasBook: + """Index the scanned files by md5, name and folded name.""" + md5_to_sha1 = {} + name_to_sha1 = {} + for sha1, entry in files.items(): + md5_to_sha1[entry["md5"]] = sha1 + name_to_sha1[entry["name"]] = sha1 + # The contents held under each name, every copy counted and not only the + # primary: which copy of identical bytes is primary follows path order. + # Keyed on primaries alone, project64's 64DD_IPL_v12_JPN.bin stopped + # naming its content once 64DD_IPL.bin sorted first, and its aliases + # 64dd_ipl_J.bin and 64DD_IPL_JP.n64 went with it. + holders: dict[str, set[str]] = {} + # The files a name designates once case is folded, as the resolver's + # name step folds it, a primary and its own .variants/ counted as one + # file. dosbox's SC-55 ROM2.BIN found Galaksija's ROM2.BIN the only + # exact holder, and its alias ROM2_ST.BIN went to a 4 KiB BASIC ROM, + # while SC-55's rom2.bin sat under the same folded name. + families: dict[str, set[str]] = {} + + def _hold(name: str, path: str, sha1: str) -> None: + holders.setdefault(name, set()).add(sha1) + directory = path.rpartition("/")[0].removesuffix("/.variants") + families.setdefault(name.casefold(), set()).add( + f"{directory}/{variant_base_name(name)}".casefold() + ) + + for sha1, entry in files.items(): + _hold(entry["name"], entry["path"], sha1) + for sha1, copy_list in (copies or {}).items(): + if sha1 in files: + for copy in copy_list: + _hold(copy["name"], copy["path"], sha1) + + # A name only .variants/ copies carry is not a primary's: those copies are + # the other revisions of whatever the name designates. Retroarch pins + # bios_E.sms to v1.3, and with the name refused, Genesis Plus GX got the + # first variant in index order, a 256 KB BIOS, by the name step. + named_primaries = { + entry["name"] for entry in files.values() if "/.variants/" not in entry["path"] + } + return _AliasBook(files, md5_to_sha1, name_to_sha1, holders, families, named_primaries) + + +def _platform_aliases(book: _AliasBook, unreadable: list[str]) -> None: + """Register the names platform YAMLs give a held content.""" + platforms_dir = Path("platforms") + if not platforms_dir.is_dir(): + return + for platform_name in list_registered_platforms( + str(platforms_dir) + ): + config_file = platforms_dir / f"{platform_name}.yml" + try: + config = source_yaml_file(config_file) or {} + except SourceUnreadable as e: + unreadable.append(str(e)) + continue + except OSError as e: + unreadable.append(f"{config_file}: {e}") + continue + + for system in config.get("systems", {}).values(): + for file_entry in system.get("files", []): + name = file_entry.get("name", "") + sha1 = file_entry.get("sha1", "") + md5 = file_entry.get("md5", "") + + # A zipped_file entry verifies a ROM INSIDE the + # archive, so its hash describes the member and not + # the file the name designates. Registering the name + # against that hash made d2fdc.zip an alias of a + # loose 256-byte state-machine-16.rom, which three + # platforms were then served in place of the archive. + if file_entry.get("zipped_file"): + continue + + matched = None + if sha1 and sha1 in book.files: + matched = sha1 + elif md5 and md5 in book.md5_to_sha1: + matched = book.md5_to_sha1[md5] + + if matched: + book.add(name, matched) + + +def _profile_entry_aliases( + book: _AliasBook, + file_entry: dict, + primary_names: set[str], + shadowed: list[tuple[str, set[str], list[str]]] | None, +) -> None: + """Register the aliases one profile entry gives the contents it designates.""" + entry_name = file_entry.get("name", "") + entry_aliases = _own_aliases(file_entry, primary_names) + # A profile may accept several revisions: each held one + # is designated by the entry, none of them by guess. + matched: set[str] = { + value for value in hash_values(file_entry.get("sha1")) + if value in book.files + } + matched |= { + book.md5_to_sha1[value] + for value in hash_values(file_entry.get("md5")) + if value in book.md5_to_sha1 + } + if matched: + # Proven by content, the profile's own name designates + # the file whatever the collection calls it. + entry_aliases.insert(0, entry_name) + if not entry_aliases: + return + if shadowed is not None: + taken = [ + alias for alias in entry_aliases + if alias != entry_name and alias in book.named_primaries + ] + if taken: + shadowed.append((entry_name, set(matched), taken)) + held = book.holders.get(entry_name, set()) + if ( + not matched + and len(held) == 1 + and len(book.families[entry_name.casefold()]) == 1 + ): + # A name carried by several contents names none of them: + # quasi88's disk.rom aliases went to whichever + # disk.rom the scan met last, a Tandy CoCo ROM. + matched = set(held) + for sha in sorted(matched): + for alias_name in entry_aliases: + book.add(alias_name, sha) + + +def _profile_aliases( + book: _AliasBook, + shadowed: list[tuple[str, set[str], list[str]]] | None, + unreadable: list[str], +) -> None: + """Register the aliases emulator YAMLs give (aliases field on file entries).""" + emulators_dir = Path("emulators") + if not emulators_dir.is_dir(): + return + for emu_file in source_yaml_paths(emulators_dir): + try: + emu_config = source_yaml_file(emu_file) or {} + except SourceUnreadable as e: + unreadable.append(str(e)) + continue + except OSError as e: + unreadable.append(f"{emu_file}: {e}") + continue + # A profile whose entries name each other (dosbox-x opens + # MT32_CONTROL.ROM and CM32L_CONTROL.ROM alike, so each entry + # aliases the other) states that ITS slot takes either name. + # Indexed globally that became evidence for every emulator: + # ScummVM's MT-32 slot received the CM-32L ROMs. + primary_names = _primary_names(emu_config.get("files", [])) + for file_entry in emu_config.get("files", []): + _profile_entry_aliases(book, file_entry, primary_names, shadowed) + + +# Identical content named differently across platforms/cores +KNOWN_ALIAS_GROUPS = [ + # ColecoVision - all these are the same 8KB BIOS + ["colecovision.rom", "coleco.rom", "BIOS.col", "bioscv.rom"], + # Game Boy - DMG boot ROM + ["gb_bios.bin", "dmg_boot.bin", "dmg_rom.bin", "dmg0_rom.bin"], + # Game Boy Color - CGB boot ROM + ["gbc_bios.bin", "cgb_boot.bin", "cgb0_boot.bin", "cgb_agb_boot.bin"], + # Super Game Boy + ["sgb_bios.bin", "sgb_boot.bin", "sgb.boot.rom"], + ["sgb2_bios.bin", "sgb2_boot.bin", "sgb2.boot.rom"], + ["sgb1.program.rom", "SGB1.sfc/program.rom"], + ["sgb2.program.rom", "SGB2.sfc/program.rom"], + # Nintendo DS. DraStic opens nds_bios_arm9.bin, nds_bios_arm7.bin + # and nds_firmware.bin and checks their size only: the collection + # answers those names with its DS dumps. + ["NDS_Bios7.bin", "bios7.bin", "nds7.bin", "nds_bios_arm7.bin"], + ["NDS_Bios9.bin", "bios9.bin", "nds9.bin", "nds_bios_arm9.bin"], + ["NDS_Lite_Firmware.bin", "nds_firmware.bin"], + ["dsi_sd_card.bin", "nds_sd_card.bin"], + # MSX + ["MSX.ROM", "MSX.rom", "Machines/Shared Roms/MSX.rom"], + # NEC PC-98 + ["N88KNJ1.ROM", "n88knj1.rom", "quasi88/n88knj1.rom"], + # Enterprise + ["zt19uk.rom", "zt19hfnt.rom", "ep128emu/roms/zt19hfnt.rom"], + # ZX Spectrum + ["48.rom", "zx48.rom"], + # SquirrelJME - all JARs are the same + [ + "squirreljme.sqc", + "squirreljme.jar", + "squirreljme-fast.jar", + "squirreljme-slow.jar", + "squirreljme-slow-test.jar", + "squirreljme-0.3.0.jar", + "squirreljme-0.3.0-fast.jar", + "squirreljme-0.3.0-slow.jar", + "squirreljme-0.3.0-slow-test.jar", + ], + # Arcade - FBNeo spectrum + ["spectrum.zip", "fbneo/spectrum.zip", "spec48k.zip"], +] + + +def collect_all_aliases( + files: dict, + copies: dict | None = None, + shadowed: list[tuple[str, set[str], list[str]]] | None = None, +) -> dict: + """Collect alternate filenames from platform YAMLs, core-info, and known aliases. + + Registers alternate names so generate_pack can resolve files stored under different names. + ``copies`` maps a sha1 to the other files the scan found with that content. + ``shadowed`` receives, per profile entry, its name, the contents its hashes + designate and the aliases a primary's name already carries. + """ + book = _alias_book(files, copies) + + # A source that does not parse is reported and the run refused: written + # without it, the database lost every alias the file proves and the + # command exited 0 (dosbox-x's wqy fonts answered not_found). + unreadable: list[str] = [] + _platform_aliases(book, unreadable) + + # core-info is not read here: it was the only network call of a build + # that must give the same database offline, and the one name it added + # (gearcoleco's writer.rom) is a profile entry proven by its sha1, which + # the profile pass below now registers. + + _profile_aliases(book, shadowed, unreadable) + + for group in KNOWN_ALIAS_GROUPS: + matched_sha1 = None + for name in group: + if name in book.name_to_sha1: + matched_sha1 = book.name_to_sha1[name] + break + if not matched_sha1: + continue + for name in group: + book.add(name, matched_sha1) + + if unreadable: + raise UnreadableSource(unreadable) + return book.aliases + + +def add_declared_aliases( + files: dict, + aliases: dict[str, list[dict]], + shadowed: list[tuple[str, set[str], list[str]]], +) -> None: + """Append to the scan's copies every alternate name the declarations give a held content.""" + declared = collect_all_aliases(files, aliases, shadowed) + for sha1, name_list in declared.items(): + for alias_entry in name_list: + if sha1 not in aliases: + aliases[sha1] = [] + aliases[sha1].append(alias_entry) diff --git a/scripts/collection/declared.py b/scripts/collection/declared.py new file mode 100644 index 000000000..d02152c9c --- /dev/null +++ b/scripts/collection/declared.py @@ -0,0 +1,34 @@ +"""The file entries the registered platforms and the emulator profiles declare, and their hash fields.""" + +from __future__ import annotations + +from pathlib import Path + +from model.profiles import source_yaml_paths +from model.registry import list_registered_platforms +from model.sources import source_yaml_file + + +def hash_values(value: object) -> list[str]: + """A hash field as lowercase values, whether written alone or as a list.""" + if not value: + return [] + values = value if isinstance(value, list) else str(value).split(",") + return [str(v).strip().lower() for v in values if str(v).strip()] + + +def declarations(platforms_dir: Path, emulators_dir: Path) -> list[dict]: + """Every file entry the registered platforms and the profiles declare.""" + sources = [ + platforms_dir / f"{name}.yml" + for name in list_registered_platforms(str(platforms_dir)) + ] if platforms_dir.is_dir() else [] + entries: list[dict] = [] + for source in sources: + config = source_yaml_file(source) or {} + for system in (config.get("systems") or {}).values(): + entries.extend(system.get("files") or []) + if emulators_dir.is_dir(): + for source in source_yaml_paths(emulators_dir): + entries.extend((source_yaml_file(source) or {}).get("files") or []) + return entries diff --git a/scripts/collection/hashcache.py b/scripts/collection/hashcache.py new file mode 100644 index 000000000..47c64db1e --- /dev/null +++ b/scripts/collection/hashcache.py @@ -0,0 +1,30 @@ +"""The digest cache a scan of bios/ reuses for files whose mtime and size did not move.""" + +from __future__ import annotations + +import json +import os + +from core.artifacts import write_text_atomic + +CACHE_DIR = ".cache" +CACHE_FILE = os.path.join(CACHE_DIR, "db_cache.json") + + +def load_cache(cache_path: str) -> dict: + """Load cache file if it exists.""" + try: + with open(cache_path) as f: + return json.load(f) + except (FileNotFoundError, json.JSONDecodeError): + return {} + + +def save_cache(cache_path: str, cache: dict) -> None: + """Save the cache whole or not at all. + + Written in place, a crash while serializing left a truncated file that + the next run read as empty and rehashed the collection from scratch. + """ + os.makedirs(os.path.dirname(cache_path), exist_ok=True) + write_text_atomic(cache_path, json.dumps(cache)) diff --git a/scripts/collection/indexes.py b/scripts/collection/indexes.py new file mode 100644 index 000000000..d6ac08e74 --- /dev/null +++ b/scripts/collection/indexes.py @@ -0,0 +1,167 @@ +"""The secondary indexes of database.json: by hash, name, path tail, shadowed alias and proven name.""" + +from __future__ import annotations + +import os + +from collection.declared import hash_values + + +def _path_suffixes(rel_path: str) -> list[str]: + """Every tail of a stored path that can answer a declared destination. + + A destination and the tree meet on a tail, and which tail is unknowable + from here: one profile writes GC/USA/IPL.bin, another writes the whole + nand/.../00000000.app.romfs. Indexing only the tail after + bios/Manufacturer/Console answered the first and never the second, so + every same-named file collapsed onto one entry. + + The bare filename is left out on purpose. by_name already holds it, and a + name alone is the weakest evidence there is. + + bios/Nintendo/GameCube/GC/USA/IPL.bin -> GC/USA/IPL.bin, USA/IPL.bin + """ + parts = [p for p in rel_path.replace("\\", "/").split("/") if p] + if parts and parts[0] == "bios": + parts = parts[1:] + return ["/".join(parts[-depth:]) for depth in range(len(parts), 1, -1)] + + +def build_indexes(files: dict, aliases: dict) -> dict: + """Build secondary indexes for fast lookup.""" + by_md5: dict[str, str] = {} + by_name: dict[str, list[str]] = {} + by_crc32: dict[str, str] = {} + by_sha256: dict[str, str] = {} + by_path_suffix: dict[str, list[str]] = {} + + for sha1, entry in files.items(): + by_md5[entry["md5"]] = sha1 + + name = entry["name"] + if name not in by_name: + by_name[name] = [] + by_name[name].append(sha1) + + by_crc32[entry["crc32"]] = sha1 + by_sha256[entry["sha256"]] = sha1 + + # Path suffix index for regional variant resolution + for suffix in _path_suffixes(entry["path"]): + if suffix == name: + continue + if suffix not in by_path_suffix: + by_path_suffix[suffix] = [] + if sha1 not in by_path_suffix[suffix]: + by_path_suffix[suffix].append(sha1) + + # Add alias names to by_name index (aliases have different filenames for same SHA1) + for sha1, alias_list in aliases.items(): + for alias in alias_list: + name = alias["name"] + if name not in by_name: + by_name[name] = [] + if sha1 not in by_name[name]: + by_name[name].append(sha1) + # Also index alias paths in by_path_suffix + for suffix in _path_suffixes(alias["path"]): + if suffix == name: + continue + if suffix not in by_path_suffix: + by_path_suffix[suffix] = [] + if sha1 not in by_path_suffix[suffix]: + by_path_suffix[suffix].append(sha1) + + return { + "by_md5": by_md5, + "by_name": by_name, + "by_crc32": by_crc32, + "by_sha256": by_sha256, + "by_path_suffix": by_path_suffix, + } + + +def shadowed_alias_index( + shadowed: list[tuple[str, set[str], list[str]]], by_name: dict +) -> dict[str, list[str]]: + """Profile aliases that a primary's name keeps out of by_name. + + QUASI88 reads DISK.ROM as n88sub.rom, but DISK.ROM is the MSX disk ROM's + own name, so by_name never points it at the PC-88 file. The resolver reads + this index only where the system names a maker and no copy filed under + that maker answers the name. An entry with no hash designates the content + its own name holds alone in by_name. + """ + index: dict[str, set[str]] = {} + for entry_name, matched, taken in shadowed: + held = by_name.get(entry_name, []) + designated = matched or (set(held) if len(held) == 1 else set()) + for alias in taken: + fresh = designated - set(by_name.get(alias, [])) + if fresh: + index.setdefault(alias, set()).update(fresh) + return {alias: sorted(sha1s) for alias, sha1s in sorted(index.items())} + + +def proven_name_index( + files: dict, indexes: dict, declarations: list[dict] +) -> dict[str, list[str]]: + """Names whose held primary no declaration proves, mapped to the primaries + of the same directory that declarations of that name prove by hash. + + A hashless entry takes a name's file by name alone. The collection files + the DSi Panda devkit boot ROMs as dsi_bios7.bin and dsi_bios9.bin, with + the eMMC key-Y zeroed, while every hash declared under those names + designates a retail dump beside them: RetroBat and dsperate were served + the devkit ROMs. Another revision kept in .variants/ is not a primary, + and a dump filed elsewhere is another machine's file. + """ + by_hash = { + "sha1": {sha1: sha1 for sha1 in files}, + "md5": indexes.get("by_md5", {}), + "crc32": indexes.get("by_crc32", {}), + "sha256": indexes.get("by_sha256", {}), + } + proven: dict[str, set[str]] = {} + for entry in declarations: + # A zipped_file hash is the member's, not the file the name designates. + if not isinstance(entry, dict) or entry.get("zipped_file"): + continue + name = str(entry.get("name") or "").rsplit("/", 1)[-1] + if not name: + continue + for kind, index in by_hash.items(): + for value in hash_values(entry.get(kind)): + held = index.get(value) + if held in files: + proven.setdefault(name, set()).add(held) + result: dict[str, list[str]] = {} + for name, designated in sorted(proven.items()): + primaries = { + sha1 for sha1 in indexes.get("by_name", {}).get(name, []) + if sha1 in files and "/.variants/" not in files[sha1]["path"] + } + if not primaries or primaries & designated: + continue + homes = {os.path.dirname(files[sha1]["path"]) for sha1 in primaries} + beside = [ + sha1 for sha1 in designated + if "/.variants/" not in files[sha1]["path"] + and os.path.dirname(files[sha1]["path"]) in homes + ] + if beside: + result[name] = sorted(beside, key=lambda sha1: files[sha1]["path"]) + return result + + +def database_indexes( + files: dict, + aliases: dict, + shadowed: list[tuple[str, set[str], list[str]]], + declarations: list[dict], +) -> dict: + """Every index database.json publishes over the scanned files and their aliases.""" + indexes = build_indexes(files, aliases) + indexes["by_shadowed_alias"] = shadowed_alias_index(shadowed, indexes["by_name"]) + indexes["by_proven_name"] = proven_name_index(files, indexes, declarations) + return indexes diff --git a/scripts/collection/record.py b/scripts/collection/record.py new file mode 100644 index 000000000..37c8dfa0b --- /dev/null +++ b/scripts/collection/record.py @@ -0,0 +1,46 @@ +"""The database.json record: its fields, the sha1s a rebuild retires, and its write.""" + +from __future__ import annotations + +import json +import os +from datetime import datetime, timezone +from pathlib import Path + +from core.artifacts import write_if_changed +from model import retired + + +def database_record(files: dict, indexes: dict, bios_dir: str) -> dict: + """The database over the scanned files, stamped with the time of the build.""" + return { + "schema_version": 1, + "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "total_files": len(files), + "total_size": sum(entry["size"] for entry in files.values()), + # The tree these paths belong to: dedup writes _mame_clones.json + # beside it, and the resolver reads the map there, not at the repo root. + "bios_dir": os.path.normpath(bios_dir), + "files": files, + "indexes": indexes, + } + + +def record_retired(output: Path, database: dict) -> int: + """Record beside the database the sha1s the rebuild drops from the one at output. + + A sha1 the rebuild drops keeps its published address: the record + beside the database says when it left and what holds its place. + """ + if not output.is_file(): + return 0 + previous = json.loads(output.read_text(encoding="utf-8")) + return retired.update( + retired.retired_path(output), previous, database, + database["generated_at"][:10], + ) + + +def write_database(output: str, database: dict) -> bool: + """Write the database unless only its timestamp moved; whether it was written.""" + return write_if_changed(output, json.dumps(database, indent=2)) diff --git a/scripts/collection/releaseassets.py b/scripts/collection/releaseassets.py new file mode 100644 index 000000000..89ee55250 --- /dev/null +++ b/scripts/collection/releaseassets.py @@ -0,0 +1,67 @@ +"""The database entries of release assets the checkout does not hold, kept across a scan.""" + +from __future__ import annotations + +import json +import os + + +def load_gitignored_large_files() -> set[str]: + """The bios/ paths .gitignore registers as release assets.""" + from model.largefiles import load_registered_paths + + return set(load_registered_paths(".gitignore")) + + +def preserve_large_file_entries(files: dict, db_path: str) -> int: + """Keep the entries of release assets the checkout does not hold. + + Files kept out of git live as assets of the large-files release, and + .gitignore registers their paths. An entry survives a scan that missed + its file only under that registered path: a bare name is shared by + other files (pak0.pk3, history.db), and a path rewritten into the + download cache is no longer one .gitignore knows, so the manifest + would send the installer to the repository for it. A fetched asset is + written back to its registered path. + """ + from model.largefiles import fetch_large_file, restore_verified + + registered = load_gitignored_large_files() + if not registered: + return 0 + + try: + with open(db_path) as f: + existing_db = json.load(f) + except FileNotFoundError: + return 0 + except json.JSONDecodeError as e: + # An unreadable database is not an absent one: rewriting it from a + # checkout without the release assets would drop every entry they + # hold, and the manifests regenerated from it would omit them. + raise SystemExit( + f"{db_path} is not valid JSON ({e}). Restore it from git " + "or regenerate it on a checkout holding the release assets before " + "scanning again" + ) from e + + # A path the scan just claimed holds known bytes. An older entry naming + # the same path describes a revision that is no longer there, and keeping + # it would publish a hash that contradicts the file it points at. + scanned_paths = {entry.get("path", "") for entry in files.values()} + + count = 0 + for sha1, entry in existing_db.get("files", {}).items(): + path = entry.get("path", "") + if sha1 in files or path not in registered or path in scanned_paths: + continue + cached = fetch_large_file( + path, + expected_sha1=entry.get("sha1", ""), + expected_md5=entry.get("md5", ""), + ) + if cached and not os.path.exists(path): + restore_verified(cached, path, sha1) + files[sha1] = entry + count += 1 + return count diff --git a/scripts/collection/scan.py b/scripts/collection/scan.py new file mode 100644 index 000000000..b304cf8c5 --- /dev/null +++ b/scripts/collection/scan.py @@ -0,0 +1,160 @@ +"""The walk of bios/: which files count, their digests, and which copy of a content is primary.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from core.hashing import compute_hashes +from resolve.localfile import variant_base_name + +SKIP_PATTERNS = {".git", ".github", "__pycache__", ".cache", ".DS_Store", "desktop.ini"} + +# Every digest database.json publishes per file, in the order compute_hashes +# returns them. The schema requires all five, so a cache entry missing any of +# them cannot serve a database entry, and the order is fixed here so a warm +# cache serialises an entry exactly like a fresh hash does. +CACHED_HASHES = ("sha1", "md5", "sha256", "crc32", "adler32") + + +def should_skip(path: Path) -> bool: + """Whether a path stays out of the collection. + + Tooling directories and hidden files do. A hidden directory inside the + collection does not: `.variants/` holds alternate dumps, and an engine + tree can carry one of its own (C-Dogs SDL reads `data/.wolf3d/`). + """ + if any(part in SKIP_PATTERNS for part in path.parts): + return True + return path.name.startswith(".") + + +def _canonical_name(filepath: Path) -> str: + """Get canonical filename, stripping .variants/ hash suffix.""" + if ".variants" in filepath.parts: + return variant_base_name(filepath.name) + return filepath.name + + +def _settled_hashes( + filepath: Path, cached: dict | None, mtime: float, size: int +) -> dict: + """The file's digests, computed again when they contradict the cache. + + A forced run rehashes everything, and this host has given a wrong SHA-1 + under load (DSi_Nand_USA.bin read as 834b140f, not ef08ae02). An entry + whose mtime and size did not move but whose digest did is hashed a + second time. A second reading that gives the cached value back settles it. + Two readings that agree against it do not: the host has returned the same + wrong digest twice in a row (62b100f2 for the same file), and a value + taken then is cached and read back by every later run. A file rewritten + in place moves its mtime, so the run stops instead of choosing. + """ + hashes = compute_hashes(filepath) + if not cached or cached.get("mtime") != mtime or cached.get("size") != size: + return hashes + if cached.get("sha1") in (None, hashes["sha1"]): + return hashes + again = compute_hashes(filepath, cache=False) + print( + f" WARNING: {filepath}: sha1 read as {hashes['sha1'][:8]} then " + f"{again['sha1'][:8]}, cached {cached['sha1'][:8]}", + file=sys.stderr, + ) + if again["sha1"] == cached["sha1"]: + return again + raise RuntimeError( + f"{filepath}: read as {again['sha1'][:8]}, cached as {cached['sha1'][:8]}, " + "with the same mtime and size. Rerun when the host is idle, or " + f"`touch {filepath}` if its bytes really changed." + ) + + +def _emulator_tree(path: str) -> bool: + """Whether a path lies in one emulator's own tree, bios/Other//.""" + parts = path.replace("\\", "/").split("/") + return len(parts) > 3 and parts[1] == "Other" + + +def _takes_primary(current: str, candidate: str) -> bool: + """Whether another copy of the same bytes becomes the content's path. + + A .variants/ copy yields to any other one. A copy in an emulator's own + tree yields to one filed under its machine: ZEsarUX's sms.rom sorted + before bios/Sega/Master System/, the resolver set it aside as another + emulator's file, and Genesis Plus GX got a variant instead of v1.3. + """ + if "/.variants/" in candidate.replace("\\", "/"): + return False + if "/.variants/" in current: + return True + return _emulator_tree(current) and not _emulator_tree(candidate) + + +def _add_scanned( + files: dict[str, dict], + aliases: dict[str, list[dict]], + filepath: Path, + rel_path: str, + size: int, + hashes: dict, +) -> None: + """Record a scanned file as its content's primary, or as an alias of it.""" + sha1 = hashes["sha1"] + entry = { + "path": rel_path, + "name": _canonical_name(filepath), + "size": size, + **hashes, + } + if sha1 not in files: + files[sha1] = entry + elif _takes_primary(files[sha1]["path"], rel_path): + aliases.setdefault(sha1, []).append( + {"name": files[sha1]["name"], "path": files[sha1]["path"]} + ) + files[sha1] = entry + else: + aliases.setdefault(sha1, []).append({"name": entry["name"], "path": rel_path}) + + +def _cached_hashes(cached: dict | None, mtime: float, size: int) -> dict | None: + """The cache's digests of a file that has not changed since.""" + if cached is None: + return None + fresh = cached.get("mtime") == mtime and cached.get("size") == size + # Rebuilding the hash dict by hand dropped whichever digest the + # list forgot, and the entry was then written back to the cache + # without it, so the loss survived every later run. Requiring the + # full set instead turns a partial cache entry into a miss, which + # heals it. + if fresh and all(name in cached for name in CACHED_HASHES): + return {name: cached[name] for name in CACHED_HASHES} + return None + + +def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict, dict]: + """Scan bios directory and compute hashes, using cache when possible.""" + files: dict[str, dict] = {} + aliases: dict[str, list[dict]] = {} + new_cache = {} + + for filepath in sorted(bios_dir.rglob("*")): + if not filepath.is_file(): + continue + if should_skip(filepath.relative_to(bios_dir)): + continue + + rel_path = str(filepath.relative_to(bios_dir.parent)) + stat = filepath.stat() + mtime = stat.st_mtime + size = stat.st_size + cache_key = rel_path + + hashes = None if force else _cached_hashes(cache.get(cache_key), mtime, size) + if hashes is None: + hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size) + _add_scanned(files, aliases, filepath, rel_path, size, hashes) + new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size} + + return files, aliases, new_cache diff --git a/scripts/generate_db.py b/scripts/generate_db.py index 4f7ec5c6a..2ec761447 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -11,432 +11,30 @@ Use --force to rehash all files. from __future__ import annotations import argparse -import json import os import sys -from dataclasses import dataclass, field -from datetime import datetime, timezone from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) -from core.cli import SourceUnreadable, add_repo_inputs, require_directory +from core.cli import add_repo_inputs, require_directory from model.dumpcatalog import annotate_provenance, DEFAULT_PROVENANCE_DIR, load_provenance_snapshots -from core.hashing import compute_hashes -from model.registry import list_registered_platforms -from core.artifacts import ( - repository_output_lock, - write_if_changed, - write_text_atomic, -) +from core.artifacts import repository_output_lock from model.safeparse import require_yaml -from model.sources import source_yaml_file -from model.profiles import source_yaml_paths -from resolve.localfile import variant_base_name from model import retired +from collection.aliases import UnreadableSource, add_declared_aliases +from collection.declared import declarations +from collection.hashcache import CACHE_FILE, load_cache, save_cache +from collection.indexes import database_indexes +from collection.record import database_record, record_retired, write_database +from collection.releaseassets import preserve_large_file_entries +from collection.scan import scan_bios_dir # Platform and profile aliases are read from YAML: without pyyaml the # database lost every one of them and the run still exited 0. yaml = require_yaml() -CACHE_DIR = ".cache" -CACHE_FILE = os.path.join(CACHE_DIR, "db_cache.json") DEFAULT_OUTPUT = "database.json" -SKIP_PATTERNS = {".git", ".github", "__pycache__", ".cache", ".DS_Store", "desktop.ini"} - -# Every digest database.json publishes per file, in the order compute_hashes -# returns them. The schema requires all five, so a cache entry missing any of -# them cannot serve a database entry, and the order is fixed here so a warm -# cache serialises an entry exactly like a fresh hash does. -CACHED_HASHES = ("sha1", "md5", "sha256", "crc32", "adler32") - - -def should_skip(path: Path) -> bool: - """Whether a path stays out of the collection. - - Tooling directories and hidden files do. A hidden directory inside the - collection does not: `.variants/` holds alternate dumps, and an engine - tree can carry one of its own (C-Dogs SDL reads `data/.wolf3d/`). - """ - if any(part in SKIP_PATTERNS for part in path.parts): - return True - return path.name.startswith(".") - - -def _canonical_name(filepath: Path) -> str: - """Get canonical filename, stripping .variants/ hash suffix.""" - if ".variants" in filepath.parts: - return variant_base_name(filepath.name) - return filepath.name - - -def _settled_hashes( - filepath: Path, cached: dict | None, mtime: float, size: int -) -> dict: - """The file's digests, computed again when they contradict the cache. - - A forced run rehashes everything, and this host has given a wrong SHA-1 - under load (DSi_Nand_USA.bin read as 834b140f, not ef08ae02). An entry - whose mtime and size did not move but whose digest did is hashed a - second time. A second reading that gives the cached value back settles it. - Two readings that agree against it do not: the host has returned the same - wrong digest twice in a row (62b100f2 for the same file), and a value - taken then is cached and read back by every later run. A file rewritten - in place moves its mtime, so the run stops instead of choosing. - """ - hashes = compute_hashes(filepath) - if not cached or cached.get("mtime") != mtime or cached.get("size") != size: - return hashes - if cached.get("sha1") in (None, hashes["sha1"]): - return hashes - again = compute_hashes(filepath, cache=False) - print( - f" WARNING: {filepath}: sha1 read as {hashes['sha1'][:8]} then " - f"{again['sha1'][:8]}, cached {cached['sha1'][:8]}", - file=sys.stderr, - ) - if again["sha1"] == cached["sha1"]: - return again - raise RuntimeError( - f"{filepath}: read as {again['sha1'][:8]}, cached as {cached['sha1'][:8]}, " - "with the same mtime and size. Rerun when the host is idle, or " - f"`touch {filepath}` if its bytes really changed." - ) - - -def _emulator_tree(path: str) -> bool: - """Whether a path lies in one emulator's own tree, bios/Other//.""" - parts = path.replace("\\", "/").split("/") - return len(parts) > 3 and parts[1] == "Other" - - -def _takes_primary(current: str, candidate: str) -> bool: - """Whether another copy of the same bytes becomes the content's path. - - A .variants/ copy yields to any other one. A copy in an emulator's own - tree yields to one filed under its machine: ZEsarUX's sms.rom sorted - before bios/Sega/Master System/, the resolver set it aside as another - emulator's file, and Genesis Plus GX got a variant instead of v1.3. - """ - if "/.variants/" in candidate.replace("\\", "/"): - return False - if "/.variants/" in current: - return True - return _emulator_tree(current) and not _emulator_tree(candidate) - - -def _add_scanned( - files: dict[str, dict], - aliases: dict[str, list[dict]], - filepath: Path, - rel_path: str, - size: int, - hashes: dict, -) -> None: - """Record a scanned file as its content's primary, or as an alias of it.""" - sha1 = hashes["sha1"] - entry = { - "path": rel_path, - "name": _canonical_name(filepath), - "size": size, - **hashes, - } - if sha1 not in files: - files[sha1] = entry - elif _takes_primary(files[sha1]["path"], rel_path): - aliases.setdefault(sha1, []).append( - {"name": files[sha1]["name"], "path": files[sha1]["path"]} - ) - files[sha1] = entry - else: - aliases.setdefault(sha1, []).append({"name": entry["name"], "path": rel_path}) - - -def _cached_hashes(cached: dict | None, mtime: float, size: int) -> dict | None: - """The cache's digests of a file that has not changed since.""" - if cached is None: - return None - fresh = cached.get("mtime") == mtime and cached.get("size") == size - # Rebuilding the hash dict by hand dropped whichever digest the - # list forgot, and the entry was then written back to the cache - # without it, so the loss survived every later run. Requiring the - # full set instead turns a partial cache entry into a miss, which - # heals it. - if fresh and all(name in cached for name in CACHED_HASHES): - return {name: cached[name] for name in CACHED_HASHES} - return None - - -def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict, dict]: - """Scan bios directory and compute hashes, using cache when possible.""" - files: dict[str, dict] = {} - aliases: dict[str, list[dict]] = {} - new_cache = {} - - for filepath in sorted(bios_dir.rglob("*")): - if not filepath.is_file(): - continue - if should_skip(filepath.relative_to(bios_dir)): - continue - - rel_path = str(filepath.relative_to(bios_dir.parent)) - stat = filepath.stat() - mtime = stat.st_mtime - size = stat.st_size - cache_key = rel_path - - hashes = None if force else _cached_hashes(cache.get(cache_key), mtime, size) - if hashes is None: - hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size) - _add_scanned(files, aliases, filepath, rel_path, size, hashes) - new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size} - - return files, aliases, new_cache - - -def _path_suffixes(rel_path: str) -> list[str]: - """Every tail of a stored path that can answer a declared destination. - - A destination and the tree meet on a tail, and which tail is unknowable - from here: one profile writes GC/USA/IPL.bin, another writes the whole - nand/.../00000000.app.romfs. Indexing only the tail after - bios/Manufacturer/Console answered the first and never the second, so - every same-named file collapsed onto one entry. - - The bare filename is left out on purpose. by_name already holds it, and a - name alone is the weakest evidence there is. - - bios/Nintendo/GameCube/GC/USA/IPL.bin -> GC/USA/IPL.bin, USA/IPL.bin - """ - parts = [p for p in rel_path.replace("\\", "/").split("/") if p] - if parts and parts[0] == "bios": - parts = parts[1:] - return ["/".join(parts[-depth:]) for depth in range(len(parts), 1, -1)] - - -def build_indexes(files: dict, aliases: dict) -> dict: - """Build secondary indexes for fast lookup.""" - by_md5: dict[str, str] = {} - by_name: dict[str, list[str]] = {} - by_crc32: dict[str, str] = {} - by_sha256: dict[str, str] = {} - by_path_suffix: dict[str, list[str]] = {} - - for sha1, entry in files.items(): - by_md5[entry["md5"]] = sha1 - - name = entry["name"] - if name not in by_name: - by_name[name] = [] - by_name[name].append(sha1) - - by_crc32[entry["crc32"]] = sha1 - by_sha256[entry["sha256"]] = sha1 - - # Path suffix index for regional variant resolution - for suffix in _path_suffixes(entry["path"]): - if suffix == name: - continue - if suffix not in by_path_suffix: - by_path_suffix[suffix] = [] - if sha1 not in by_path_suffix[suffix]: - by_path_suffix[suffix].append(sha1) - - # Add alias names to by_name index (aliases have different filenames for same SHA1) - for sha1, alias_list in aliases.items(): - for alias in alias_list: - name = alias["name"] - if name not in by_name: - by_name[name] = [] - if sha1 not in by_name[name]: - by_name[name].append(sha1) - # Also index alias paths in by_path_suffix - for suffix in _path_suffixes(alias["path"]): - if suffix == name: - continue - if suffix not in by_path_suffix: - by_path_suffix[suffix] = [] - if sha1 not in by_path_suffix[suffix]: - by_path_suffix[suffix].append(sha1) - - return { - "by_md5": by_md5, - "by_name": by_name, - "by_crc32": by_crc32, - "by_sha256": by_sha256, - "by_path_suffix": by_path_suffix, - } - - -def shadowed_alias_index( - shadowed: list[tuple[str, set[str], list[str]]], by_name: dict -) -> dict[str, list[str]]: - """Profile aliases that a primary's name keeps out of by_name. - - QUASI88 reads DISK.ROM as n88sub.rom, but DISK.ROM is the MSX disk ROM's - own name, so by_name never points it at the PC-88 file. The resolver reads - this index only where the system names a maker and no copy filed under - that maker answers the name. An entry with no hash designates the content - its own name holds alone in by_name. - """ - index: dict[str, set[str]] = {} - for entry_name, matched, taken in shadowed: - held = by_name.get(entry_name, []) - designated = matched or (set(held) if len(held) == 1 else set()) - for alias in taken: - fresh = designated - set(by_name.get(alias, [])) - if fresh: - index.setdefault(alias, set()).update(fresh) - return {alias: sorted(sha1s) for alias, sha1s in sorted(index.items())} - - -def _declarations(platforms_dir: Path, emulators_dir: Path) -> list[dict]: - """Every file entry the registered platforms and the profiles declare.""" - sources = [ - platforms_dir / f"{name}.yml" - for name in list_registered_platforms(str(platforms_dir)) - ] if platforms_dir.is_dir() else [] - entries: list[dict] = [] - for source in sources: - config = source_yaml_file(source) or {} - for system in (config.get("systems") or {}).values(): - entries.extend(system.get("files") or []) - if emulators_dir.is_dir(): - for source in source_yaml_paths(emulators_dir): - entries.extend((source_yaml_file(source) or {}).get("files") or []) - return entries - - -def proven_name_index( - files: dict, indexes: dict, declarations: list[dict] -) -> dict[str, list[str]]: - """Names whose held primary no declaration proves, mapped to the primaries - of the same directory that declarations of that name prove by hash. - - A hashless entry takes a name's file by name alone. The collection files - the DSi Panda devkit boot ROMs as dsi_bios7.bin and dsi_bios9.bin, with - the eMMC key-Y zeroed, while every hash declared under those names - designates a retail dump beside them: RetroBat and dsperate were served - the devkit ROMs. Another revision kept in .variants/ is not a primary, - and a dump filed elsewhere is another machine's file. - """ - by_hash = { - "sha1": {sha1: sha1 for sha1 in files}, - "md5": indexes.get("by_md5", {}), - "crc32": indexes.get("by_crc32", {}), - "sha256": indexes.get("by_sha256", {}), - } - proven: dict[str, set[str]] = {} - for entry in declarations: - # A zipped_file hash is the member's, not the file the name designates. - if not isinstance(entry, dict) or entry.get("zipped_file"): - continue - name = str(entry.get("name") or "").rsplit("/", 1)[-1] - if not name: - continue - for kind, index in by_hash.items(): - for value in _as_list(entry.get(kind)): - held = index.get(value) - if held in files: - proven.setdefault(name, set()).add(held) - result: dict[str, list[str]] = {} - for name, designated in sorted(proven.items()): - primaries = { - sha1 for sha1 in indexes.get("by_name", {}).get(name, []) - if sha1 in files and "/.variants/" not in files[sha1]["path"] - } - if not primaries or primaries & designated: - continue - homes = {os.path.dirname(files[sha1]["path"]) for sha1 in primaries} - beside = [ - sha1 for sha1 in designated - if "/.variants/" not in files[sha1]["path"] - and os.path.dirname(files[sha1]["path"]) in homes - ] - if beside: - result[name] = sorted(beside, key=lambda sha1: files[sha1]["path"]) - return result - - -def load_cache(cache_path: str) -> dict: - """Load cache file if it exists.""" - try: - with open(cache_path) as f: - return json.load(f) - except (FileNotFoundError, json.JSONDecodeError): - return {} - - -def save_cache(cache_path: str, cache: dict) -> None: - """Save the cache whole or not at all. - - Written in place, a crash while serializing left a truncated file that - the next run read as empty and rehashed the collection from scratch. - """ - os.makedirs(os.path.dirname(cache_path), exist_ok=True) - write_text_atomic(cache_path, json.dumps(cache)) - - -def _load_gitignored_large_files() -> set[str]: - """The bios/ paths .gitignore registers as release assets.""" - from model.largefiles import load_registered_paths - - return set(load_registered_paths(".gitignore")) - - -def _preserve_large_file_entries(files: dict, db_path: str) -> int: - """Keep the entries of release assets the checkout does not hold. - - Files kept out of git live as assets of the large-files release, and - .gitignore registers their paths. An entry survives a scan that missed - its file only under that registered path: a bare name is shared by - other files (pak0.pk3, history.db), and a path rewritten into the - download cache is no longer one .gitignore knows, so the manifest - would send the installer to the repository for it. A fetched asset is - written back to its registered path. - """ - from model.largefiles import fetch_large_file, restore_verified - - registered = _load_gitignored_large_files() - if not registered: - return 0 - - try: - with open(db_path) as f: - existing_db = json.load(f) - except FileNotFoundError: - return 0 - except json.JSONDecodeError as e: - # An unreadable database is not an absent one: rewriting it from a - # checkout without the release assets would drop every entry they - # hold, and the manifests regenerated from it would omit them. - raise SystemExit( - f"{db_path} is not valid JSON ({e}). Restore it from git " - "or regenerate it on a checkout holding the release assets before " - "scanning again" - ) from e - - # A path the scan just claimed holds known bytes. An older entry naming - # the same path describes a revision that is no longer there, and keeping - # it would publish a hash that contradicts the file it points at. - scanned_paths = {entry.get("path", "") for entry in files.values()} - - count = 0 - for sha1, entry in existing_db.get("files", {}).items(): - path = entry.get("path", "") - if sha1 in files or path not in registered or path in scanned_paths: - continue - cached = fetch_large_file( - path, - expected_sha1=entry.get("sha1", ""), - expected_md5=entry.get("md5", ""), - ) - if cached and not os.path.exists(path): - restore_verified(cached, path, sha1) - files[sha1] = entry - count += 1 - return count - def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description="Generate multi-indexed BIOS database") @@ -470,61 +68,35 @@ def _generate(args: argparse.Namespace) -> int: print("Warning: No BIOS files found", file=sys.stderr) # Preserve entries for large files stored as release assets (.gitignore) - preserved = _preserve_large_file_entries(files, args.output) + preserved = preserve_large_file_entries(files, args.output) if preserved: print(f" Preserved {preserved} large file entries from existing database") shadowed: list[tuple[str, set[str], list[str]]] = [] try: - platform_aliases = _collect_all_aliases(files, aliases, shadowed) + add_declared_aliases(files, aliases, shadowed) except UnreadableSource as exc: for source in exc.sources: print(f"Error: cannot read {source}", file=sys.stderr) print(f"Error: {args.output} not written", file=sys.stderr) return 1 - for sha1, name_list in platform_aliases.items(): - for alias_entry in name_list: - if sha1 not in aliases: - aliases[sha1] = [] - aliases[sha1].append(alias_entry) snapshots = load_provenance_snapshots(args.provenance_dir) provenance_counts = annotate_provenance(files, snapshots) - indexes = build_indexes(files, aliases) - indexes["by_shadowed_alias"] = shadowed_alias_index(shadowed, indexes["by_name"]) - indexes["by_proven_name"] = proven_name_index( - files, indexes, _declarations(Path("platforms"), Path("emulators")) + indexes = database_indexes( + files, aliases, shadowed, declarations(Path("platforms"), Path("emulators")) ) - total_size = sum(entry["size"] for entry in files.values()) + database = database_record(files, indexes, args.bios_dir) + total_size = database["total_size"] - database = { - "schema_version": 1, - "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - "total_files": len(files), - "total_size": total_size, - # The tree these paths belong to: dedup writes _mame_clones.json - # beside it, and the resolver reads the map there, not at the repo root. - "bios_dir": os.path.normpath(args.bios_dir), - "files": files, - "indexes": indexes, - } - - # A sha1 the rebuild drops keeps its published address: the record - # beside the database says when it left and what holds its place. output = Path(args.output) - if output.is_file(): - previous = json.loads(output.read_text(encoding="utf-8")) - 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.retired_path(output)}") + left = record_retired(output, database) + if left: + print(f" Left the collection: {left} files, recorded in " + f"{retired.retired_path(output)}") - new_content = json.dumps(database, indent=2) - written = write_if_changed(args.output, new_content) + written = write_database(args.output, database) save_cache(CACHE_FILE, new_cache) @@ -542,311 +114,6 @@ def _generate(args: argparse.Namespace) -> int: return 0 -def _as_list(value: object) -> list[str]: - """A hash field as lowercase values, whether written alone or as a list.""" - if not value: - return [] - values = value if isinstance(value, list) else str(value).split(",") - return [str(v).strip().lower() for v in values if str(v).strip()] - - -def _primary_names(entries: list) -> set[str]: - return {str(fe.get("name", "")).lower() for fe in entries if isinstance(fe, dict)} - - -def _own_aliases(file_entry: dict, primary_names: set[str]) -> list[str]: - """Aliases that name no other entry of the same profile.""" - name = str(file_entry.get("name", "")).lower() - return [ - alias for alias in file_entry.get("aliases") or [] - if str(alias).lower() == name or str(alias).lower() not in primary_names - ] - - -class UnreadableSource(Exception): - """Platform or profile files that do not parse, named one per line.""" - - def __init__(self, sources: list[str]) -> None: - super().__init__("\n".join(sources)) - self.sources = sources - - -@dataclass -class _AliasBook: - """The alternate names collected so far, and what designates a content.""" - - files: dict - md5_to_sha1: dict[str, str] - name_to_sha1: dict[str, str] - # The contents held under each name, every copy counted. - holders: dict[str, set[str]] - # The files a name designates once case is folded. - families: dict[str, set[str]] - # A name only .variants/ copies carry is not a primary's. - named_primaries: set[str] - aliases: dict[str, list[dict]] = field(default_factory=dict) - - def add(self, name: str, matched_sha1: str) -> None: - if not name or name in self.named_primaries: - return - if matched_sha1 not in self.aliases: - self.aliases[matched_sha1] = [] - existing = {a["name"] for a in self.aliases[matched_sha1]} - if name not in existing: - self.aliases[matched_sha1].append({"name": name, "path": ""}) - - -def _alias_book(files: dict, copies: dict | None) -> _AliasBook: - """Index the scanned files by md5, name and folded name.""" - md5_to_sha1 = {} - name_to_sha1 = {} - for sha1, entry in files.items(): - md5_to_sha1[entry["md5"]] = sha1 - name_to_sha1[entry["name"]] = sha1 - # The contents held under each name, every copy counted and not only the - # primary: which copy of identical bytes is primary follows path order. - # Keyed on primaries alone, project64's 64DD_IPL_v12_JPN.bin stopped - # naming its content once 64DD_IPL.bin sorted first, and its aliases - # 64dd_ipl_J.bin and 64DD_IPL_JP.n64 went with it. - holders: dict[str, set[str]] = {} - # The files a name designates once case is folded, as the resolver's - # name step folds it, a primary and its own .variants/ counted as one - # file. dosbox's SC-55 ROM2.BIN found Galaksija's ROM2.BIN the only - # exact holder, and its alias ROM2_ST.BIN went to a 4 KiB BASIC ROM, - # while SC-55's rom2.bin sat under the same folded name. - families: dict[str, set[str]] = {} - - def _hold(name: str, path: str, sha1: str) -> None: - holders.setdefault(name, set()).add(sha1) - directory = path.rpartition("/")[0].removesuffix("/.variants") - families.setdefault(name.casefold(), set()).add( - f"{directory}/{variant_base_name(name)}".casefold() - ) - - for sha1, entry in files.items(): - _hold(entry["name"], entry["path"], sha1) - for sha1, copy_list in (copies or {}).items(): - if sha1 in files: - for copy in copy_list: - _hold(copy["name"], copy["path"], sha1) - - # A name only .variants/ copies carry is not a primary's: those copies are - # the other revisions of whatever the name designates. Retroarch pins - # bios_E.sms to v1.3, and with the name refused, Genesis Plus GX got the - # first variant in index order, a 256 KB BIOS, by the name step. - named_primaries = { - entry["name"] for entry in files.values() if "/.variants/" not in entry["path"] - } - return _AliasBook(files, md5_to_sha1, name_to_sha1, holders, families, named_primaries) - - -def _platform_aliases(book: _AliasBook, unreadable: list[str]) -> None: - """Register the names platform YAMLs give a held content.""" - platforms_dir = Path("platforms") - if not platforms_dir.is_dir(): - return - for platform_name in list_registered_platforms( - str(platforms_dir) - ): - config_file = platforms_dir / f"{platform_name}.yml" - try: - config = source_yaml_file(config_file) or {} - except SourceUnreadable as e: - unreadable.append(str(e)) - continue - except OSError as e: - unreadable.append(f"{config_file}: {e}") - continue - - for system in config.get("systems", {}).values(): - for file_entry in system.get("files", []): - name = file_entry.get("name", "") - sha1 = file_entry.get("sha1", "") - md5 = file_entry.get("md5", "") - - # A zipped_file entry verifies a ROM INSIDE the - # archive, so its hash describes the member and not - # the file the name designates. Registering the name - # against that hash made d2fdc.zip an alias of a - # loose 256-byte state-machine-16.rom, which three - # platforms were then served in place of the archive. - if file_entry.get("zipped_file"): - continue - - matched = None - if sha1 and sha1 in book.files: - matched = sha1 - elif md5 and md5 in book.md5_to_sha1: - matched = book.md5_to_sha1[md5] - - if matched: - book.add(name, matched) - - -def _profile_entry_aliases( - book: _AliasBook, - file_entry: dict, - primary_names: set[str], - shadowed: list[tuple[str, set[str], list[str]]] | None, -) -> None: - """Register the aliases one profile entry gives the contents it designates.""" - entry_name = file_entry.get("name", "") - entry_aliases = _own_aliases(file_entry, primary_names) - # A profile may accept several revisions: each held one - # is designated by the entry, none of them by guess. - matched: set[str] = { - value for value in _as_list(file_entry.get("sha1")) - if value in book.files - } - matched |= { - book.md5_to_sha1[value] - for value in _as_list(file_entry.get("md5")) - if value in book.md5_to_sha1 - } - if matched: - # Proven by content, the profile's own name designates - # the file whatever the collection calls it. - entry_aliases.insert(0, entry_name) - if not entry_aliases: - return - if shadowed is not None: - taken = [ - alias for alias in entry_aliases - if alias != entry_name and alias in book.named_primaries - ] - if taken: - shadowed.append((entry_name, set(matched), taken)) - held = book.holders.get(entry_name, set()) - if ( - not matched - and len(held) == 1 - and len(book.families[entry_name.casefold()]) == 1 - ): - # A name carried by several contents names none of them: - # quasi88's disk.rom aliases went to whichever - # disk.rom the scan met last, a Tandy CoCo ROM. - matched = set(held) - for sha in sorted(matched): - for alias_name in entry_aliases: - book.add(alias_name, sha) - - -def _profile_aliases( - book: _AliasBook, - shadowed: list[tuple[str, set[str], list[str]]] | None, - unreadable: list[str], -) -> None: - """Register the aliases emulator YAMLs give (aliases field on file entries).""" - emulators_dir = Path("emulators") - if not emulators_dir.is_dir(): - return - for emu_file in source_yaml_paths(emulators_dir): - try: - emu_config = source_yaml_file(emu_file) or {} - except SourceUnreadable as e: - unreadable.append(str(e)) - continue - except OSError as e: - unreadable.append(f"{emu_file}: {e}") - continue - # A profile whose entries name each other (dosbox-x opens - # MT32_CONTROL.ROM and CM32L_CONTROL.ROM alike, so each entry - # aliases the other) states that ITS slot takes either name. - # Indexed globally that became evidence for every emulator: - # ScummVM's MT-32 slot received the CM-32L ROMs. - primary_names = _primary_names(emu_config.get("files", [])) - for file_entry in emu_config.get("files", []): - _profile_entry_aliases(book, file_entry, primary_names, shadowed) - - -# Identical content named differently across platforms/cores -KNOWN_ALIAS_GROUPS = [ - # ColecoVision - all these are the same 8KB BIOS - ["colecovision.rom", "coleco.rom", "BIOS.col", "bioscv.rom"], - # Game Boy - DMG boot ROM - ["gb_bios.bin", "dmg_boot.bin", "dmg_rom.bin", "dmg0_rom.bin"], - # Game Boy Color - CGB boot ROM - ["gbc_bios.bin", "cgb_boot.bin", "cgb0_boot.bin", "cgb_agb_boot.bin"], - # Super Game Boy - ["sgb_bios.bin", "sgb_boot.bin", "sgb.boot.rom"], - ["sgb2_bios.bin", "sgb2_boot.bin", "sgb2.boot.rom"], - ["sgb1.program.rom", "SGB1.sfc/program.rom"], - ["sgb2.program.rom", "SGB2.sfc/program.rom"], - # Nintendo DS. DraStic opens nds_bios_arm9.bin, nds_bios_arm7.bin - # and nds_firmware.bin and checks their size only: the collection - # answers those names with its DS dumps. - ["NDS_Bios7.bin", "bios7.bin", "nds7.bin", "nds_bios_arm7.bin"], - ["NDS_Bios9.bin", "bios9.bin", "nds9.bin", "nds_bios_arm9.bin"], - ["NDS_Lite_Firmware.bin", "nds_firmware.bin"], - ["dsi_sd_card.bin", "nds_sd_card.bin"], - # MSX - ["MSX.ROM", "MSX.rom", "Machines/Shared Roms/MSX.rom"], - # NEC PC-98 - ["N88KNJ1.ROM", "n88knj1.rom", "quasi88/n88knj1.rom"], - # Enterprise - ["zt19uk.rom", "zt19hfnt.rom", "ep128emu/roms/zt19hfnt.rom"], - # ZX Spectrum - ["48.rom", "zx48.rom"], - # SquirrelJME - all JARs are the same - [ - "squirreljme.sqc", - "squirreljme.jar", - "squirreljme-fast.jar", - "squirreljme-slow.jar", - "squirreljme-slow-test.jar", - "squirreljme-0.3.0.jar", - "squirreljme-0.3.0-fast.jar", - "squirreljme-0.3.0-slow.jar", - "squirreljme-0.3.0-slow-test.jar", - ], - # Arcade - FBNeo spectrum - ["spectrum.zip", "fbneo/spectrum.zip", "spec48k.zip"], -] - - -def _collect_all_aliases( - files: dict, - copies: dict | None = None, - shadowed: list[tuple[str, set[str], list[str]]] | None = None, -) -> dict: - """Collect alternate filenames from platform YAMLs, core-info, and known aliases. - - Registers alternate names so generate_pack can resolve files stored under different names. - ``copies`` maps a sha1 to the other files the scan found with that content. - ``shadowed`` receives, per profile entry, its name, the contents its hashes - designate and the aliases a primary's name already carries. - """ - book = _alias_book(files, copies) - - # A source that does not parse is reported and the run refused: written - # without it, the database lost every alias the file proves and the - # command exited 0 (dosbox-x's wqy fonts answered not_found). - unreadable: list[str] = [] - _platform_aliases(book, unreadable) - - # core-info is not read here: it was the only network call of a build - # that must give the same database offline, and the one name it added - # (gearcoleco's writer.rom) is a profile entry proven by its sha1, which - # the profile pass below now registers. - - _profile_aliases(book, shadowed, unreadable) - - for group in KNOWN_ALIAS_GROUPS: - matched_sha1 = None - for name in group: - if name in book.name_to_sha1: - matched_sha1 = book.name_to_sha1[name] - break - if not matched_sha1: - continue - for name in group: - book.add(name, matched_sha1) - - if unreadable: - raise UnreadableSource(unreadable) - return book.aliases - - if __name__ == "__main__": from core.cli import run_cli diff --git a/tests/sources.py b/tests/sources.py index 5fed8a9da..b02a231b8 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -31,6 +31,10 @@ COMMANDS = { "refresh_data_dirs.py": ("packs/datadirs.py",), "split_pack.py": ("packs/parts.py",), "dedup.py": ("model/nodedup.py",), + "generate_db.py": ( + "collection/scan.py", "collection/hashcache.py", "collection/releaseassets.py", + "collection/declared.py", "collection/aliases.py", "collection/indexes.py", "collection/record.py", + ), "release_record.py": ("model/releaserecord.py", "release/record.py"), "release_notes.py": ("release/notes.py",), "check_release.py": ("release/check.py",), diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index a01e85c30..e2b1b8699 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -1940,9 +1940,9 @@ class RegionRegressions(unittest.TestCase): files[sha1] = {"path": rel, "name": "IPL.bin", "size": len(payload), "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"} - from scripts import generate_db + from collection.indexes import build_indexes - db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + db = {"files": files, "indexes": build_indexes(files, {})} by_md5 = {e["md5"]: s for s, e in files.items()} self.assertEqual( regionaudit.resolve_sha1({"name": "IPL.bin", "md5": [files[shas["bios/GC/USA/IPL.bin"]]["md5"]]}, db), @@ -3678,17 +3678,17 @@ class AnUnreadableDatabaseStopsTheScan(unittest.TestCase): def test_a_corrupt_database_is_not_an_empty_one(self): from unittest import mock - from scripts import generate_db + from collection import releaseassets with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "database.json" path.write_text("<<<<<<< HEAD\n{}\n") - with mock.patch.object(generate_db, "_load_gitignored_large_files", + with mock.patch.object(releaseassets, "load_gitignored_large_files", return_value={"bios/big.bin"}): with self.assertRaises(SystemExit): - generate_db._preserve_large_file_entries({}, str(path)) + releaseassets.preserve_large_file_entries({}, str(path)) self.assertEqual( - generate_db._preserve_large_file_entries( + releaseassets.preserve_large_file_entries( {}, str(Path(directory) / "absent.json") ), 0, @@ -3828,15 +3828,15 @@ class TheDatabaseCacheIsWrittenWhole(unittest.TestCase): import json from unittest import mock - from scripts import generate_db + from collection import hashcache with tempfile.TemporaryDirectory() as directory: path = os.path.join(directory, "cache", "db_cache.json") - generate_db.save_cache(path, {"a": 1}) + hashcache.save_cache(path, {"a": 1}) with mock.patch.object(json, "dumps", side_effect=TypeError("miscomputed")), \ self.assertRaises(TypeError): - generate_db.save_cache(path, {"a": 2}) - self.assertEqual(generate_db.load_cache(path), {"a": 1}) + hashcache.save_cache(path, {"a": 2}) + self.assertEqual(hashcache.load_cache(path), {"a": 1}) self.assertEqual(os.listdir(os.path.dirname(path)), ["db_cache.json"]) @@ -6906,13 +6906,13 @@ class AForcedRehashIsCheckedAgainstTheLastOne(unittest.TestCase): def test_a_reading_the_cache_and_a_second_reading_contradict_is_outvoted(self): from unittest import mock - from scripts import generate_db + from collection import scan cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} readings = iter([{"sha1": "b" * 40}, {"sha1": "a" * 40}]) - with mock.patch.object(generate_db, "compute_hashes", lambda *a, **k: next(readings)), \ + with mock.patch.object(scan, "compute_hashes", lambda *a, **k: next(readings)), \ contextlib.redirect_stderr(io.StringIO()) as err: - settled = generate_db._settled_hashes(Path("x.bin"), cached, 1.0, 4) + settled = scan._settled_hashes(Path("x.bin"), cached, 1.0, 4) self.assertEqual(settled["sha1"], "a" * 40) self.assertIn("WARNING", err.getvalue()) @@ -6923,22 +6923,22 @@ class AForcedRehashIsCheckedAgainstTheLastOne(unittest.TestCase): later run read it back. An unmoved file is never rewritten silently.""" from unittest import mock - from scripts import generate_db + from collection import scan cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} - with mock.patch.object(generate_db, "compute_hashes", lambda *a, **k: {"sha1": "b" * 40}), \ + with mock.patch.object(scan, "compute_hashes", lambda *a, **k: {"sha1": "b" * 40}), \ self.assertRaisesRegex(RuntimeError, "touch"): - generate_db._settled_hashes(Path("x.bin"), cached, 1.0, 4) + scan._settled_hashes(Path("x.bin"), cached, 1.0, 4) def test_a_changed_file_takes_its_new_digest(self): from unittest import mock - from scripts import generate_db + from collection import scan cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} - with mock.patch.object(generate_db, "compute_hashes", lambda *a, **k: {"sha1": "c" * 40}): + with mock.patch.object(scan, "compute_hashes", lambda *a, **k: {"sha1": "c" * 40}): self.assertEqual( - generate_db._settled_hashes(Path("x.bin"), cached, 2.0, 4)["sha1"], "c" * 40 + scan._settled_hashes(Path("x.bin"), cached, 2.0, 4)["sha1"], "c" * 40 ) diff --git a/tests/test_case_insensitive_platforms.py b/tests/test_case_insensitive_platforms.py index 8dab55f15..4eb276054 100644 --- a/tests/test_case_insensitive_platforms.py +++ b/tests/test_case_insensitive_platforms.py @@ -46,7 +46,7 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): def setUp(self): from model.platforms import _platform_config_cache from model.profiles import emulator_profiles_cache - import generate_db + from collection.indexes import build_indexes tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -61,7 +61,7 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase): "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"}} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} Path("platforms").mkdir() Path("emulators").mkdir() self.config = { diff --git a/tests/test_core_size_refusal.py b/tests/test_core_size_refusal.py index 59e022769..8c1d82b3c 100644 --- a/tests/test_core_size_refusal.py +++ b/tests/test_core_size_refusal.py @@ -23,7 +23,7 @@ import yaml from model.platforms import _platform_config_cache from model.profiles import load_emulator_profiles, emulator_profiles_cache -import generate_db +from collection.indexes import build_indexes from packs import manifest as packs_manifest from packs import platformpack from resolve.validation import core_size_refusal @@ -77,7 +77,7 @@ class _Collection(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(self.payload).hexdigest(), "sha256": hashlib.sha256(self.payload).hexdigest(), "crc32": "00000001", }} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} self.config = { "platform": "Exist", "version": "2.1", "verification_mode": "existence", "cores": ["sized", "unsized"], diff --git a/tests/test_db_aliases.py b/tests/test_db_aliases.py index 535ba3bcf..efdb58bf3 100644 --- a/tests/test_db_aliases.py +++ b/tests/test_db_aliases.py @@ -18,7 +18,9 @@ import unittest from pathlib import Path from unittest import mock -import generate_db +from collection.aliases import UnreadableSource, collect_all_aliases +from collection.scan import scan_bios_dir +from tests.sources import script_source REPO_ROOT = Path(__file__).resolve().parents[1] @@ -41,7 +43,7 @@ class AliasesNeedAnUnambiguousName(unittest.TestCase): 'files:\n - name: "disk.rom"\n aliases: ["n88sub.rom"]\n' ) with mock.patch.dict(sys.modules, {"scraper.coreinfo_scraper": stub}): - return generate_db._collect_all_aliases(files) + return collect_all_aliases(files) finally: os.chdir(previous) @@ -86,7 +88,7 @@ class AliasesNeedAnUnambiguousName(unittest.TestCase): class NoNetworkInTheBuild(unittest.TestCase): def test_generate_db_reads_no_remote_source(self): """core-info was fetched on every run, offline ones included.""" - source = (REPO_ROOT / "scripts" / "generate_db.py").read_text(encoding="utf-8") + source = script_source("generate_db.py") self.assertNotIn("coreinfo_scraper", source) self.assertNotIn("urllib.request", source) @@ -99,7 +101,7 @@ class NoNetworkInTheBuild(unittest.TestCase): Path("emulators/g.yml").write_text( 'files:\n - name: "writer.rom"\n sha1: "s1"\n' ) - aliases = generate_db._collect_all_aliases( + aliases = collect_all_aliases( {"s1": {"name": "WRITER.ROM", "path": "bios/WRITER.ROM", "md5": "m"}} ) finally: @@ -118,7 +120,7 @@ class AcceptedRevisionLists(unittest.TestCase): 'files:\n - name: "MT32_CONTROL.ROM"\n' ' sha1: ["s1", "s2", "absent"]\n' ) - aliases = generate_db._collect_all_aliases({ + aliases = collect_all_aliases({ "s1": {"name": "ctrl_1_04.rom", "path": "a", "md5": "m1"}, "s2": {"name": "ctrl_1_05.rom", "path": "b", "md5": "m2"}, }) @@ -140,7 +142,7 @@ class CrossNamingStaysInItsProfile(unittest.TestCase): ' - name: "MT32_CONTROL.ROM"\n sha1: "mt"\n aliases: ["CM32L_CONTROL.ROM"]\n' ' - name: "CM32L_CONTROL.ROM"\n sha1: "cm"\n aliases: ["MT32_CONTROL.ROM"]\n' ) - aliases = generate_db._collect_all_aliases({ + aliases = collect_all_aliases({ "mt": {"name": "mt32_control.rom", "path": "a", "md5": "m1"}, "cm": {"name": "cm32l_control.rom", "path": "b", "md5": "m2"}, }) @@ -158,7 +160,6 @@ class AnUnreadableSourceStopsTheRun(unittest.TestCase): import shutil import tempfile - import generate_db root = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, root, True) @@ -167,8 +168,8 @@ class AnUnreadableSourceStopsTheRun(unittest.TestCase): self.addCleanup(os.chdir, previous) Path("emulators").mkdir() Path("emulators/broken.yml").write_text("files: [\n - name: a\n") - with self.assertRaises(generate_db.UnreadableSource) as caught: - generate_db._collect_all_aliases({}) + with self.assertRaises(UnreadableSource) as caught: + collect_all_aliases({}) self.assertIn("broken.yml", str(caught.exception)) @@ -184,7 +185,7 @@ class DrasticNamesTheDSDumps(unittest.TestCase): os.chdir(tmp) try: Path("emulators").mkdir() - return generate_db._collect_all_aliases(files) + return collect_all_aliases(files) finally: os.chdir(previous) @@ -230,7 +231,7 @@ class AliasesFollowContentNotPrimaryCopy(unittest.TestCase): try: Path("emulators").mkdir() Path("emulators/p.yml").write_text(self.PROFILE) - return generate_db._collect_all_aliases(files, copies) + return collect_all_aliases(files, copies) finally: os.chdir(previous) @@ -259,14 +260,14 @@ class AliasesFollowContentNotPrimaryCopy(unittest.TestCase): Path("emulators/s.yml").write_text( 'files:\n - name: "BS-X.bin"\n aliases: ["BS-X.bios"]\n' ) - aliases = generate_db._collect_all_aliases(files, copies) + aliases = collect_all_aliases(files, copies) finally: os.chdir(previous) self.assertEqual(aliases, {}) def test_the_build_passes_the_scan_copies(self): - source = (REPO_ROOT / "scripts" / "generate_db.py").read_text(encoding="utf-8") - self.assertIn("_collect_all_aliases(files, aliases, shadowed)", source) + source = script_source("generate_db.py") + self.assertIn("collect_all_aliases(files, aliases, shadowed)", source) class TheSmsBiosKeepsItsNames(unittest.TestCase): @@ -291,7 +292,7 @@ class TheSmsBiosKeepsItsNames(unittest.TestCase): "systems:\n sms:\n files:\n" ' - name: "bios_U.sms"\n sha1: "v13"\n' ) - aliases = generate_db._collect_all_aliases(files) + aliases = collect_all_aliases(files) finally: os.chdir(previous) self.assertIn("bios_U.sms", {a["name"] for a in aliases.get("v13", [])}) @@ -311,7 +312,7 @@ class TheSmsBiosKeepsItsNames(unittest.TestCase): "systems:\n sms:\n files:\n" ' - name: "bios_U.sms"\n sha1: "v13"\n' ) - aliases = generate_db._collect_all_aliases(files) + aliases = collect_all_aliases(files) finally: os.chdir(previous) self.assertEqual(aliases, {}) @@ -323,7 +324,7 @@ class TheSmsBiosKeepsItsNames(unittest.TestCase): (bios / rel).parent.mkdir(parents=True, exist_ok=True) (bios / rel).write_bytes(b"v1.3") (bios / "Other/zesarux/own.rom").write_bytes(b"only zesarux") - files, copies, _cache = generate_db.scan_bios_dir(bios, {}, True) + files, copies, _cache = scan_bios_dir(bios, {}, True) paths = {entry["path"] for entry in files.values()} self.assertIn("bios/Sega/Master System/SMS_us_1.3.sms", paths) self.assertIn("bios/Other/zesarux/own.rom", paths) diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index b5f3c875f..04f2d606d 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -27,7 +27,8 @@ except ImportError: jsonschema = None from model.profiles import load_emulator_profiles, emulator_profiles_cache from resolve.directories import directory_members -import generate_db +from collection.indexes import build_indexes +from collection.scan import should_skip from packs import emulatorpack from packs import manifest as packs_manifest from packs import platformpack @@ -116,7 +117,7 @@ class DirectoryFixture(unittest.TestCase): def _db(self) -> dict: """The index generate_db builds, over files stored where the test put them.""" - indexes = generate_db.build_indexes(self.files, {}) + indexes = build_indexes(self.files, {}) stored = { sha1: {**record, "path": str(self.root / record["path"])} for sha1, record in self.files.items() @@ -393,9 +394,9 @@ class CollectionScanAndIgnoreRules(unittest.TestCase): The scan dropped every dot-directory but `.variants`, so 695 files of a collected tree could not enter the database.""" self.assertFalse( - generate_db.should_skip(Path("Game Engines/cdogs/data/.wolf3d/N3D.json")) + should_skip(Path("Game Engines/cdogs/data/.wolf3d/N3D.json")) ) - self.assertFalse(generate_db.should_skip(Path("Sony/.variants/scph.bin.1234"))) + self.assertFalse(should_skip(Path("Sony/.variants/scph.bin.1234"))) def test_hidden_files_and_tooling_directories_stay_out(self): for skipped in ( @@ -404,7 +405,7 @@ class CollectionScanAndIgnoreRules(unittest.TestCase): ".cache/large/file.bin", ".git/config", ): - self.assertTrue(generate_db.should_skip(Path(skipped)), skipped) + self.assertTrue(should_skip(Path(skipped)), skipped) def test_an_ignored_file_under_bios_is_a_registered_release_asset(self): """`.gitignore` is the register of release assets, path by path. A diff --git a/tests/test_foreign_tree.py b/tests/test_foreign_tree.py index 2f19337a2..a4f02e903 100644 --- a/tests/test_foreign_tree.py +++ b/tests/test_foreign_tree.py @@ -17,7 +17,7 @@ import tempfile import unittest from pathlib import Path -import generate_db +from collection.indexes import build_indexes from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parent.parent @@ -43,7 +43,7 @@ class ForeignTree(unittest.TestCase): "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001", } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} def tearDown(self): os.chdir(self._cwd) @@ -91,7 +91,7 @@ class AReleaseNamedAfterTheTree(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": f"{len(files) + 1:08x}"} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} def tearDown(self): os.chdir(self._cwd) diff --git a/tests/test_game_data_homonyms.py b/tests/test_game_data_homonyms.py index d6a3aa217..975ec5e91 100644 --- a/tests/test_game_data_homonyms.py +++ b/tests/test_game_data_homonyms.py @@ -105,7 +105,7 @@ class AbsentFileIsNotReplacedByAHomonym(unittest.TestCase): import hashlib import tempfile - import generate_db + from collection.indexes import build_indexes self._tmp = tempfile.TemporaryDirectory() root = Path(self._tmp.name) @@ -123,7 +123,7 @@ class AbsentFileIsNotReplacedByAHomonym(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "0", } - indexes = generate_db.build_indexes( + indexes = build_indexes( {s: {**r, "path": r["path"][len(str(root)) + 1:]} for s, r in files.items()}, {}, ) @@ -154,7 +154,7 @@ class APlatformEntryTakesNoOtherEmulatorsTree(unittest.TestCase): def setUp(self): import tempfile - import generate_db + from collection.indexes import build_indexes self._tmp = tempfile.TemporaryDirectory() self._cwd = os.getcwd() @@ -172,7 +172,7 @@ class APlatformEntryTakesNoOtherEmulatorsTree(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "0", }} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} self.registry = {"xrick": {"local_cache": "data/xrick"}} def tearDown(self): diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index da80fb234..b15eef141 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -1051,7 +1051,7 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): from model import profiles from model.platforms import _platform_config_cache from model.profiles import emulator_profiles_cache - import generate_db + from collection.indexes import build_indexes tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -1075,7 +1075,7 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase): ) registered.start() self.addCleanup(registered.stop) - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} Path("platforms").mkdir() Path("platforms/p.yml").write_text(json.dumps({ "platform": "P", "version": "2.1", "verification_mode": "existence", "cores": ["core"], @@ -1132,7 +1132,7 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): from model import profiles from model.platforms import _platform_config_cache from model.profiles import emulator_profiles_cache - import generate_db + from collection.indexes import build_indexes tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -1149,7 +1149,7 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase): "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} Path("platforms").mkdir() Path("platforms/p.yml").write_text(json.dumps({ "platform": "P", "version": "2.1", "verification_mode": "existence", @@ -1215,7 +1215,7 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): from model import profiles from model.platforms import _platform_config_cache from model.profiles import emulator_profiles_cache - import generate_db + from collection.indexes import build_indexes tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -1232,7 +1232,7 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase): "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} Path("platforms").mkdir() Path("platforms/p.yml").write_text(json.dumps({ "platform": "P", "version": "2.1", "verification_mode": "existence", diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index 7f5b56262..bb8afa150 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -347,9 +347,9 @@ class HashCacheKeepsEveryDigest(unittest.TestCase): """ def setUp(self): - import generate_db + from collection import scan - self.generate_db = generate_db + self.scan = scan self._tmp = tempfile.TemporaryDirectory() self.bios = Path(self._tmp.name) / "bios" (self.bios / "Sony" / "PS").mkdir(parents=True) @@ -359,23 +359,23 @@ class HashCacheKeepsEveryDigest(unittest.TestCase): self._tmp.cleanup() def test_cache_hit_serves_the_full_digest_set(self): - files, _, cache = self.generate_db.scan_bios_dir(self.bios, {}, force=False) + files, _, cache = self.scan.scan_bios_dir(self.bios, {}, force=False) entry = next(iter(files.values())) - self.assertTrue(set(self.generate_db.CACHED_HASHES).issubset(entry)) + self.assertTrue(set(self.scan.CACHED_HASHES).issubset(entry)) # Second pass, this time served entirely from the cache. - again, _, cache2 = self.generate_db.scan_bios_dir(self.bios, cache, force=False) + again, _, cache2 = self.scan.scan_bios_dir(self.bios, cache, force=False) entry2 = next(iter(again.values())) self.assertTrue( - set(self.generate_db.CACHED_HASHES).issubset(entry2), - f"cache hit lost {set(self.generate_db.CACHED_HASHES) - set(entry2)}", + set(self.scan.CACHED_HASHES).issubset(entry2), + f"cache hit lost {set(self.scan.CACHED_HASHES) - set(entry2)}", ) self.assertEqual( - {k: entry[k] for k in self.generate_db.CACHED_HASHES}, - {k: entry2[k] for k in self.generate_db.CACHED_HASHES}, + {k: entry[k] for k in self.scan.CACHED_HASHES}, + {k: entry2[k] for k in self.scan.CACHED_HASHES}, ) self.assertTrue( - set(self.generate_db.CACHED_HASHES).issubset(next(iter(cache2.values()))) + set(self.scan.CACHED_HASHES).issubset(next(iter(cache2.values()))) ) def test_a_warm_cache_serialises_exactly_like_a_fresh_hash(self): @@ -385,8 +385,8 @@ class HashCacheKeepsEveryDigest(unittest.TestCase): hashing, so a run with a warm cache rewrote all 7,850 entries with their digests in a different order and no content change. """ - fresh, _, cache = self.generate_db.scan_bios_dir(self.bios, {}, force=True) - warm, _, _ = self.generate_db.scan_bios_dir(self.bios, cache, force=False) + fresh, _, cache = self.scan.scan_bios_dir(self.bios, {}, force=True) + warm, _, _ = self.scan.scan_bios_dir(self.bios, cache, force=False) self.assertEqual( [list(entry) for entry in fresh.values()], [list(entry) for entry in warm.values()], @@ -396,13 +396,13 @@ class HashCacheKeepsEveryDigest(unittest.TestCase): ) def test_a_partial_cache_entry_is_rehashed_instead_of_trusted(self): - _, _, cache = self.generate_db.scan_bios_dir(self.bios, {}, force=False) + _, _, cache = self.scan.scan_bios_dir(self.bios, {}, force=False) key = next(iter(cache)) cache[key].pop("adler32") - files, _, healed = self.generate_db.scan_bios_dir(self.bios, cache, force=False) + files, _, healed = self.scan.scan_bios_dir(self.bios, cache, force=False) entry = next(iter(files.values())) - self.assertTrue(set(self.generate_db.CACHED_HASHES).issubset(entry)) - self.assertTrue(set(self.generate_db.CACHED_HASHES).issubset(healed[key])) + self.assertTrue(set(self.scan.CACHED_HASHES).issubset(entry)) + self.assertTrue(set(self.scan.CACHED_HASHES).issubset(healed[key])) class PreservedLargeFileEntries(unittest.TestCase): @@ -414,16 +414,16 @@ class PreservedLargeFileEntries(unittest.TestCase): """ def setUp(self): - import generate_db + from collection import releaseassets - self.generate_db = generate_db + self.releaseassets = releaseassets self._tmp = tempfile.TemporaryDirectory() self.tmp = Path(self._tmp.name) self._cwd = os.getcwd() os.chdir(self.tmp) (self.tmp / ".gitignore").write_text("bios/Sony/PS3/FW.PUP\n") self._real_fetch = largefiles.fetch_large_file - generate_db.__dict__.pop("fetch_large_file", None) + releaseassets.__dict__.pop("fetch_large_file", None) def tearDown(self): os.chdir(self._cwd) @@ -445,7 +445,7 @@ class PreservedLargeFileEntries(unittest.TestCase): ) # The scan found the current revision at that path. files = {"a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - count = self.generate_db._preserve_large_file_entries(files, db_path) + count = self.releaseassets.preserve_large_file_entries(files, db_path) self.assertEqual(count, 0) self.assertEqual(list(files), ["a" * 40]) @@ -455,7 +455,7 @@ class PreservedLargeFileEntries(unittest.TestCase): {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) files: dict = {} - count = self.generate_db._preserve_large_file_entries(files, db_path) + count = self.releaseassets.preserve_large_file_entries(files, db_path) self.assertEqual(count, 1) self.assertIn("b" * 40, files) @@ -469,7 +469,7 @@ class PreservedLargeFileEntries(unittest.TestCase): {sha1: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) files: dict = {} - count = self.generate_db._preserve_large_file_entries(files, db_path) + count = self.releaseassets.preserve_large_file_entries(files, db_path) self.assertEqual(count, 1) self.assertEqual(files[sha1]["path"], "bios/Sony/PS3/FW.PUP") self.assertEqual((self.tmp / "bios/Sony/PS3/FW.PUP").read_bytes(), b"firmware") @@ -483,7 +483,7 @@ class PreservedLargeFileEntries(unittest.TestCase): db_path = self._write_db( {sha1: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) - self.generate_db._preserve_large_file_entries({}, db_path) + self.releaseassets.preserve_large_file_entries({}, db_path) self.assertEqual(list((self.tmp / "bios/Sony/PS3").iterdir()), []) def test_an_interrupted_restore_leaves_no_file_behind(self): @@ -501,7 +501,7 @@ class PreservedLargeFileEntries(unittest.TestCase): with mock.patch.object(largefiles.shutil, "copy2", interrupted), \ self.assertRaises(KeyboardInterrupt): - self.generate_db._preserve_large_file_entries({}, db_path) + self.releaseassets.preserve_large_file_entries({}, db_path) directory = self.tmp / "bios/Sony/PS3" self.assertEqual(list(directory.iterdir()), []) @@ -512,7 +512,7 @@ class PreservedLargeFileEntries(unittest.TestCase): ) files: dict = {} self.assertEqual( - self.generate_db._preserve_large_file_entries(files, db_path), 0 + self.releaseassets.preserve_large_file_entries(files, db_path), 0 ) self.assertEqual(files, {}) @@ -523,7 +523,7 @@ class PreservedLargeFileEntries(unittest.TestCase): ) files = {"a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} self.assertEqual( - self.generate_db._preserve_large_file_entries(files, db_path), 0 + self.releaseassets.preserve_large_file_entries(files, db_path), 0 ) self.assertEqual(list(files), ["a" * 40]) diff --git a/tests/test_layers.py b/tests/test_layers.py index d6bac726c..2b5dd6f62 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -43,6 +43,7 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { # The launcher archives are written by the pack member writer. "installer_build": frozenset({"packs"}), "devtools": frozenset(), + "collection": frozenset(), # A job's commit subjects are checked against the repository's commit rules. "unattended": frozenset({"devtools"}), # The installer event schema is checked against the one the build writes. diff --git a/tests/test_maker_folder_names.py b/tests/test_maker_folder_names.py index 5e4e72572..5a8f5be19 100644 --- a/tests/test_maker_folder_names.py +++ b/tests/test_maker_folder_names.py @@ -33,7 +33,7 @@ from model.profiles import emulator_profiles_cache, load_emulator_profiles from model.registry import list_registered_platforms, load_data_dir_registry from resolve.localfile import resolve_local_file from resolve.ownership import BUCKET_FOLDERS, names_manufacturer -import generate_db +from collection.indexes import shadowed_alias_index from packs import manifest as packs_manifest, md5pack, naming as packs_naming, platformpack from resolve import ownership from packs.coverage import verify_platform @@ -134,7 +134,7 @@ class ShadowedAliasIndex(_Collection): shadowed = [("a.rom", set(), ["B.ROM"]), ("c.rom", {"1" * 40}, ["B.ROM"])] by_name = {"a.rom": ["2" * 40, "3" * 40], "B.ROM": ["4" * 40]} self.assertEqual( - generate_db.shadowed_alias_index(shadowed, by_name), {"B.ROM": ["1" * 40]} + shadowed_alias_index(shadowed, by_name), {"B.ROM": ["1" * 40]} ) diff --git a/tests/test_md5_pack_context.py b/tests/test_md5_pack_context.py index 4f55ee18f..3029d013e 100644 --- a/tests/test_md5_pack_context.py +++ b/tests/test_md5_pack_context.py @@ -75,7 +75,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): import yaml from model.profiles import emulator_profiles_cache - import generate_db + from collection.indexes import build_indexes from packs import emulatorpack with tempfile.TemporaryDirectory() as directory: @@ -92,7 +92,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase): "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "0", }} - db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + db = {"files": files, "indexes": build_indexes(files, {})} (root / "emulators" / "triforce.yml").write_text(yaml.dump({ "emulator": "Triforce", "type": "libretro", "cores": ["triforce"], "systems": ["sega-triforce"], diff --git a/tests/test_no_game_data.py b/tests/test_no_game_data.py index 54ecc73bd..a035b5ac7 100644 --- a/tests/test_no_game_data.py +++ b/tests/test_no_game_data.py @@ -29,7 +29,7 @@ import yaml from model.platforms import load_platform_config, _platform_config_cache from model.profiles import emulator_profiles_cache -import generate_db +from collection.indexes import build_indexes from packs import archive as packs_archive from packs import manifest as packs_manifest from packs import platformpack @@ -88,7 +88,7 @@ class _Fixture(unittest.TestCase): "md5": hashlib.md5(data).hexdigest(), "sha256": hashlib.sha256(data).hexdigest(), "crc32": "00000000", } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} self.platforms.mkdir() self.emulators.mkdir() for key, profile in PROFILES.items(): @@ -161,7 +161,7 @@ class ManifestCategory(_Fixture): def test_an_omitted_game_data_file_is_marked(self): (self.bios / "Doom" / "engine.pk3").unlink() files = {sha1: e for sha1, e in self.db["files"].items() if e["name"] != "engine.pk3"} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} manifest = self.manifest() omitted = {e["dest"]: e.get("category") for e in manifest["omitted_files"]} self.assertEqual(omitted.get("engine.pk3"), "game_data") diff --git a/tests/test_pack_core_extras.py b/tests/test_pack_core_extras.py index a1b4513cc..c91e5ed45 100644 --- a/tests/test_pack_core_extras.py +++ b/tests/test_pack_core_extras.py @@ -151,7 +151,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): def setUp(self): from model.platforms import _platform_config_cache from model.profiles import load_emulator_profiles, emulator_profiles_cache - import generate_db + from collection.indexes import build_indexes tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) previous = os.getcwd() @@ -167,7 +167,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} Path("platforms").mkdir() config = {"platform": "P", "verification_mode": "existence", "cores": ["c"], "systems": {"s": {"files": [ diff --git a/tests/test_pack_counts.py b/tests/test_pack_counts.py index 2f1084045..f21c0ea05 100644 --- a/tests/test_pack_counts.py +++ b/tests/test_pack_counts.py @@ -31,7 +31,7 @@ except ImportError: from core.artifacts import ArtifactLockBusy, artifact_lock from model.platforms import _platform_config_cache from model.profiles import emulator_profiles_cache, load_emulator_profiles -import generate_db +from collection.indexes import build_indexes from packs import archive as packs_archive from packs import datatrees from packs import manifest as packs_manifest @@ -101,7 +101,7 @@ class PackCountFixture(unittest.TestCase): "sha256": hashlib.sha256(payload).hexdigest(), "crc32": f"{len(payload):08x}", } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} for name, payload in (("a.txt", b"one"), ("sub/b.txt", b"three"), ("c.txt", b"")): (self.data / name).parent.mkdir(parents=True, exist_ok=True) (self.data / name).write_bytes(payload) @@ -252,7 +252,7 @@ class ManifestFollowsTheBuilder(PackCountFixture): "sha1": sha1, "md5": hashlib.md5(raw).hexdigest(), "sha256": hashlib.sha256(raw).hexdigest(), "crc32": "00000000", } - self.db["indexes"] = generate_db.build_indexes(self.db["files"], {}) + self.db["indexes"] = build_indexes(self.db["files"], {}) self._platform([{ "name": "set.zip", "destination": "set.zip", "md5": hashlib.md5(rom).hexdigest(), "zipped_file": "basic.rom", @@ -548,7 +548,7 @@ class RefusedFilesAreNotPresent(unittest.TestCase): import os from model.platforms import _platform_config_cache - import generate_db + from collection.indexes import build_indexes from sitegen import readme as sitegen_readme with tempfile.TemporaryDirectory() as tmp: @@ -567,7 +567,7 @@ class RefusedFilesAreNotPresent(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001", } - db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + db = {"files": files, "indexes": build_indexes(files, {})} config = { "platform": "Hashy", "version": "2.1", "verification_mode": "md5", "base_destination": "bios", "systems": {"sys": {"files": [ diff --git a/tests/test_path_conflict_status.py b/tests/test_path_conflict_status.py index 808365ec8..23802ddb0 100644 --- a/tests/test_path_conflict_status.py +++ b/tests/test_path_conflict_status.py @@ -22,7 +22,7 @@ import yaml from model.platforms import load_platform_config, _platform_config_cache from model.profiles import emulator_profiles_cache -import generate_db +from collection.indexes import build_indexes from packs import emulatorpack from packs import platformpack from packs.coverage import verify_platform @@ -50,7 +50,7 @@ class ConflictingDeclarations(unittest.TestCase): "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001", } } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} platform = { "platform": "Conflict", "verification_mode": "existence", @@ -123,7 +123,7 @@ class AnExtraDoesNotPassAHashCheck(unittest.TestCase): "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000002", } } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} platform = { "platform": "Hashed", "verification_mode": "md5", @@ -190,7 +190,7 @@ class TheEmulatorPackShipsWhatTheCoreAccepts(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000003", }} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} profile = { "emulator": "Mac", "type": "libretro", "cores": ["mac"], "systems": ["apple-macintosh"], @@ -247,7 +247,7 @@ class AlternativesAgreeWithThePack(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000004", }} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} profile = { "emulator": "Eng", "type": "libretro", "cores": ["eng"], "systems": ["x"], "files": [ @@ -307,7 +307,7 @@ class AMaskedArchiveIsMissing(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "0"} self.sha1_b = sha1 - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} self.emulators.mkdir() a_sha1 = next(k for k in files if k != sha1) (self.emulators / "a.yml").write_text(yaml.dump({ diff --git a/tests/test_path_suffix.py b/tests/test_path_suffix.py index 861d90ce4..cc2c0147f 100644 --- a/tests/test_path_suffix.py +++ b/tests/test_path_suffix.py @@ -11,7 +11,7 @@ import unittest from pathlib import Path from resolve.localfile import resolve_local_file -from generate_db import _path_suffixes +from collection.indexes import _path_suffixes class TestPathSuffixes(unittest.TestCase): diff --git a/tests/test_proven_name.py b/tests/test_proven_name.py index 4e8318c97..72cdc363f 100644 --- a/tests/test_proven_name.py +++ b/tests/test_proven_name.py @@ -21,7 +21,7 @@ import unittest import zlib from pathlib import Path -import generate_db +from collection.indexes import build_indexes, proven_name_index from resolve.localfile import resolve_local_file REPO_ROOT = Path(__file__).resolve().parents[1] @@ -49,10 +49,10 @@ class ProvenNameIndex(unittest.TestCase): hashlib.sha1(RETAIL).hexdigest(): record("bios/N/DSi/biosdsi7.bin", RETAIL), hashlib.sha1(OTHER).hexdigest(): record("bios/X/Y/other.bin", OTHER), } - self.indexes = generate_db.build_indexes(self.files, {}) + self.indexes = build_indexes(self.files, {}) def index(self, declarations: list[dict]) -> dict: - return generate_db.proven_name_index(self.files, self.indexes, declarations) + return proven_name_index(self.files, self.indexes, declarations) def test_name_points_at_the_proven_dump_beside_it(self): declared = [{"name": "dsi_bios7.bin", "md5": hashlib.md5(RETAIL).hexdigest()}] @@ -95,13 +95,13 @@ class HashlessEntryTakesTheProvenDump(unittest.TestCase): hashlib.sha1(DEVKIT).hexdigest(): record("bios/N/DSi/dsi_bios7.bin", DEVKIT), hashlib.sha1(RETAIL).hexdigest(): record("bios/N/DSi/biosdsi7.bin", RETAIL), } - indexes = generate_db.build_indexes(files, {}) + indexes = build_indexes(files, {}) db = {"files": files, "indexes": indexes} entry = {"name": "dsi_bios7.bin", "size": 64} self.assertEqual( resolve_local_file(entry, db)[0], "bios/N/DSi/dsi_bios7.bin" ) - indexes["by_proven_name"] = generate_db.proven_name_index( + indexes["by_proven_name"] = proven_name_index( files, indexes, [{"name": "dsi_bios7.bin", "md5": hashlib.md5(RETAIL).hexdigest()}], ) diff --git a/tests/test_required_only_twins.py b/tests/test_required_only_twins.py index b1cd816f8..3da7b212a 100644 --- a/tests/test_required_only_twins.py +++ b/tests/test_required_only_twins.py @@ -23,7 +23,7 @@ import yaml from model.platforms import _platform_config_cache from model.profiles import emulator_profiles_cache -import generate_db +from collection.indexes import build_indexes from packs import manifest as packs_manifest from packs import platformpack @@ -48,7 +48,7 @@ class RequiredTwins(unittest.TestCase): "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000008", } } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} platform = { "platform": "Twins", "version": "2.1", diff --git a/tests/test_retired_files.py b/tests/test_retired_files.py index f67826116..0d729d723 100644 --- a/tests/test_retired_files.py +++ b/tests/test_retired_files.py @@ -16,6 +16,7 @@ import unittest from pathlib import Path from model import retired as model_retired +from tests.sources import script_source REPO_ROOT = Path(__file__).resolve().parents[1] @@ -62,7 +63,7 @@ class WhatLeftIsRecorded(unittest.TestCase): 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") + source = script_source("generate_db.py") self.assertIn("retired.update(", source) diff --git a/tests/test_slots.py b/tests/test_slots.py index 1145041f0..028ea269c 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -605,11 +605,11 @@ class TestSelfContradictingDestinations(unittest.TestCase): ) def test_the_database_and_the_arbiter_read_one_rule(self): - import generate_db + from collection import scan variant = Path("bios/M/C/.variants/aes.zip") - self.assertEqual(generate_db._canonical_name(variant), "aes.zip") - for module in ("resolve/collisions.py", "generate_db.py"): + self.assertEqual(scan._canonical_name(variant), "aes.zip") + for module in ("resolve/collisions.py", "collection/scan.py"): source = (Path(__file__).resolve().parents[1] / "scripts" / module).read_text() with self.subTest(module=module): self.assertIn("variant_base_name(", source) diff --git a/tests/test_twin_declaration_status.py b/tests/test_twin_declaration_status.py index 70ced4db2..232465f80 100644 --- a/tests/test_twin_declaration_status.py +++ b/tests/test_twin_declaration_status.py @@ -22,7 +22,7 @@ from pathlib import Path import yaml from model.platforms import _platform_config_cache -import generate_db +from collection.indexes import build_indexes from packs import archive from packs import platformpack from packs.verdicts import Status @@ -47,7 +47,7 @@ class TwinDeclarationStatus(unittest.TestCase): "sha1": SHA1, "md5": hashlib.md5(PAYLOAD).hexdigest(), "sha256": hashlib.sha256(PAYLOAD).hexdigest(), "crc32": "00000001", }} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} Path("platforms/_registry.yml").write_text( yaml.dump({"platforms": {"twin": {"config": "twin.yml"}}}) ) diff --git a/tests/test_twin_declarations.py b/tests/test_twin_declarations.py index fac6b2a68..bf0fdfcdf 100644 --- a/tests/test_twin_declarations.py +++ b/tests/test_twin_declarations.py @@ -18,7 +18,7 @@ import unittest from pathlib import Path from model.profiles import emulator_profiles_cache -import generate_db +from collection.indexes import build_indexes from packs.coverage import verify_platform @@ -42,7 +42,7 @@ class TwinDeclarations(unittest.TestCase): "md5": self.md5[rel], "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001", } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} self.emulators = Path(self._tmp.name) / "emulators" self.emulators.mkdir() emulator_profiles_cache.clear() diff --git a/tests/test_unplaced_extras.py b/tests/test_unplaced_extras.py index 47e630f82..3cda02285 100644 --- a/tests/test_unplaced_extras.py +++ b/tests/test_unplaced_extras.py @@ -20,7 +20,7 @@ import yaml from model.platforms import _platform_config_cache, load_platform_config from model.profiles import load_emulator_profiles, emulator_profiles_cache -import generate_db +from collection.indexes import build_indexes from packs import manifest as packs_manifest from packs.extras import platform_region_groups from packs.coverage import verify_platform @@ -56,7 +56,7 @@ class SlugPlatform(unittest.TestCase): "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001", } - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} self.config = { "platform": "Slugs", "version": "2.1", @@ -133,7 +133,7 @@ class RegionKeysForEveryClaimant(unittest.TestCase): files = {sha1: {"path": "bios/jp.bin", "name": "jp.bin", "size": 2, "sha1": sha1, "md5": hashlib.md5(b"jp").hexdigest(), "sha256": hashlib.sha256(b"jp").hexdigest(), "crc32": "00000001"}} - db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + db = {"files": files, "indexes": build_indexes(files, {})} for name, extra in (("one", " system: sys\n"), ("two", "")): Path(f"emulators/{name}.yml").write_text( f"emulator: {name}\ntype: libretro\nsystems: [sys]\ncores: [{name}]\n" @@ -178,7 +178,7 @@ class FlatFirmwareFolder(unittest.TestCase): "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001", } - db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + db = {"files": files, "indexes": build_indexes(files, {})} config = { "platform": "Flat", "version": "2.1", "verification_mode": "md5", "base_destination": "bios", "cores": ["psx"], @@ -264,7 +264,7 @@ class UserProvidedIsNeverTakenFromTheCollection(unittest.TestCase): files = {sha1: {"path": "bios/Sony/scph5501.bin", "name": "scph5501.bin", "size": 3, "sha1": sha1, "md5": hashlib.md5(b"psx").hexdigest(), "sha256": hashlib.sha256(b"psx").hexdigest(), "crc32": "00000001"}} - db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + db = {"files": files, "indexes": build_indexes(files, {})} Path("emulators/fake.yml").write_text( "emulator: Fake\ntype: libretro\nsystems: [psx]\ncores: [fake]\n" "files:\n - name: scph5501.bin\n storage: user_provided\n" @@ -294,7 +294,7 @@ class OnePathCountsOnce(unittest.TestCase): files = {sha1: {"path": "bios/Commodore/rom.key", "name": "rom.key", "size": 3, "sha1": sha1, "md5": hashlib.md5(b"key").hexdigest(), "sha256": hashlib.sha256(b"key").hexdigest(), "crc32": "00000001"}} - db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + db = {"files": files, "indexes": build_indexes(files, {})} for core, region in (("one", ""), ("two", " region: [world]\n")): Path(f"emulators/{core}.yml").write_text( f"emulator: {core}\ntype: libretro\nsystems: [amiga]\ncores: [{core}]\n" diff --git a/tests/test_verify_data_dir_notice.py b/tests/test_verify_data_dir_notice.py index a200b6ed9..e041abd4b 100644 --- a/tests/test_verify_data_dir_notice.py +++ b/tests/test_verify_data_dir_notice.py @@ -18,7 +18,7 @@ import tempfile import unittest from pathlib import Path -import generate_db +from collection.indexes import build_indexes from packs.report import print_platform_result from packs.coverage import verify_platform @@ -32,7 +32,7 @@ class UncachedDataDirectoryNotice(unittest.TestCase): os.chdir(self._tmp.name) Path("emulators").mkdir() Path("data/present").mkdir(parents=True) - self.db = {"files": {}, "indexes": generate_db.build_indexes({}, {})} + self.db = {"files": {}, "indexes": build_indexes({}, {})} self.config = { "platform": "Tree", "verification_mode": "md5", "systems": {"msx": {"files": [{ diff --git a/tests/test_verify_release_asset.py b/tests/test_verify_release_asset.py index 687d4a27c..bd9bf37ff 100644 --- a/tests/test_verify_release_asset.py +++ b/tests/test_verify_release_asset.py @@ -26,7 +26,7 @@ import yaml from model.platforms import _platform_config_cache from tests.sources import script_source from model.profiles import emulator_profiles_cache -import generate_db +from collection.indexes import build_indexes from packs import archive from packs import emulatorpack from packs import platformpack @@ -57,7 +57,7 @@ class ReleaseAssetNotCached(unittest.TestCase): "sha1": SHA1, "md5": hashlib.md5(PAYLOAD).hexdigest(), "sha256": hashlib.sha256(PAYLOAD).hexdigest(), "crc32": "00000001", }} - self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})} + self.db = {"files": files, "indexes": build_indexes(files, {})} self.config = { "platform": "Big", "verification_mode": self.mode, "systems": {"sys": {"files": [{ diff --git a/wiki/architecture.md b/wiki/architecture.md index be973af82..1fa5b2d60 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -40,6 +40,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c resolve/ from declarations to files: content checks, resolution, layouts, cores, truth packs/ pack building and verification: selection, archives, manifests, coverage profiling/ emulator profiles confronted with their upstream source (profile_sync.py) + collection/ the scan of bios/ into database.json: digests, aliases, indexes romrecipes/ romset identification, rebuilt pinned archives, each archive's recipe acquire/ catalog coverage and the searches for a missing file scraper/ upstream scrapers (libretro, batocera, recalbox...)