diff --git a/scripts/generate_db.py b/scripts/generate_db.py index c3883d556..33f38b513 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -13,9 +13,7 @@ from __future__ import annotations import argparse import json import os -import shutil import sys -import tempfile from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path @@ -27,7 +25,6 @@ from core.hashing import compute_hashes from model.registry import list_registered_platforms from core.artifacts import ( repository_output_lock, - set_plain_mode, write_if_changed, write_text_atomic, ) @@ -388,25 +385,6 @@ def _load_gitignored_large_files() -> set[str]: return set(load_registered_paths(".gitignore")) -def _restore(cached: str, path: str) -> None: - """Copy a fetched asset to its registered path, whole or not at all. - - An interrupted copy at the final name is a truncated file the next scan - hashes and publishes. A scratch beside it is swapped in only once full. - """ - directory = os.path.dirname(path) - os.makedirs(directory, exist_ok=True) - fd, scratch = tempfile.mkstemp(dir=directory, prefix=".restore-") - os.close(fd) - try: - shutil.copy2(cached, scratch) - set_plain_mode(scratch) - os.replace(scratch, path) - finally: - if os.path.exists(scratch): - os.remove(scratch) - - def _preserve_large_file_entries(files: dict, db_path: str) -> int: """Keep the entries of release assets the checkout does not hold. @@ -418,7 +396,7 @@ def _preserve_large_file_entries(files: dict, db_path: str) -> int: 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 + from model.largefiles import fetch_large_file, restore_verified registered = _load_gitignored_large_files() if not registered: @@ -455,7 +433,7 @@ def _preserve_large_file_entries(files: dict, db_path: str) -> int: expected_md5=entry.get("md5", ""), ) if cached and not os.path.exists(path): - _restore(cached, path) + restore_verified(cached, path, sha1) files[sha1] = entry count += 1 return count diff --git a/scripts/model/largefiles.py b/scripts/model/largefiles.py index 99a7b44a3..98925662b 100644 --- a/scripts/model/largefiles.py +++ b/scripts/model/largefiles.py @@ -11,6 +11,7 @@ import json import os import sys import re +import shutil import tempfile import time import urllib.error @@ -21,7 +22,7 @@ from collections.abc import Iterable from pathlib import Path from core.artifacts import set_plain_mode -from core.hashing import compute_hashes, parse_hash_list +from core.hashing import compute_hashes, file_digest, parse_hash_list from core.paths import REPO_ROOT @@ -160,6 +161,33 @@ def fetch_large_file( return None +def restore_verified(source: str, path: str, sha1: str) -> bool: + """Copy a cached asset to its registered path, only if the copy hashes to sha1. + + The cache was hashed before the copy, and another run can replace a + cached name in between (a re-uploaded asset): the copy is what counts. + Whole or absent: a scan running beside a plain copy hashed the truncated + file and published that in the database. + """ + directory = os.path.dirname(os.path.abspath(path)) + os.makedirs(directory, exist_ok=True) + handle, scratch = tempfile.mkstemp( + dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp" + ) + os.close(handle) + try: + shutil.copy2(source, scratch) + if file_digest(Path(scratch)) != sha1: + print(f"Changed in the cache while restoring: {source}", file=sys.stderr) + return False + set_plain_mode(scratch) + os.replace(scratch, path) + return True + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(scratch) + + def _download(name: str, tmp_path: str) -> bool: """Stream the first release URL of *name* that answers into *tmp_path*.""" # Only a name no candidate answers is reported: a spaced name is diff --git a/scripts/release/restore.py b/scripts/release/restore.py index 71c033d8e..60470b459 100644 --- a/scripts/release/restore.py +++ b/scripts/release/restore.py @@ -2,14 +2,11 @@ from __future__ import annotations -import contextlib import os import sys -import tempfile from pathlib import Path -from model.largefiles import registered_paths -from core.artifacts import copy_file_atomic, set_plain_mode +from model.largefiles import registered_paths, restore_verified from core.hashing import file_digest from model.database import load_database @@ -39,32 +36,6 @@ def index_cache(cache_dir: str) -> dict[str, str]: return index -def _copy_verified(source: str, path: str, sha1: str) -> bool: - """Copy *source* to *path* only if the copy hashes to *sha1*. - - The cache was hashed before the copy, and another run can replace a - cached name in between (a re-uploaded asset): the copy is what counts. - Whole or absent: a scan running beside a plain copy hashed the truncated - file and published that in the database. - """ - handle, scratch = tempfile.mkstemp( - dir=os.path.dirname(os.path.abspath(path)), - prefix=f".{os.path.basename(path)}.", suffix=".tmp", - ) - os.close(handle) - try: - copy_file_atomic(source, scratch) - if file_digest(Path(scratch)) != sha1: - print(f"Changed in the cache while restoring: {source}", file=sys.stderr) - return False - set_plain_mode(scratch) - os.replace(scratch, path) - return True - finally: - with contextlib.suppress(FileNotFoundError): - os.unlink(scratch) - - def restore( cache_dir: str, db_path: str, gitignore: str ) -> tuple[int, list[str]]: @@ -88,7 +59,7 @@ def restore( unsatisfied.append(path) continue os.makedirs(os.path.dirname(path), exist_ok=True) - if not _copy_verified(source, path, sha1): + if not restore_verified(source, path, sha1): unsatisfied.append(path) continue print(f"Restored: {path}") diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index a49a2b2df..bca980eb5 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -55,7 +55,7 @@ class EveryWriterGoesThroughIt(unittest.TestCase): for name, helper in ( ("generate_pack.py", "write_text_atomic("), ("release_record.py", "write_text_atomic("), - ("restore_large_files.py", "copy_file_atomic("), + ("restore_large_files.py", "restore_verified("), ): source = script_source(name) with self.subTest(script=name): diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index a4ed81961..c9f321b6d 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -453,29 +453,42 @@ class PreservedLargeFileEntries(unittest.TestCase): 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( - {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} + {sha1: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) files: dict = {} count = self.generate_db._preserve_large_file_entries(files, db_path) self.assertEqual(count, 1) - self.assertEqual(files["b" * 40]["path"], "bios/Sony/PS3/FW.PUP") + self.assertEqual(files[sha1]["path"], "bios/Sony/PS3/FW.PUP") self.assertEqual((self.tmp / "bios/Sony/PS3/FW.PUP").read_bytes(), b"firmware") + 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.generate_db._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): 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( - {"b" * 40: {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} + {hashlib.sha1(b"firmware").hexdigest(): {"name": "FW.PUP", "path": "bios/Sony/PS3/FW.PUP"}} ) def interrupted(_src, dst, *_a, **_k): Path(dst).write_bytes(b"firm") raise KeyboardInterrupt - with mock.patch.object(self.generate_db.shutil, "copy2", interrupted), \ + with mock.patch.object(largefiles.shutil, "copy2", interrupted), \ self.assertRaises(KeyboardInterrupt): self.generate_db._preserve_large_file_entries({}, db_path) directory = self.tmp / "bios/Sony/PS3"