diff --git a/scripts/collection/hashcache.py b/scripts/collection/hashcache.py index 47c64db1e..6d5920384 100644 --- a/scripts/collection/hashcache.py +++ b/scripts/collection/hashcache.py @@ -4,11 +4,19 @@ from __future__ import annotations import json import os +from pathlib import Path from core.artifacts import write_text_atomic -CACHE_DIR = ".cache" -CACHE_FILE = os.path.join(CACHE_DIR, "db_cache.json") + +def cache_path(bios_dir: Path) -> str: + """The cache of the tree holding bios_dir, beside it as its keys are relative to it. + + A path fixed on the working directory let a scan of a copy (tmp/wt/bios) + replace the repository's cache with the copy's entries, keyed bios/... + like the real ones, and the next real run rehashed every file. + """ + return str(bios_dir.parent / ".cache" / "db_cache.json") def load_cache(cache_path: str) -> dict: diff --git a/scripts/collection/releaseassets.py b/scripts/collection/releaseassets.py index 109a96e2f..c63daa74c 100644 --- a/scripts/collection/releaseassets.py +++ b/scripts/collection/releaseassets.py @@ -59,8 +59,10 @@ def surviving_entries(existing_db: dict, files: dict, registered: set[str]) -> d } -def restore_release_assets(entries: dict, registered: set[str], *, offline: bool) -> None: - """Write each kept entry's asset back to its registered path, fetched only when online.""" +def restore_release_assets( + entries: dict, registered: set[str], tree: Path, *, offline: bool +) -> None: + """Write each kept entry's asset back to its registered path under tree, fetched only when online.""" from model.largefiles import fetch_large_file, restore_verified for sha1, entry in entries.items(): @@ -72,5 +74,6 @@ def restore_release_assets(entries: dict, registered: set[str], *, offline: bool offline=offline, registered=registered, ) - if cached and not os.path.exists(path): - restore_verified(cached, path, sha1) + destination = str(tree / path) + if cached and not os.path.exists(destination): + restore_verified(cached, destination, sha1) diff --git a/scripts/collection/run.py b/scripts/collection/run.py index adb2a4729..b9caf15f5 100644 --- a/scripts/collection/run.py +++ b/scripts/collection/run.py @@ -8,7 +8,7 @@ from pathlib import Path from collection.aliases import add_declared_aliases from collection.declared import UnreadableSource, read_declarations -from collection.hashcache import CACHE_FILE, load_cache, save_cache +from collection.hashcache import cache_path, load_cache, save_cache from collection.indexes import database_indexes from collection.record import database_record, record_retired, write_database from collection.releaseassets import ( @@ -22,21 +22,20 @@ from collection.scan import scan_bios_dir from model import retired from model.dumpcatalog import annotate_provenance, load_provenance_snapshots -# Database entries name paths relative to the working directory, and so does -# the registry of release assets beside them. -GITIGNORE = Path(".gitignore") +def preserve_release_assets(files: dict, db_path: str, tree: Path, *, offline: bool) -> int: + """Keep the entries of release assets the scan missed, their files restored, and count them. - -def preserve_release_assets(files: dict, db_path: str, *, offline: bool) -> int: - """Keep the entries of release assets the scan missed, their files restored, and count them.""" - registered = load_gitignored_large_files(GITIGNORE) + Database entries name paths relative to the tree holding bios/, and so + does the registry of release assets in that tree's .gitignore. + """ + registered = load_gitignored_large_files(tree / ".gitignore") if not registered: return 0 existing_db = read_database(db_path) if existing_db is None: return 0 kept = surviving_entries(existing_db, files, registered) - restore_release_assets(kept, registered, offline=offline) + restore_release_assets(kept, registered, tree, offline=offline) files.update(kept) return len(kept) @@ -44,10 +43,11 @@ def preserve_release_assets(files: dict, db_path: str, *, offline: bool) -> int: def generate(args: argparse.Namespace) -> int: """Scan bios/ and write the database, 1 when a declared source or the old database cannot be read.""" bios_dir = Path(args.bios_dir) + cache_file = cache_path(bios_dir) # A forced run rehashes every file but keeps the previous digests to # check the new ones against. - cache = load_cache(CACHE_FILE) + cache = load_cache(cache_file) print(f"Scanning {bios_dir}/ ...") files, aliases, new_cache = scan_bios_dir(bios_dir, cache, args.force) @@ -57,7 +57,9 @@ def generate(args: argparse.Namespace) -> int: # Preserve entries for large files stored as release assets (.gitignore) try: - preserved = preserve_release_assets(files, args.output, offline=args.offline) + preserved = preserve_release_assets( + files, args.output, bios_dir.parent, offline=args.offline + ) except DatabaseUnreadable as exc: print(exc, file=sys.stderr) return 1 @@ -89,7 +91,7 @@ def generate(args: argparse.Namespace) -> int: written = write_database(args.output, database) - save_cache(CACHE_FILE, new_cache) + save_cache(cache_file, new_cache) alias_count = sum(len(v) for v in aliases.values()) name_count = len(indexes["by_name"]) diff --git a/scripts/generate_db.py b/scripts/generate_db.py index 72061ac0f..ed1b1b220 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -4,7 +4,8 @@ Usage: python scripts/generate_db.py [--force] [--bios-dir DIR] [--output FILE] -Supports incremental mode via .cache/db_cache.json (mtime-based). +Supports incremental mode via .cache/db_cache.json beside the scanned +tree (mtime-based). Use --force to rehash all files. """ diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 3a4509c01..4ef3486b1 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -3736,15 +3736,44 @@ class AnUnreadableDatabaseStopsTheScan(unittest.TestCase): err = io.StringIO() with mock.patch.object(run, "load_gitignored_large_files", return_value={"bios/big.bin"}), \ - mock.patch.object(run, "load_cache", return_value={}), \ - mock.patch.object(run, "save_cache") as saved, \ redirect_stdout(io.StringIO()), redirect_stderr(err): self.assertEqual(run.generate(args), 1) self.assertIn("is not valid JSON", err.getvalue()) - saved.assert_not_called() + self.assertFalse((root / ".cache").exists()) self.assertTrue(output.read_text().startswith("<<<<<<<")) +class TheDigestCacheBelongsToTheScannedTree(unittest.TestCase): + """The cache path was fixed on the working directory: scanning a copy + (tmp/wt/bios) replaced the repository's cache with the copy's entries, + keyed bios/... like the real ones, and the next run rehashed everything.""" + + def test_a_scan_writes_its_cache_beside_its_tree(self): + import argparse + import io + from contextlib import redirect_stderr, redirect_stdout + + from collection import hashcache, run + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "bios" / "Sony").mkdir(parents=True) + (root / "bios" / "Sony" / "a.bin").write_bytes(b"a") + (root / "_registry.yml").write_text("platforms: {}\n") + args = argparse.Namespace( + bios_dir=str(root / "bios"), force=False, + output=str(root / "database.json"), offline=True, + platforms_dir=str(root), emulators_dir=str(root), + provenance_dir=str(root), + ) + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(run.generate(args), 0) + cache = root / ".cache" / "db_cache.json" + self.assertEqual(hashcache.cache_path(root / "bios"), str(cache)) + self.assertEqual(list(hashcache.load_cache(str(cache))), ["bios/Sony/a.bin"]) + self.assertEqual(hashcache.cache_path(Path("bios")), ".cache/db_cache.json") + + class TheZipIndexCacheKnowsItsInputs(unittest.TestCase): """build_zip_contents_index cached on (path, mtime) alone: a smaller max_entry_size, or a database giving the same archive another sha1, diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index 63d70c225..7bcdf3251 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -492,9 +492,12 @@ class RestoredReleaseAssets(unittest.TestCase): self._tmp.cleanup() def _restore(self, *, offline: bool = False) -> None: - entries = {self.sha1: {"name": "FW.PUP", "path": str(self.target)}} + # Entries name paths relative to the tree holding bios/, never to + # the working directory. + path = "bios/Sony/PS3/FW.PUP" + entries = {self.sha1: {"name": "FW.PUP", "path": path}} self.releaseassets.restore_release_assets( - entries, {str(self.target)}, offline=offline + entries, {path}, self.tmp, offline=offline ) def test_a_fetched_asset_returns_to_its_registered_path(self):