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.
+16 -14
View File
@@ -889,8 +889,10 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
CDN caches, and --fetch <revision> read the tip whatever was named."""
def setUp(self):
from scripts.scraper import datfetch
from scripts.scraper import romset_dat_importer as importer
self.datfetch = datfetch
self.importer = importer
self._tmp = tempfile.TemporaryDirectory()
self.dir = Path(self._tmp.name)
@@ -922,46 +924,46 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
from scripts.scraper import base_scraper
with mock.patch.object(self.importer, "_api_json", self._api), \
mock.patch.object(self.importer, "fetch_branch_head", self._head), \
with mock.patch.object(self.datfetch, "api_json", self._api), \
mock.patch.object(self.datfetch, "fetch_branch_head", self._head), \
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")
with self._patched(), self.assertRaises(self.importer.BlobMismatchError):
self.importer.fetch_pack("fbneo", "latest", self.dir)
with self._patched(), self.assertRaises(self.datfetch.BlobMismatchError):
self.datfetch.fetch_pack("fbneo", "latest", self.dir)
self.assertFalse((self.dir / "fbneo-dats" / "c0ffee" / "Demo.dat").exists())
def test_the_named_revision_is_the_one_listed(self):
with self._patched():
target, blobs = self.importer.fetch_pack("fbneo", "v1.0.0.02", self.dir)
target, blobs = self.datfetch.fetch_pack("fbneo", "v1.0.0.02", self.dir)
self.assertEqual(
self.calls,
["libretro/FBNeo@v1.0.0.02",
f"{self.importer.FBNEO_API}/contents/dats?ref=c0ffee"],
f"{self.datfetch.FBNEO_API}/contents/dats?ref=c0ffee"],
)
self.assertEqual(list(blobs), ["Demo.dat"])
def test_the_cache_is_keyed_by_the_commit(self):
with self._patched():
target, blobs = self.importer.fetch_pack("fbneo", "v1.0.0.02", self.dir)
target, blobs = self.datfetch.fetch_pack("fbneo", "v1.0.0.02", self.dir)
self.assertEqual(target, self.dir / "fbneo-dats" / "c0ffee")
self.assertEqual(self.importer.cached_pack("fbneo", "c0ffee", self.dir), (target, blobs))
self.assertEqual(self.datfetch.cached_pack("fbneo", "c0ffee", self.dir), (target, blobs))
def test_another_commit_is_not_cached(self):
with self._patched():
self.importer.fetch_pack("fbneo", "latest", self.dir)
with self.assertRaises(self.importer.NotCached):
self.importer.cached_pack("fbneo", "da14132b", self.dir)
self.datfetch.fetch_pack("fbneo", "latest", self.dir)
with self.assertRaises(self.datfetch.NotCached):
self.datfetch.cached_pack("fbneo", "da14132b", self.dir)
def test_an_uncached_listxml_is_named(self):
with self.assertRaises(self.importer.NotCached):
self.importer.cached_pack("mame", "mame0289", self.dir)
with self.assertRaises(self.datfetch.NotCached):
self.datfetch.cached_pack("mame", "mame0289", self.dir)
def test_latest_reads_the_default_branch(self):
with self._patched():
self.importer.fetch_pack("fbneo", "latest", self.dir)
self.datfetch.fetch_pack("fbneo", "latest", self.dir)
self.assertEqual(self.calls[0], "libretro/FBNeo@None")
def test_a_revision_import_is_labelled_and_leaves_the_tip_blobs(self):
+1 -1
View File
@@ -922,7 +922,7 @@ class EveryGitHubApiCallerSendsTheToken(unittest.TestCase):
for path in [*scripts.rglob("*.py"), *scripts.rglob("*.sh")]
if "api.github.com" in (source := path.read_text(encoding="utf-8"))
# arcade_parent_importer names API URLs and sends them through
# romset_dat_importer._api_json, which holds the token, and the
# datfetch.api_json, which holds the token, and the
# scrapers through base_scraper.github_json, the rest through
# core.upstream.fetch_body or forge_headers.
and ("Request(" in source or "urlopen(" in source or path.suffix == ".sh")
+1
View File
@@ -1716,6 +1716,7 @@ the GitHub and text fetches, and the shared CLI), `dat_parser.py` (clrmamepro DA
`logiqx_parser.py` (Logiqx XML DAT parser, used by the dump catalogs),
`mame_parser.py` (MAME C source BIOS root set parser),
`fbneo_parser.py` (FBNeo C source BIOS set parser),
`datfetch.py` (upstream MAME `-listxml` and FBNeo DATs, cached under `.cache/dats/`),
`_hash_merge.py` (text-based YAML patching that preserves formatting).
Adding a scraper: inherit `BaseScraper`, implement `fetch_requirements()` and