diff --git a/scripts/bios_integrity.py b/scripts/bios_integrity.py index 8bf7229b6..cf0eb1a59 100644 --- a/scripts/bios_integrity.py +++ b/scripts/bios_integrity.py @@ -44,7 +44,7 @@ from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from core.cli import add_repo_inputs -from core.hashing import file_digest +from core.hashing import file_digest, git_blob_sha from model.largefiles import load_registered_paths MISREAD = "misread" @@ -114,7 +114,7 @@ def modified_for_git(root: Path, path: str) -> bool: def restore_from_blob(root: Path, path: str, blob: str, expected: str) -> str: """Write the blob's bytes over path, after checking them. Empty on success.""" data = git(root, "cat-file", "blob", blob).stdout - object_id = hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() + object_id = git_blob_sha(data) if object_id != blob: return f"blob read back as {object_id[:12]}, not {blob[:12]}" if hashlib.sha1(data).hexdigest() != expected: diff --git a/scripts/core/hashing.py b/scripts/core/hashing.py index 63343710e..d5708350e 100644 --- a/scripts/core/hashing.py +++ b/scripts/core/hashing.py @@ -112,6 +112,14 @@ def file_digest(path: Path, algorithm: str = "sha1") -> str: return digest.hexdigest() +def git_blob_sha(data: bytes) -> str: + """The sha git gives a blob, so a cached file can be checked against a + repository listing without any other state.""" + digest = hashlib.sha1(f"blob {len(data)}\0".encode()) + digest.update(data) + return digest.hexdigest() + + def md5sum(source: str | os.PathLike[str] | IO[bytes]) -> str: """Compute MD5 of a file path or file-like object - matches Batocera's md5sum().""" if isinstance(source, (str, os.PathLike)): diff --git a/scripts/scraper/arcade_parent_importer.py b/scripts/scraper/arcade_parent_importer.py index 35e1cf7b2..812af2b80 100644 --- a/scripts/scraper/arcade_parent_importer.py +++ b/scripts/scraper/arcade_parent_importer.py @@ -54,18 +54,12 @@ from model.database import load_database from core.artifacts import write_if_changed from model.profiles import load_emulator_profiles from core.cli import add_repo_inputs, run_cli -from core.hashing import compute_hashes +from core.hashing import compute_hashes, git_blob_sha from core.upstream import parse_repo -from .base_scraper import download +from .base_scraper import BlobMismatchError, download, fetch_verified_blob from .clex import DriverSourceError, blank_comments, call_args, call_span from .listxml import Opener, attrs, iter_elements, open_listxml, rom_members -from .romset_dat_importer import ( - MAME_LISTXML_URL, - BlobMismatchError, - _api_json, - fetch_pack, - git_blob_sha, -) +from .romset_dat_importer import MAME_LISTXML_URL, _api_json, fetch_pack SCHEMA_VERSION = 1 DEFAULT_OUTPUT = Path("games") / "arcade" @@ -891,17 +885,11 @@ def fetch_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tuple ) if isinstance(listing, list) else None if item is None: raise FileNotFoundError(f"{slug}@{commit[:8]} has no {path}") - destination = cache_dir / "repo" / slug / commit / path - if destination.is_file() and git_blob_sha(destination.read_bytes()) != item["sha"]: - destination.unlink() url = ( f"https://raw.githubusercontent.com/{slug}/{commit}/" f"{urllib.parse.quote(path)}" ) - download(url, destination, skip_existing=True) - if git_blob_sha(destination.read_bytes()) != item["sha"]: - destination.unlink() - raise BlobMismatchError(f"{url} is not blob {item['sha']}") + destination = fetch_verified_blob(url, cache_dir / "repo" / slug / commit / path, item["sha"]) return destination, item["sha"] diff --git a/scripts/scraper/base_scraper.py b/scripts/scraper/base_scraper.py index d6d629364..143f57cd7 100644 --- a/scripts/scraper/base_scraper.py +++ b/scripts/scraper/base_scraper.py @@ -18,6 +18,7 @@ from typing import Any, Callable, NoReturn, TypeVar from core.github import github_token from core.artifacts import copy_stream_atomic, write_text_atomic +from core.hashing import git_blob_sha from core.upstream import ( MAX_RESPONSE_SIZE, RateLimitError, @@ -259,6 +260,26 @@ def download( return _open(urllib.request.Request(url, headers=headers or {}), save, timeout) +class BlobMismatchError(ValueError): + """A downloaded file is not the blob the repository listing names.""" + + +def fetch_verified_blob(url: str, destination: Path, blob_sha: str, context: str = "") -> Path: + """`destination`, downloaded from `url` unless the cached copy already is + git blob `blob_sha`, and checked against it. + + The cache is addressed by content: a file already there is kept only + while its blob sha is the one the repository lists. + """ + if destination.is_file() and git_blob_sha(destination.read_bytes()) != blob_sha: + destination.unlink() + download(url, destination, skip_existing=True) + if git_blob_sha(destination.read_bytes()) != blob_sha: + destination.unlink() + raise BlobMismatchError(f"{url} is not blob {blob_sha}{context}") + return destination + + def github_json( url: str, failure: str, timeout: float = 30, error: type[Exception] = RuntimeError ) -> Any: diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index fa9b66b0f..2af4c4b2c 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -48,7 +48,13 @@ from core.cli import add_repo_inputs, run_cli from model.database import load_database from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot from resolve.localfile import variant_base_name -from .base_scraper import download, fetch_github_latest_version, github_json +from .base_scraper import ( + BlobMismatchError, + download, + fetch_github_latest_version, + fetch_verified_blob, + github_json, +) from .listxml import ( Opener, iter_dat_documents, @@ -410,18 +416,6 @@ def fetch_tag(source: str, requested: str) -> str: return requested -class BlobMismatchError(ValueError): - """A downloaded DAT is not the blob the repository listing names.""" - - -def git_blob_sha(data: bytes) -> str: - """The sha git gives a blob, so a cached file can be checked against a - repository listing without any other state.""" - digest = hashlib.sha1(f"blob {len(data)}\0".encode()) - digest.update(data) - return digest.hexdigest() - - def fetch_pack( source: str, tag: str, cache_dir: Path ) -> tuple[Path, dict[str, str]]: @@ -455,18 +449,10 @@ def fetch_pack( for item in listing: if item.get("type") != "file" or not item["name"].lower().endswith(".dat"): continue - destination = target / item["name"] - # The cache is addressed by content: a file already there is kept - # only while its blob sha is the one the repository lists. - if destination.is_file() and git_blob_sha(destination.read_bytes()) != item["sha"]: - destination.unlink() - download(item["download_url"], destination, skip_existing=True) - if git_blob_sha(destination.read_bytes()) != item["sha"]: - destination.unlink() - raise BlobMismatchError( - f"{item['name']} downloaded from {item['download_url']} is not " - f"blob {item['sha']} of libretro/FBNeo {sha}" - ) + fetch_verified_blob( + item["download_url"], target / item["name"], item["sha"], + f" of libretro/FBNeo {sha}", + ) blobs[item["name"]] = item["sha"] # A DAT the revision does not carry is not read from an older fetch. for stale in target.glob("*"): diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index b5e6ab900..8cde2e55a 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -4,6 +4,7 @@ from __future__ import annotations import tests +import contextlib import hashlib import json import sys @@ -27,11 +28,11 @@ from scripts.scraper.romset_dat_importer import ( compact_entries, holds_target, listxml_entries, - git_blob_sha, merge_snapshot, recipe_entries, ) from scripts.scraper.logiqx_parser import parse_logiqx +from core.hashing import git_blob_sha from core.torrentzip import build_torrentzip, is_torrentzip ROOT = Path(__file__).resolve().parent.parent @@ -889,7 +890,7 @@ class FbneoFetchReadsOneRevision(unittest.TestCase): return {"sha": "c0ffee"} return [{ "type": "file", "name": "Demo.dat", - "sha": self.importer.git_blob_sha(FBNEO_DAT), + "sha": git_blob_sha(FBNEO_DAT), "download_url": "https://raw.githubusercontent.com/libretro/FBNeo/c0ffee/dats/Demo.dat", }] @@ -897,12 +898,15 @@ class FbneoFetchReadsOneRevision(unittest.TestCase): destination.write_bytes(self.served) return "" + @contextlib.contextmanager def _patched(self): from unittest import mock - return mock.patch.multiple( - self.importer, _api_json=self._api, download=self._download - ) + from scripts.scraper import base_scraper + + with mock.patch.object(self.importer, "_api_json", self._api), \ + mock.patch.object(base_scraper, "download", self._download): + yield def test_bytes_that_are_not_the_listed_blob_are_refused(self): self.served = FBNEO_DAT.replace(b"1.0.0.03", b"1.0.0.02")