refactor: share the git blob check of downloads

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:02:01 +01:00
1 parent 8d58a9edfd
commit fd0f6c7798
6 files changed
+55 -48

No files matched your search

+4 -16
View File
@@ -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"]
+21
View File
@@ -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:
+11 -25
View File
@@ -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("*"):