refactor: move upstream DAT fetching to datfetch

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 21:42:18 +01:00
1 parent 3df7a60e43
commit d1b0c77039
7 files changed
+122 -113

No files matched your search

+3 -3
View File
@@ -61,7 +61,7 @@ from .fbneo_parser import zip_name
from .clex import DriverSourceError, blank_comments, call_args, call_span
from .listxml import Opener, attrs, iter_elements, open_listxml, rom_members
from model.mamerelease import mame_tag
from .romset_dat_importer import MAME_LISTXML_URL, _api_json, cached_pack, fetch_pack
from .datfetch import MAME_LISTXML_URL, api_json, cached_pack, fetch_pack
SCHEMA_VERSION = 1
DEFAULT_OUTPUT = Path("games") / "arcade"
@@ -813,7 +813,7 @@ def fetch_driver_source(
skip_existing=True)
source = read_driver_source(tarball)
if not offline:
listing = _api_json(f"https://api.github.com/repos/{slug}/git/trees/{commit}")
listing = api_json(f"https://api.github.com/repos/{slug}/git/trees/{commit}")
listed = next(
(
item.get("sha")
@@ -879,7 +879,7 @@ def fetch_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tuple
"""One file of a GitHub repository at a commit, checked against the blob
sha the repository lists for it, and that sha."""
folder, _, name = path.rpartition("/")
listing = _api_json(
listing = api_json(
f"https://api.github.com/repos/{slug}/contents/{urllib.parse.quote(folder)}?ref={commit}"
)
item = next(
+97
View File
@@ -0,0 +1,97 @@
"""Upstream MAME and FBNeo DATs, downloaded once into a cache read offline."""
from __future__ import annotations
from pathlib import Path
from core.hashing import git_blob_sha
from .base_scraper import (
BlobMismatchError,
download,
fetch_branch_head,
fetch_verified_blob,
github_json,
)
MAME_LISTXML_URL = (
"https://github.com/mamedev/mame/releases/download/{tag}/{tag}lx.zip"
)
FBNEO_REPO = "libretro/FBNeo"
FBNEO_API = f"https://api.github.com/repos/{FBNEO_REPO}"
def api_json(url: str) -> object:
"""An api.github.com answer, ConnectionError when it cannot be read."""
return github_json(url, f"cannot read {url}", timeout=60, error=ConnectionError)
class NotCached(FileNotFoundError):
"""The cache holds no pack for the revision asked."""
def _listxml_path(tag: str, cache_dir: Path) -> Path:
return cache_dir / f"{tag}lx.zip"
def _fbneo_folder(commit: str, cache_dir: Path) -> Path:
# One folder per commit: a folder refilled for whatever revision was
# last asked gave an offline read the DATs of another pin.
return cache_dir / "fbneo-dats" / commit
def fetch_pack(
source: str, tag: str, cache_dir: Path
) -> tuple[Path, dict[str, str]]:
"""Download the upstream DAT for *source*.
MAME ships its ``-listxml`` output as a release asset, and FBNeo keeps its
DATs in the repository, so neither needs a browser. The second value
names the upstream state fetched: empty for a release asset, whose tag
already says which version it is, and the git blob sha of every DAT for
FBNeo, whose files change under a constant header version.
"""
if source == "mame":
listxml = _listxml_path(tag, cache_dir)
download(MAME_LISTXML_URL.format(tag=tag), listxml, skip_existing=True)
return listxml, {}
# The revision is resolved to a commit first and everything is read at
# that commit: a branch URL is served through a CDN cache, so the bytes
# could predate the listing that named their blob.
sha = fetch_branch_head(FBNEO_REPO, None if tag == "latest" else tag)
listing = api_json(f"{FBNEO_API}/contents/dats?ref={sha}")
if not isinstance(listing, list):
raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}")
target = _fbneo_folder(sha, cache_dir)
target.mkdir(parents=True, exist_ok=True)
blobs: dict[str, str] = {}
for item in listing:
if item.get("type") != "file" or not item["name"].lower().endswith(".dat"):
continue
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("*"):
if stale.is_file() and stale.name not in blobs:
stale.unlink()
return target, blobs
def cached_pack(
source: str, revision: str, cache_dir: Path
) -> tuple[Path, dict[str, str]]:
"""What fetch_pack wrote for *revision* (a MAME tag, a full FBNeo commit),
read offline. The FBNeo blobs are recomputed from the bytes."""
if source == "mame":
listxml = _listxml_path(revision, cache_dir)
if not listxml.is_file():
raise NotCached(f"{listxml} is not cached")
return listxml, {}
folder = _fbneo_folder(revision, cache_dir)
blobs = {p.name: git_blob_sha(p.read_bytes()) for p in sorted(folder.glob("*.dat"))}
if not blobs:
raise NotCached(f"{folder} is not cached")
return folder, blobs
+2 -2
View File
@@ -58,7 +58,7 @@ from .mame_devices import (
)
from .listxml import open_listxml
from model.mamerelease import mame_tag, mame_version
from .romset_dat_importer import fetch_pack
from .datfetch import fetch_pack
from .sparse_clone import fresh_cache, remove_clone, sparse_clone
from .mame_parser import parse_mame_source_tree
from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT
@@ -299,7 +299,7 @@ def _pinned_version(profile_path: Path) -> str:
def fetch_release_listxml(version: str) -> Path:
"""The -listxml MAME publishes for a release, in the DAT importer's cache.
"""The -listxml MAME publishes for a release, in the shared DAT cache.
0.289 is the tag mame0289 and the asset mame0289lx.zip.
"""
+2 -93
View File
@@ -40,7 +40,6 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import IO
from core.hashing import git_blob_sha
from core.ziptools import is_archive_path, zip_members
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
@@ -49,14 +48,8 @@ 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 (
BlobMismatchError,
download,
fetch_branch_head,
fetch_github_latest_version,
fetch_verified_blob,
github_json,
)
from .base_scraper import BlobMismatchError, fetch_github_latest_version
from .datfetch import fetch_pack
from .listxml import (
Opener,
iter_dat_documents,
@@ -395,21 +388,9 @@ def merge_snapshot(
return write_snapshot(output, snapshot)
MAME_LISTXML_URL = (
"https://github.com/mamedev/mame/releases/download/{tag}/{tag}lx.zip"
)
MAME_REPO = "mamedev/mame"
FBNEO_REPO = "libretro/FBNeo"
FBNEO_API = f"https://api.github.com/repos/{FBNEO_REPO}"
def _api_json(url: str) -> object:
"""An api.github.com answer, ConnectionError when it cannot be read."""
return github_json(url, f"cannot read {url}", timeout=60, error=ConnectionError)
def fetch_tag(source: str, requested: str) -> str:
"""The revision a ``--fetch`` names: bare, the newest MAME release or
the tip of FBNeo's default branch."""
@@ -420,78 +401,6 @@ def fetch_tag(source: str, requested: str) -> str:
return requested
class NotCached(FileNotFoundError):
"""The cache holds no pack for the revision asked."""
def _listxml_path(tag: str, cache_dir: Path) -> Path:
return cache_dir / f"{tag}lx.zip"
def _fbneo_folder(commit: str, cache_dir: Path) -> Path:
# One folder per commit: a folder refilled for whatever revision was
# last asked gave an offline read the DATs of another pin.
return cache_dir / "fbneo-dats" / commit
def fetch_pack(
source: str, tag: str, cache_dir: Path
) -> tuple[Path, dict[str, str]]:
"""Download the upstream DAT for *source*.
MAME ships its ``-listxml`` output as a release asset, and FBNeo keeps its
DATs in the repository, so neither needs a browser. The second value
names the upstream state fetched: empty for a release asset, whose tag
already says which version it is, and the git blob sha of every DAT for
FBNeo, whose files change under a constant header version.
"""
if source == "mame":
listxml = _listxml_path(tag, cache_dir)
download(MAME_LISTXML_URL.format(tag=tag), listxml, skip_existing=True)
return listxml, {}
# The revision is resolved to a commit first and everything is read at
# that commit: a branch URL is served through a CDN cache, so the bytes
# could predate the listing that named their blob.
sha = fetch_branch_head(FBNEO_REPO, None if tag == "latest" else tag)
listing = _api_json(f"{FBNEO_API}/contents/dats?ref={sha}")
if not isinstance(listing, list):
raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}")
target = _fbneo_folder(sha, cache_dir)
target.mkdir(parents=True, exist_ok=True)
blobs: dict[str, str] = {}
for item in listing:
if item.get("type") != "file" or not item["name"].lower().endswith(".dat"):
continue
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("*"):
if stale.is_file() and stale.name not in blobs:
stale.unlink()
return target, blobs
def cached_pack(
source: str, revision: str, cache_dir: Path
) -> tuple[Path, dict[str, str]]:
"""What fetch_pack wrote for *revision* (a MAME tag, a full FBNeo commit),
read offline. The FBNeo blobs are recomputed from the bytes."""
if source == "mame":
listxml = _listxml_path(revision, cache_dir)
if not listxml.is_file():
raise NotCached(f"{listxml} is not cached")
return listxml, {}
folder = _fbneo_folder(revision, cache_dir)
blobs = {p.name: git_blob_sha(p.read_bytes()) for p in sorted(folder.glob("*.dat"))}
if not blobs:
raise NotCached(f"{folder} is not cached")
return folder, blobs
def _is_listxml(pack: Path) -> bool:
"""Whether *pack* holds a MAME -listxml document rather than a DAT.