diff --git a/scripts/collection/releaseassets.py b/scripts/collection/releaseassets.py index 89ee55250..109a96e2f 100644 --- a/scripts/collection/releaseassets.py +++ b/scripts/collection/releaseassets.py @@ -4,64 +4,73 @@ from __future__ import annotations import json import os +from pathlib import Path -def load_gitignored_large_files() -> set[str]: - """The bios/ paths .gitignore registers as release assets.""" +class DatabaseUnreadable(Exception): + """The previous database exists and is not JSON: its release-asset entries cannot be kept.""" + + +def load_gitignored_large_files(gitignore: str | Path) -> set[str]: + """The bios/ paths a .gitignore registers as release assets.""" from model.largefiles import load_registered_paths - return set(load_registered_paths(".gitignore")) + 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 - +def read_database(db_path: str) -> dict | None: + """The previous database, None when there is none.""" try: with open(db_path) as f: - existing_db = json.load(f) + return json.load(f) except FileNotFoundError: - return 0 + return None 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( + raise DatabaseUnreadable( 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 + +def surviving_entries(existing_db: dict, files: dict, registered: set[str]) -> dict: + """The entries of the previous database a scan that missed their file keeps. + + Files kept out of git live as assets of the large-files release, and + .gitignore registers their paths. An entry survives 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 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()} + return { + sha1: entry + for sha1, entry in existing_db.get("files", {}).items() + if sha1 not in files + and entry.get("path", "") in registered + and entry.get("path", "") not in scanned_paths + } - count = 0 - for sha1, entry in existing_db.get("files", {}).items(): + +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.""" + from model.largefiles import fetch_large_file, restore_verified + + for sha1, entry in entries.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", ""), + offline=offline, + registered=registered, ) 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/run.py b/scripts/collection/run.py index 5e36e8b88..34961878d 100644 --- a/scripts/collection/run.py +++ b/scripts/collection/run.py @@ -11,14 +11,38 @@ 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.releaseassets import ( + DatabaseUnreadable, + load_gitignored_large_files, + read_database, + restore_release_assets, + surviving_entries, +) 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, *, offline: bool) -> int: + """Keep the entries of release assets the scan missed, their files restored, and count them.""" + registered = load_gitignored_large_files(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) + files.update(kept) + return len(kept) + def generate(args: argparse.Namespace) -> int: - """Scan bios/ and write the database, 1 when a declared source cannot be read.""" + """Scan bios/ and write the database, 1 when a declared source or the old database cannot be read.""" bios_dir = Path(args.bios_dir) # A forced run rehashes every file but keeps the previous digests to @@ -32,7 +56,11 @@ 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) + try: + preserved = preserve_release_assets(files, args.output, offline=args.offline) + except DatabaseUnreadable as exc: + print(exc, file=sys.stderr) + return 1 if preserved: print(f" Preserved {preserved} large file entries from existing database") diff --git a/scripts/generate_db.py b/scripts/generate_db.py index 374e413b2..02dbee1d9 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -40,6 +40,11 @@ def main() -> int: default=DEFAULT_PROVENANCE_DIR, help="Directory with dump-catalog snapshots", ) + parser.add_argument( + "--offline", + action="store_true", + help="Restore release assets from the local cache only, never download", + ) args = parser.parse_args() require_directory(args.bios_dir) with repository_output_lock(args.output): diff --git a/scripts/orchestrate/prepare.py b/scripts/orchestrate/prepare.py index 280801474..170334b9a 100644 --- a/scripts/orchestrate/prepare.py +++ b/scripts/orchestrate/prepare.py @@ -12,7 +12,7 @@ from orchestrate.labels import STEP_LABELS, skip_notice from orchestrate.results import SKIPPED -def database_steps(results: dict) -> bool: +def database_steps(args: argparse.Namespace, results: dict) -> bool: """Steps 0 to 1c: schemas, database, dump catalogs, romset recipes.""" all_ok = True # Step 0: the schema check PR validation runs. Without it a profile with @@ -35,19 +35,20 @@ def database_steps(results: dict) -> bool: results["validate_schemas"] = ok all_ok = all_ok and ok - # Step 1: Generate database - ok, _ = runner.run( - [ - sys.executable, - "scripts/generate_db.py", - "--force", - "--bios-dir", - "bios", - "--output", - "database.json", - ], - STEP_LABELS["generate_db"], - ) + # Step 1: Generate database. Offline, a release asset missing from + # .cache/large/ is not downloaded to restore it. + db_cmd = [ + sys.executable, + "scripts/generate_db.py", + "--force", + "--bios-dir", + "bios", + "--output", + "database.json", + ] + if args.offline: + db_cmd.append("--offline") + ok, _ = runner.run(db_cmd, STEP_LABELS["generate_db"]) results["generate_db"] = ok if not ok: print("\nDatabase generation failed, aborting.") diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 439b7af34..79dce7b99 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -147,7 +147,7 @@ def main() -> None: total_start = time.monotonic() results = StepResults(total_start) - all_ok = database_steps(results) + all_ok = database_steps(args, results) all_ok = refresh_steps(args, results) and all_ok all_ok = truth_steps(args, results) and all_ok ok, verify_output, destinations_file = verify_steps(args, results, held) diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 74c0c7bcd..75053e7a8 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -3710,23 +3710,46 @@ class AnUnreadableDatabaseStopsTheScan(unittest.TestCase): manifests.""" def test_a_corrupt_database_is_not_an_empty_one(self): - from unittest import mock - from collection import releaseassets with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "database.json" path.write_text("<<<<<<< HEAD\n{}\n") - with mock.patch.object(releaseassets, "load_gitignored_large_files", - return_value={"bios/big.bin"}): - with self.assertRaises(SystemExit): - releaseassets.preserve_large_file_entries({}, str(path)) - self.assertEqual( - releaseassets.preserve_large_file_entries( - {}, str(Path(directory) / "absent.json") - ), - 0, - ) + with self.assertRaises(releaseassets.DatabaseUnreadable) as caught: + releaseassets.read_database(str(path)) + self.assertIn("is not valid JSON", str(caught.exception)) + self.assertIsNone( + releaseassets.read_database(str(Path(directory) / "absent.json")) + ) + + def test_the_build_exits_1_on_it(self): + import argparse + import io + from contextlib import redirect_stderr, redirect_stdout + from unittest import mock + + from collection import run + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "bios").mkdir() + output = root / "database.json" + output.write_text("<<<<<<< HEAD\n{}\n") + args = argparse.Namespace( + bios_dir=str(root / "bios"), force=True, output=str(output), + offline=True, platforms_dir=str(root), emulators_dir=str(root), + provenance_dir=str(root), + ) + 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.assertTrue(output.read_text().startswith("<<<<<<<")) class TheZipIndexCacheKnowsItsInputs(unittest.TestCase): diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index bb8afa150..cc7357a50 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -26,6 +26,7 @@ from model.composition import GAME_DATA_TOPS, composition_tier from model.profiles import load_emulator_profiles from model import largefiles from release import assets as release_assets +from tests.sources import script_source REPO_ROOT = Path(__file__).resolve().parent.parent @@ -413,87 +414,90 @@ class PreservedLargeFileEntries(unittest.TestCase): bytes. """ + REGISTERED = {"bios/Sony/PS3/FW.PUP"} + + def setUp(self): + from collection import releaseassets + + self.releaseassets = releaseassets + + def _kept(self, existing: dict, files: dict) -> dict: + return self.releaseassets.surviving_entries( + {"files": existing}, files, self.REGISTERED + ) + + def test_stale_entry_for_a_rescanned_path_is_dropped(self): + existing = { + "a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}, + "b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}, + } + # The scan found the current revision at that path. + files = {"a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} + self.assertEqual(self._kept(existing, files), {}) + + def test_absent_large_file_is_still_preserved(self): + existing = {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} + self.assertEqual(list(self._kept(existing, {})), ["b" * 40]) + + def test_a_file_sharing_only_the_name_is_not_preserved(self): + existing = {"c" * 40: {"name": "FW.PUP", "path": "bios/Sony/PSP/FW.PUP"}} + self.assertEqual(self._kept(existing, {}), {}) + + def test_a_second_revision_under_a_rescanned_path_is_dropped(self): + existing = {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} + files = {"a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} + self.assertEqual(self._kept(existing, files), {}) + + +class RestoredReleaseAssets(unittest.TestCase): + """A kept entry's asset goes back to its registered path, whole or not at all.""" + def setUp(self): from collection import releaseassets 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.cache = self.tmp / "cache" / "FW.PUP" + self.cache.parent.mkdir() + self.target = self.tmp / "bios/Sony/PS3/FW.PUP" + self.sha1 = hashlib.sha1(b"firmware").hexdigest() self._real_fetch = largefiles.fetch_large_file - releaseassets.__dict__.pop("fetch_large_file", None) + self.asked: list[dict] = [] + + def fetch(*_a, **kwargs): + self.asked.append(kwargs) + return str(self.cache) + + largefiles.fetch_large_file = fetch def tearDown(self): - os.chdir(self._cwd) largefiles.fetch_large_file = self._real_fetch self._tmp.cleanup() - def _write_db(self, entries: dict) -> str: - path = str(self.tmp / "database.json") - Path(path).write_text(json.dumps({"files": entries})) - return path - - def test_stale_entry_for_a_rescanned_path_is_dropped(self): - largefiles.fetch_large_file = lambda *_a, **_k: None - db_path = self._write_db( - { - "a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}, - "b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}, - } + def _restore(self, *, offline: bool = False) -> None: + entries = {self.sha1: {"name": "FW.PUP", "path": str(self.target)}} + self.releaseassets.restore_release_assets( + entries, {str(self.target)}, offline=offline ) - # The scan found the current revision at that path. - files = {"a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - count = self.releaseassets.preserve_large_file_entries(files, db_path) - self.assertEqual(count, 0) - self.assertEqual(list(files), ["a" * 40]) - - def test_absent_large_file_is_still_preserved(self): - largefiles.fetch_large_file = lambda *_a, **_k: None - db_path = self._write_db( - {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - ) - files: dict = {} - count = self.releaseassets.preserve_large_file_entries(files, db_path) - self.assertEqual(count, 1) - self.assertIn("b" * 40, files) def test_a_fetched_asset_returns_to_its_registered_path(self): - cache = self.tmp / "cache" / "FW.PUP" - cache.parent.mkdir() - cache.write_bytes(b"firmware") - largefiles.fetch_large_file = lambda *_a, **_k: str(cache) - sha1 = hashlib.sha1(b"firmware").hexdigest() - db_path = self._write_db( - {sha1: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - ) - files: dict = {} - 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") + self.cache.write_bytes(b"firmware") + self._restore() + self.assertEqual(self.target.read_bytes(), b"firmware") + + def test_offline_is_passed_to_the_fetch(self): + self.cache.write_bytes(b"firmware") + self._restore(offline=True) + self.assertEqual([kwargs["offline"] for kwargs in self.asked], [True]) def test_a_cached_copy_with_other_bytes_is_not_restored(self): - cache = self.tmp / "cache" / "FW.PUP" - cache.parent.mkdir() - cache.write_bytes(b"replaced") - largefiles.fetch_large_file = lambda *_a, **_k: str(cache) - sha1 = hashlib.sha1(b"firmware").hexdigest() - db_path = self._write_db( - {sha1: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - ) - self.releaseassets.preserve_large_file_entries({}, db_path) - self.assertEqual(list((self.tmp / "bios/Sony/PS3").iterdir()), []) + self.cache.write_bytes(b"replaced") + self._restore() + self.assertEqual(list(self.target.parent.iterdir()), []) def test_an_interrupted_restore_leaves_no_file_behind(self): - cache = self.tmp / "cache" / "FW.PUP" - cache.parent.mkdir() - cache.write_bytes(b"firmware") - largefiles.fetch_large_file = lambda *_a, **_k: str(cache) - db_path = self._write_db( - {hashlib.sha1(b"firmware").hexdigest(): {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - ) + self.cache.write_bytes(b"firmware") def interrupted(_src, dst, *_a, **_k): Path(dst).write_bytes(b"firm") @@ -501,31 +505,21 @@ class PreservedLargeFileEntries(unittest.TestCase): with mock.patch.object(largefiles.shutil, "copy2", interrupted), \ self.assertRaises(KeyboardInterrupt): - self.releaseassets.preserve_large_file_entries({}, db_path) - directory = self.tmp / "bios/Sony/PS3" - self.assertEqual(list(directory.iterdir()), []) + self._restore() + self.assertEqual(list(self.target.parent.iterdir()), []) - def test_a_file_sharing_only_the_name_is_not_preserved(self): - largefiles.fetch_large_file = lambda *_a, **_k: "/cache/large/FW.PUP" - db_path = self._write_db( - {"c" * 40: {"name": "FW.PUP", "path": "bios/Sony/PSP/FW.PUP"}} - ) - files: dict = {} - self.assertEqual( - self.releaseassets.preserve_large_file_entries(files, db_path), 0 - ) - self.assertEqual(files, {}) - def test_a_second_revision_under_a_rescanned_path_is_dropped(self): - largefiles.fetch_large_file = lambda *_a, **_k: "/cache/large/FW.PUP" - db_path = self._write_db( - {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - ) - files = {"a" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} - self.assertEqual( - self.releaseassets.preserve_large_file_entries(files, db_path), 0 - ) - self.assertEqual(list(files), ["a" * 40]) +class TheOfflinePipelineDownloadsNoAsset(unittest.TestCase): + """generate_db had no --offline: pipeline --offline step 1 downloaded a + registered asset missing from .cache/large/ to restore it.""" + + def test_the_database_step_passes_offline(self): + source = script_source("pipeline.py") + self.assertIn('db_cmd.append("--offline")', source) + + def test_generate_db_hands_offline_to_the_restore(self): + source = script_source("generate_db.py") + self.assertIn("offline=args.offline", source) class ReleaseAssetNames(unittest.TestCase): diff --git a/wiki/tools.md b/wiki/tools.md index 243c07b30..d4f820663 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -140,7 +140,8 @@ alone, run `python scripts/check_buildbot_system.py`. Scan `bios/` and build `database.json` with multi-indexed lookups. Large files in `.gitignore` are preserved from the existing database -and downloaded from GitHub release assets if not cached locally. +and downloaded from GitHub release assets if not cached locally +(`--offline` restores them from the cache only, as the offline pipeline does). ```bash python scripts/generate_db.py --force --bios-dir bios --output database.json @@ -1428,7 +1429,7 @@ Further options, by script: | `download.py` | `--list`, `--info ` shows a pack's file name, size and parts without downloading | | `export_native.py` | `--truth-dir`, `--upstream-dir` (where the platforms' own files are cached) | | `find_pinned_revision.py` | `--repo URL --path FILE --md5 HASH`, `--write PATH`, `--cache-dir` | -| `generate_db.py` | `--provenance-dir` (dump-catalog snapshots joined into the database) | +| `generate_db.py` | `--provenance-dir` (dump-catalog snapshots joined into the database), `--offline` (release assets restored from `.cache/large/` only, never downloaded) | | `generate_site.py` | `--site-dir` (the Starlight project, `website/` by default), `--docs-dir` (the pages, `src/content/docs` of that project by default) | | `mame_ref_audit.py` | `--write` points each stale ref at the line declaring its set, `--offline`, `--cache-dir` | | `migrate.py` | `--dry-run`, `--include-branches` also reads BIOS files from every remote branch |