diff --git a/scripts/model/database.py b/scripts/model/database.py index e1c00e6a6..d7307cdc4 100644 --- a/scripts/model/database.py +++ b/scripts/model/database.py @@ -48,6 +48,42 @@ def load_database(db_path: str) -> dict: ) from None +# One slot: the files dict, its size, and path -> (sha1, record) built from it. +_PATH_INDEX: list[tuple[dict, int, dict[str, tuple[str, dict]]]] = [] + + +def _path_index(db: dict) -> dict[str, tuple[str, dict]]: + """Normalized path -> (sha1, record), built once per database.""" + files = db.get("files", {}) + if _PATH_INDEX: + cached, size, index = _PATH_INDEX[0] + if cached is files and size == len(files): + return index + index = { + os.path.normpath(record["path"]): (sha1, record) + for sha1, record in files.items() + if record.get("path") + } + _PATH_INDEX[:] = [(files, len(files), index)] + return index + + +def record_at(db: dict, path: str | None) -> dict | None: + """The database record stored at a path, spelled any way normpath reads alike.""" + if not path: + return None + found = _path_index(db).get(os.path.normpath(path)) + return found[1] if found else None + + +def sha1_at(db: dict, path: str | None) -> str | None: + """The sha1 the database keys the file at a path under.""" + if not path: + return None + found = _path_index(db).get(os.path.normpath(path)) + return found[0] if found else None + + _mame_clone_map_cache: dict[str, dict[str, str]] = {} diff --git a/scripts/packs/emulatorcheck.py b/scripts/packs/emulatorcheck.py index 66fe538a6..240ce8fe1 100644 --- a/scripts/packs/emulatorcheck.py +++ b/scripts/packs/emulatorcheck.py @@ -11,6 +11,7 @@ from core.hashing import compute_hashes from core.paths import BIOS_DIR, REPO_ROOT from core.ziptools import build_zip_contents_index from model.alternatives import set_requirements, settle_sets, slot_set_keys +from model.database import sha1_at from model.profiles import ( ProfileSelectionError, entry_serves_systems, @@ -207,7 +208,6 @@ class _EmulatorPack: # The emulator pack walks profiles in name order and keeps the first # file at a path, folding case: a later profile's different file there # (zesarux pentagon.rom after speccy's PENTAGON.ROM) is not in the pack. - sha1_by_path: dict = field(init=False) # Destination -> (file packed there, its profile, the path as written). # Archives and data trees take paths too, before and after the loose # files of their profile, as the pack writes them. @@ -215,11 +215,6 @@ class _EmulatorPack: taken: Placed = field(default_factory=lambda: Placed(True)) content_ids: dict[str, str | None] = field(default_factory=dict) - def __post_init__(self) -> None: - self.sha1_by_path = { - entry.get("path"): sha1 for sha1, entry in self.db.get("files", {}).items() - } - def pending(self, entry: dict, local_path: str | None, status: str) -> tuple[str | None, str]: from resolve.packfiles import pending_release_asset, run_is_offline @@ -236,7 +231,7 @@ class _EmulatorPack: if not path: return None if path not in self.content_ids: - self.content_ids[path] = self.sha1_by_path.get(path) or ( + self.content_ids[path] = sha1_at(self.db, path) or ( compute_hashes(path)["sha1"] if os.path.isfile(path) else None ) return self.content_ids[path] diff --git a/scripts/packs/extras.py b/scripts/packs/extras.py index 82eb40559..e02a0513c 100644 --- a/scripts/packs/extras.py +++ b/scripts/packs/extras.py @@ -11,6 +11,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict from core.options import reject_unknown +from model.database import sha1_at from model.profiles import PROFILE_IDENTITY_FIELDS, entry_system_ids, lists_files from model.systems import norm_system_id from model.alternatives import core_file_spares, required_only_spares, set_fields @@ -415,13 +416,10 @@ def hidden_extras( system_ids = options.get("system_ids") include_all = options.get("include_all", False) required_only = options.get("required_only", False) - sha1_by_path = { - entry.get("path"): sha1 for sha1, entry in db.get("files", {}).items() - } base_dest = config.get("base_destination", "") taken = Placed(bool(config.get("case_insensitive_fs", False)), content={}) for dest, local in shipped.items(): - taken.take(dest, sha1_by_path.get(local)) + taken.take(dest, sha1_at(db, local)) prefix = detect_extras_prefix(config, base_dest) region_prefix = declared_root(config) hidden: dict[tuple[str, str, str], str] = {} @@ -459,7 +457,7 @@ def hidden_extras( local, _status = resolve_local_file( fe, db, dest_hint=fe.get("destination", "") ) - held = (sha1_by_path.get(local) or _file_sha1(local)) if local else None + held = (sha1_at(db, local) or _file_sha1(local)) if local else None if reason == "case_twin" and held and taken.content_at(full) == held: continue key = ( diff --git a/scripts/packs/manifestentry.py b/scripts/packs/manifestentry.py index 104f3f51c..6a8c66032 100644 --- a/scripts/packs/manifestentry.py +++ b/scripts/packs/manifestentry.py @@ -9,6 +9,7 @@ from dataclasses import dataclass from core.hashing import compute_hashes from core.paths import declared_destination +from model.database import sha1_at from model.declarations import OUTER_ROOTS, declared_root from model.largefiles import asset_name, load_registered_paths, published_asset_name from packs.extras import ( @@ -68,23 +69,6 @@ def _get_repo_path(sha1: str, db: dict) -> str: return entry.get("path", "") -# The database the index was built from, held so its identity stays its own. -_DB_SHA1_BY_PATH: list[tuple[dict, dict[str, str]]] = [] - - -def _db_sha1_by_path(db: dict) -> dict[str, str]: - """Path -> sha1 of the database, built once per database.""" - if _DB_SHA1_BY_PATH and _DB_SHA1_BY_PATH[0][0] is db: - return _DB_SHA1_BY_PATH[0][1] - index = { - os.path.normpath(entry["path"]): sha1 - for sha1, entry in db.get("files", {}).items() - if entry.get("path") - } - _DB_SHA1_BY_PATH[:] = [(db, index)] - return index - - # The hashes a manifest entry records, and each file's once verified. _MANIFEST_HASHES = frozenset({"sha1", "sha256"}) _STABLE_HASHES: dict[tuple, dict] = {} @@ -100,7 +84,7 @@ def _stable_hashes(local_path: str, db: dict) -> dict: refused rather than published. """ stat = os.stat(local_path) - expected = _db_sha1_by_path(db).get(os.path.normpath(local_path)) + expected = sha1_at(db, local_path) # Keyed by what was checked, the sha1 this database expects there, never # by id(db): a database freed and replaced at the same address answered # with hashes verified against the first one. diff --git a/scripts/resolve/collisions.py b/scripts/resolve/collisions.py index 885131ce1..466358e75 100644 --- a/scripts/resolve/collisions.py +++ b/scripts/resolve/collisions.py @@ -10,7 +10,8 @@ from core.hashing import compute_hashes, parse_hash_list, parse_md5_list from core.paths import comparable_destination from core.ziptools import check_inside_zip from resolve.localfile import resolve_local_file, variant_base_name -from resolve.packfiles import records_by_path, preferred_entries +from model.database import record_at +from resolve.packfiles import preferred_entries @dataclass @@ -124,7 +125,7 @@ def _record_at(path: str, db: dict) -> dict | None: path verify --all and slots.py both take. The index is the pack resolver's, so one run holds one copy of it. """ - return records_by_path(db).get(path) + return record_at(db, path) def content_sha1(path: str, db: dict) -> str | None: diff --git a/scripts/resolve/launchers.py b/scripts/resolve/launchers.py index cc9533f53..e3f6678bb 100644 --- a/scripts/resolve/launchers.py +++ b/scripts/resolve/launchers.py @@ -21,6 +21,7 @@ from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass from core.hashing import parse_hash_list +from model.database import record_at from model.declarations import CONFIGS_ROOT, ROMS_ROOT, declared_root, outer_layout from model.profiles import lists_files from resolve.content import name_match_size_ok @@ -1239,10 +1240,7 @@ def held_record(report: dict, db: dict) -> dict | None: local, status = resolve_local_file(report, db, dest_hint=report.get("path") or "") if local is None or status in ("not_found", "hash_mismatch"): return None - for record in db.get("files", {}).values(): - if record.get("path") == local: - return record - return None + return record_at(db, local) def declared_destinations(config: dict) -> set[str]: diff --git a/scripts/resolve/packfiles.py b/scripts/resolve/packfiles.py index 55b025814..3deab05e6 100644 --- a/scripts/resolve/packfiles.py +++ b/scripts/resolve/packfiles.py @@ -13,6 +13,7 @@ import urllib.error import urllib.request from pathlib import Path +from model.database import record_at from model.largefiles import fetch_large_file from core.hashing import cut_md5_owner, parse_hash_list from resolve.content import declared_hash_verdict @@ -135,21 +136,6 @@ def run_is_offline(offline: bool | None = None) -> bool: ) -_RECORDS_BY_PATH: list[tuple[dict, int, dict[str, dict]]] = [] - - -def records_by_path(db: dict) -> dict[str, dict]: - """The database records by path, built once per database.""" - files = db.get("files", {}) - if _RECORDS_BY_PATH: - cached, size, index = _RECORDS_BY_PATH[0] - if cached is files and size == len(files): - return index - index = {record.get("path"): record for record in files.values()} - _RECORDS_BY_PATH[:] = [(files, len(files), index)] - return index - - def pending_release_asset( file_entry: dict, db: dict, registered: list[str] | None = None, ) -> str | None: @@ -175,10 +161,9 @@ def pending_release_asset( assets = set(asset_candidates(name, registered)) if not assets: return None - records = records_by_path(db) declared_size = file_entry.get("size") for path, asset in sorted(asset_names(registered).items()): - record = records.get(path) + record = record_at(db, path) if asset not in assets or record is None: continue if isinstance(declared_size, int) and record.get("size") != declared_size: diff --git a/scripts/resolve/regionaudit.py b/scripts/resolve/regionaudit.py index 20cd2c2db..68ea48828 100644 --- a/scripts/resolve/regionaudit.py +++ b/scripts/resolve/regionaudit.py @@ -9,6 +9,7 @@ import collections import re from model import region +from model.database import sha1_at from model.region import NOINTRO from model.profiles import lists_files from resolve.localfile import resolve_local_file @@ -42,21 +43,19 @@ def catalog_regions(db: dict) -> dict[str, tuple[set[str], str]]: return out -def resolve_sha1(file_entry: dict, db: dict, by_path: dict | None = None) -> str | None: +def resolve_sha1(file_entry: dict, db: dict) -> str | None: """The repo SHA1 a profile entry resolves to, by the pack's own resolver. A private resolver read sha1, then md5, then a lone name: entries that identify their file by path (Dolphin's three IPL.bin), by crc32 (geargrafx) or by sha256 (mednafen) were never checked at all. """ - if by_path is None: - by_path = {entry.get("path", ""): sha1 for sha1, entry in db["files"].items()} path, status = resolve_local_file( file_entry, db, dest_hint=file_entry.get("path") or "" ) if not path or status in ("not_found", "hash_mismatch"): return None - return by_path.get(path) + return sha1_at(db, path) def build_report(profiles: dict, db: dict) -> dict: @@ -69,7 +68,6 @@ def build_report(profiles: dict, db: dict) -> dict: for slugs, _name in catalog.values(): vocabulary.update(slugs) - by_path = {entry.get("path", ""): sha1 for sha1, entry in db["files"].items()} for emu_name, profile in sorted(profiles.items()): if not lists_files(profile): continue @@ -77,7 +75,7 @@ def build_report(profiles: dict, db: dict) -> dict: if not isinstance(f, dict) or not f.get("region"): continue declared = region.normalize_declared(f["region"]) - sha1 = resolve_sha1(dict(f, source_profile=emu_name), db, by_path) + sha1 = resolve_sha1(dict(f, source_profile=emu_name), db) if not sha1 or sha1 not in catalog: unchecked += 1 continue diff --git a/tests/test_manifest_entry.py b/tests/test_manifest_entry.py index 9392cbcb0..adc0caf9f 100644 --- a/tests/test_manifest_entry.py +++ b/tests/test_manifest_entry.py @@ -78,7 +78,7 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase): def test_a_copy_the_database_lacks_is_omitted(self): """A copy the scan never indexed has no repo path: an omission.""" - with mock.patch.object(manifestentry, "_db_sha1_by_path", return_value={}): + with mock.patch.object(manifestentry, "sha1_at", return_value=None): files, omitted, pack_only = self._run_core_entries( {"sha1": "0" * 40, "sha256": "0" * 64} )