diff --git a/scripts/scraper/fbneo_hash_scraper.py b/scripts/scraper/fbneo_hash_scraper.py index 3eca408fa..fffc2fadc 100644 --- a/scripts/scraper/fbneo_hash_scraper.py +++ b/scripts/scraper/fbneo_hash_scraper.py @@ -12,79 +12,33 @@ import json import logging import os import re -import shutil -import subprocess import sys -from datetime import datetime, timedelta, timezone +from datetime import datetime, timezone from pathlib import Path from typing import Any import yaml +from core import paths +from core.paths import REPO_ROOT from model.profiles import source_yaml_paths from core.artifacts import write_text_atomic from model.safeparse import yaml_load from scripts.scraper._hash_merge import compute_diff, merge_fbneo_profile from scripts.scraper.fbneo_parser import parse_fbneo_source_tree +from scripts.scraper.sparse_clone import fresh_cache, remove_clone, sparse_clone log = logging.getLogger(__name__) REPO_URL = "https://github.com/finalburnneo/FBNeo.git" -REPO_ROOT = Path(__file__).resolve().parent.parent.parent # One clone per process, for the reason mame_hash_scraper gives. CLONE_DIR = REPO_ROOT / "tmp" / f"fbneo-{os.getpid()}" CACHE_PATH = REPO_ROOT / "data" / "fbneo-hashes.json" -EMULATORS_DIR = REPO_ROOT / "emulators" +EMULATORS_DIR = REPO_ROOT / paths.EMULATORS_DIR STALE_HOURS = 24 -def _is_cache_fresh() -> bool: - """Check if the JSON cache exists and is less than 24 hours old.""" - if not CACHE_PATH.exists(): - return False - try: - data = json.loads(CACHE_PATH.read_text(encoding="utf-8")) - if not data.get("bios_sets"): - return False - fetched_at = datetime.fromisoformat(data["fetched_at"]) - return datetime.now(timezone.utc) - fetched_at < timedelta(hours=STALE_HOURS) - except (json.JSONDecodeError, KeyError, ValueError): - return False - - -def _sparse_clone() -> None: - """Sparse clone FBNeo repo: src/burn/drv, and in cone mode src/burn/version.h.""" - if CLONE_DIR.exists(): - shutil.rmtree(CLONE_DIR) - - CLONE_DIR.parent.mkdir(parents=True, exist_ok=True) - - subprocess.run( - [ - "git", - "clone", - "--depth", - "1", - "--filter=blob:none", - "--sparse", - REPO_URL, - str(CLONE_DIR), - ], - check=True, - capture_output=True, - text=True, - ) - - subprocess.run( - ["git", "sparse-checkout", "set", "src/burn/drv"], - cwd=CLONE_DIR, - check=True, - capture_output=True, - text=True, - ) - - # src/burn/version.h, as the libretro core prints it: "v%x.%x.%x.%02x" of # the BCD BURN_VERSION, so VER_ALPHA 3 reads 1.0.0.03. FBNeo bumps this file # without tagging: the last tag (v1.0.0.02) was 9 337 commits behind it. @@ -103,42 +57,29 @@ def version_from_header(text: str) -> str: return f"v{major}.{minor}.{beta}.{alpha:02d}" -def _extract_version() -> tuple[str, str]: - """The version the cloned source states, and its commit.""" +def _extract_version() -> str: + """The version the cloned source states.""" header = CLONE_DIR / "src" / "burn" / "version.h" - version = version_from_header(header.read_text(encoding="utf-8", errors="replace")) - sha_result = subprocess.run( - ["git", "rev-parse", "HEAD"], - cwd=CLONE_DIR, - capture_output=True, - text=True, - check=True, - ) - return version, sha_result.stdout.strip() - - -def _cleanup() -> None: - """Remove the sparse clone directory.""" - if CLONE_DIR.exists(): - shutil.rmtree(CLONE_DIR) + return version_from_header(header.read_text(encoding="utf-8", errors="replace")) def fetch_and_cache(force: bool = False) -> dict[str, Any]: """Clone, parse, and write JSON cache. Returns the cache dict.""" - if not force and _is_cache_fresh(): + fresh = None if force else fresh_cache(CACHE_PATH, STALE_HOURS) + if fresh is not None: log.info("cache fresh, skipping clone (use --force to override)") - return json.loads(CACHE_PATH.read_text(encoding="utf-8")) + return fresh try: - log.info("sparse cloning %s", REPO_URL) - _sparse_clone() + # src/burn/drv, and in cone mode src/burn/version.h. + commit = sparse_clone(REPO_URL, CLONE_DIR, ["src/burn/drv"]) log.info("extracting version") - version, commit = _extract_version() + version = _extract_version() log.info("parsing source tree") bios_sets = parse_fbneo_source_tree(str(CLONE_DIR)) - if not bios_sets or not commit: + if not bios_sets: # An empty read was cached for a day and merged nothing, and # the pipeline step reported OK. raise RuntimeError(f"no BIOS set read at FBNeo {version} ({commit[:12]})") @@ -159,7 +100,7 @@ def fetch_and_cache(force: bool = False) -> dict[str, Any]: return cache finally: - _cleanup() + remove_clone(CLONE_DIR) def _find_fbneo_profiles() -> list[Path]: diff --git a/scripts/scraper/mame_hash_scraper.py b/scripts/scraper/mame_hash_scraper.py index a3f59d345..3b6b317c0 100644 --- a/scripts/scraper/mame_hash_scraper.py +++ b/scripts/scraper/mame_hash_scraper.py @@ -12,8 +12,6 @@ import json import os import logging import re -import shutil -import subprocess import sys from collections import Counter from datetime import datetime, timezone @@ -55,8 +53,9 @@ from .mame_devices import ( source_path, ) from .listxml import open_listxml +from .sparse_clone import fresh_cache, remove_clone, sparse_clone from .mame_parser import parse_mame_source_tree -from core.paths import REPO_ROOT +from core.paths import EMULATORS_DIR, PLATFORMS_DIR, REPO_ROOT log = logging.getLogger(__name__) @@ -64,8 +63,8 @@ _CACHE_PATH = REPO_ROOT / "data" / "mame-hashes.json" # One clone per process: a fixed tmp/mame was removed and recloned at another # release by a second run while the first was still parsing it. _CLONE_DIR = REPO_ROOT / "tmp" / f"mame-{os.getpid()}" -_EMULATORS_DIR = REPO_ROOT / "emulators" -_PLATFORMS_DIR = REPO_ROOT / "platforms" +_EMULATORS_DIR = REPO_ROOT / EMULATORS_DIR +_PLATFORMS_DIR = REPO_ROOT / PLATFORMS_DIR _FLOPPY_SOURCE = "src/devices/imagedev/floppy.cpp" # Where a device set goes when only machines no seed places load it: MAME # starts such a machine from its set name, as an arcade folder passes one. @@ -78,30 +77,6 @@ _STALE_HOURS = 24 # Cache -def _load_cache() -> dict[str, Any] | None: - if not _CACHE_PATH.exists(): - return None - try: - with open(_CACHE_PATH, encoding="utf-8") as f: - return json.load(f) - except (json.JSONDecodeError, OSError): - return None - - -def _is_stale(cache: dict[str, Any] | None) -> bool: - if cache is None or not cache.get("bios_sets"): - return True - fetched_at = cache.get("fetched_at") - if not fetched_at: - return True - try: - ts = datetime.fromisoformat(fetched_at) - age = datetime.now(timezone.utc) - ts - return age.total_seconds() > _STALE_HOURS * 3600 - except (ValueError, TypeError): - return True - - def _write_cache(data: dict[str, Any]) -> None: _CACHE_PATH.parent.mkdir(parents=True, exist_ok=True) write_text_atomic( @@ -113,47 +88,15 @@ def _write_cache(data: dict[str, Any]) -> None: # Git operations -def _run_git( - args: list[str], cwd: Path | None = None -) -> subprocess.CompletedProcess[str]: - return subprocess.run( - ["git", *args], - cwd=cwd, - check=True, - capture_output=True, - text=True, - ) - - -def _sparse_clone(tag: str) -> None: - """Clone the release the data will be labelled with, not master. +def _sparse_clone(tag: str) -> str: + """Clone the release the data will be labelled with, not master, and + return its commit. The version comes from the latest release. Cloning master gave line numbers and hashes of a later revision under that release's label, and the profiles cited lines no declared revision holds. """ - if _CLONE_DIR.exists(): - shutil.rmtree(_CLONE_DIR) - _CLONE_DIR.parent.mkdir(parents=True, exist_ok=True) - - log.info("sparse cloning mamedev/mame %s into %s", tag, _CLONE_DIR) - _run_git( - [ - "clone", - "--depth", - "1", - "--branch", - tag, - "--filter=blob:none", - "--sparse", - _REPO_URL, - str(_CLONE_DIR), - ] - ) - _run_git( - ["sparse-checkout", "set", "src/mame", "src/devices"], - cwd=_CLONE_DIR, - ) + return sparse_clone(_REPO_URL, _CLONE_DIR, ["src/mame", "src/devices"], tag) def _get_version() -> str: @@ -173,31 +116,6 @@ def _parse_version_tag(tag: str) -> str: return raw -def _get_commit() -> str: - """The commit the clone holds, or an error: never an empty pin. - - Returned empty, it was cached for a day and the merge advanced - core_version and the refs to the new release while upstream_commit - stayed on the old one, a profile describing two revisions at once. - """ - try: - result = _run_git(["rev-parse", "HEAD"], cwd=_CLONE_DIR) - except subprocess.CalledProcessError as exc: - raise RuntimeError( - f"cannot read the commit of the MAME clone in {_CLONE_DIR}: {exc}" - ) from exc - commit = result.stdout.strip() - if not commit: - raise RuntimeError(f"the MAME clone in {_CLONE_DIR} names no commit") - return commit - - -def _cleanup() -> None: - if _CLONE_DIR.exists(): - log.info("cleaning up %s", _CLONE_DIR) - shutil.rmtree(_CLONE_DIR) - - # Profile discovery @@ -292,18 +210,17 @@ def _format_diff( def _fetch_hashes(force: bool) -> dict[str, Any]: - cache = _load_cache() - if not force and cache is not None and not _is_stale(cache): + cache = None if force else fresh_cache(_CACHE_PATH, _STALE_HOURS) + if cache is not None: log.info("using cached data from %s", cache.get("fetched_at", "")) return cache try: tag = fetch_github_latest_version(MAME_REPO) - _sparse_clone(tag) + commit = _sparse_clone(tag) bios_sets = parse_mame_source_tree(str(_CLONE_DIR)) version = _parse_version_tag(tag) - commit = _get_commit() - if not bios_sets or not commit: + if not bios_sets: # An empty read was cached for a day and every profile entry # came out "out of scope", so nothing was refreshed and the # pipeline step reported OK. @@ -319,7 +236,7 @@ def _fetch_hashes(force: bool) -> dict[str, Any]: _write_cache(data) return data finally: - _cleanup() + remove_clone(_CLONE_DIR) def _run(args: argparse.Namespace) -> None: @@ -483,12 +400,11 @@ _QUOTE_REF = re.compile(r'^(\s*source_ref: )([^"\'\n].*)$', re.MULTILINE) def _write_release(args: argparse.Namespace) -> None: """Write the profile of one MAME release, read from its own tag.""" try: - _sparse_clone(args.release) + commit = _sparse_clone(args.release) bios_sets = parse_mame_source_tree(str(_CLONE_DIR)) - commit = _get_commit() finally: - _cleanup() - if not bios_sets or not commit: + remove_clone(_CLONE_DIR) + if not bios_sets: raise RuntimeError(f"no BIOS root set read at {args.release}") reference = yaml_load((_EMULATORS_DIR / "mame.yml").read_text(encoding="utf-8")) profile = release_profile( diff --git a/scripts/scraper/sparse_clone.py b/scripts/scraper/sparse_clone.py new file mode 100644 index 000000000..f322eaf1d --- /dev/null +++ b/scripts/scraper/sparse_clone.py @@ -0,0 +1,72 @@ +"""A shallow sparse clone of an upstream tree, and the day-long cache of what +was read from it (the MAME and FBNeo hash scrapers).""" + +from __future__ import annotations + +import json +import logging +import shutil +import subprocess +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any + +log = logging.getLogger(__name__) + + +def fresh_cache(path: Path, hours: int = 24) -> dict[str, Any] | None: + """The cache at `path` when it holds BIOS sets read less than `hours` ago. + + A missing, unreadable or damaged file, an empty read and a timestamp + without a time zone all count as stale: the caller reads upstream again. + """ + try: + with open(path, encoding="utf-8") as handle: + cache = json.load(handle) + except FileNotFoundError: + return None + except (json.JSONDecodeError, OSError) as exc: + log.warning("ignoring the cache %s: %s", path, exc) + return None + if not isinstance(cache, dict) or not cache.get("bios_sets"): + return None + try: + age = datetime.now(timezone.utc) - datetime.fromisoformat(cache["fetched_at"]) + except (KeyError, ValueError, TypeError): + return None + return cache if age < timedelta(hours=hours) else None + + +def _git(args: list[str], cwd: Path | None = None) -> str: + return subprocess.run( + ["git", *args], cwd=cwd, check=True, capture_output=True, text=True + ).stdout + + +def sparse_clone(url: str, dest: Path, dirs: list[str], ref: str | None = None) -> str: + """Clone `dirs` of `url` at `ref` (the default branch when None) into + `dest`, replacing what is there, and return the commit cloned. + + Never an empty commit: returned empty, it was cached for a day and a + merge advanced core_version and the refs while upstream_commit stayed + on the previous release, a profile describing two revisions at once. + """ + remove_clone(dest) + dest.parent.mkdir(parents=True, exist_ok=True) + log.info("sparse cloning %s %s into %s", url, ref or "HEAD", dest) + branch = ["--branch", ref] if ref else [] + _git(["clone", "--depth", "1", *branch, "--filter=blob:none", "--sparse", url, str(dest)]) + _git(["sparse-checkout", "set", *dirs], cwd=dest) + try: + commit = _git(["rev-parse", "HEAD"], cwd=dest).strip() + except subprocess.CalledProcessError as exc: + raise RuntimeError(f"cannot read the commit of the clone in {dest}: {exc}") from exc + if not commit: + raise RuntimeError(f"the clone in {dest} names no commit") + return commit + + +def remove_clone(dest: Path) -> None: + if dest.exists(): + log.info("cleaning up %s", dest) + shutil.rmtree(dest) diff --git a/tests/test_hash_merge.py b/tests/test_hash_merge.py index 6b20399f5..a61854106 100644 --- a/tests/test_hash_merge.py +++ b/tests/test_hash_merge.py @@ -433,17 +433,19 @@ class TheScraperClonesTheReleaseItLabels(unittest.TestCase): from scripts.scraper import mame_hash_scraper as scraper + from scripts.scraper import sparse_clone + calls: list[list[str]] = [] + + def git(args: list[str], cwd: object = None) -> str: + calls.append(args) + return "c" * 40 + "\n" if args[0] == "rev-parse" else "" + with mock.patch.object(scraper, "fetch_github_latest_version", return_value="mame0289"), \ - mock.patch.object(scraper, "_run_git", - side_effect=lambda args, cwd=None: calls.append(args)), \ + mock.patch.object(sparse_clone, "_git", side_effect=git), \ mock.patch.object(scraper, "parse_mame_source_tree", return_value={"neogeo": {"roms": []}}), \ - mock.patch.object(scraper, "_get_commit", return_value="c" * 40), \ - mock.patch.object(scraper, "_write_cache"), \ - mock.patch.object(scraper, "_cleanup"), \ - mock.patch.object(scraper, "_load_cache", return_value={}), \ - mock.patch.object(scraper, "_is_stale", return_value=True): + mock.patch.object(scraper, "_write_cache"): data = scraper._fetch_hashes(force=True) clone = next(args for args in calls if args[0] == "clone") self.assertEqual(clone[clone.index("--branch") + 1], "mame0289") @@ -806,22 +808,29 @@ class TestDerivativeVersion(unittest.TestCase): class AnUnreadableCloneStopsTheScrape(unittest.TestCase): - """_get_commit swallowed a failed rev-parse and returned "": cached for a - day, the merge then advanced core_version and the refs while + """A failed rev-parse was swallowed and returned "": cached for a day, + the merge then advanced core_version and the refs while upstream_commit stayed on the previous release.""" def test_no_empty_commit_reaches_the_cache(self): import subprocess from unittest import mock - from scripts.scraper import mame_hash_scraper as scraper + from scripts.scraper import sparse_clone + dest = Path(tempfile.gettempdir()) / "retrobios-no-clone" failing = subprocess.CalledProcessError(128, ["git", "rev-parse", "HEAD"]) - with mock.patch.object(scraper, "_run_git", side_effect=failing), self.assertRaises(RuntimeError): - scraper._get_commit() - empty = subprocess.CompletedProcess(["git"], 0, stdout="\n", stderr="") - with mock.patch.object(scraper, "_run_git", return_value=empty), self.assertRaises(RuntimeError): - scraper._get_commit() + + def git_failing(args: list[str], cwd: object = None) -> str: + if args[0] == "rev-parse": + raise failing + return "" + + for git in (git_failing, lambda args, cwd=None: "\n" if args[0] == "rev-parse" else ""): + with mock.patch.object(sparse_clone, "_git", side_effect=git), \ + mock.patch.object(sparse_clone, "remove_clone"), \ + self.assertRaises(RuntimeError): + sparse_clone.sparse_clone("https://x/y.git", dest, ["src"]) diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index 6ee605b62..04f31aeca 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -1137,18 +1137,11 @@ class HashScraperRefusesAnEmptyRead(unittest.TestCase): cache = Path(tmp) / "mame-hashes.json" with mock.patch.object(m, "_CACHE_PATH", cache), \ mock.patch.object(m, "fetch_github_latest_version", return_value="mame0289"), \ - mock.patch.object(m, "_sparse_clone"), \ - mock.patch.object(m, "_cleanup"), \ - mock.patch.object(m, "_get_commit", return_value="abc"), \ + mock.patch.object(m, "_sparse_clone", return_value="abc"), \ mock.patch.object(m, "parse_mame_source_tree", return_value={}), self.assertRaises(RuntimeError): m._fetch_hashes(force=True) self.assertFalse(cache.exists()) - def test_mame_does_not_serve_an_empty_cache(self): - from scraper import mame_hash_scraper as m - - self.assertTrue(m._is_stale(self._fresh({}))) - self.assertFalse(m._is_stale(self._fresh({"neogeo": {}}))) def test_fbneo_raises_and_writes_no_cache(self): from scraper import fbneo_hash_scraper as f @@ -1156,23 +1149,28 @@ class HashScraperRefusesAnEmptyRead(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: cache = Path(tmp) / "fbneo-hashes.json" with mock.patch.object(f, "CACHE_PATH", cache), \ - mock.patch.object(f, "_sparse_clone"), \ - mock.patch.object(f, "_cleanup"), \ - mock.patch.object(f, "_extract_version", return_value=("v1.0.0.03", "abc")), \ + mock.patch.object(f, "sparse_clone", return_value="abc"), \ + mock.patch.object(f, "_extract_version", return_value="v1.0.0.03"), \ mock.patch.object(f, "parse_fbneo_source_tree", return_value={}), self.assertRaises(RuntimeError): f.fetch_and_cache(force=True) self.assertFalse(cache.exists()) - def test_fbneo_does_not_serve_an_empty_cache(self): - from scraper import fbneo_hash_scraper as f + def test_an_empty_or_unreadable_cache_is_not_served(self): + from scraper.sparse_clone import fresh_cache with tempfile.TemporaryDirectory() as tmp: - cache = Path(tmp) / "fbneo-hashes.json" - with mock.patch.object(f, "CACHE_PATH", cache): - cache.write_text(json.dumps(self._fresh({}))) - self.assertFalse(f._is_cache_fresh()) - cache.write_text(json.dumps(self._fresh({"neogeo": {}}))) - self.assertTrue(f._is_cache_fresh()) + cache = Path(tmp) / "hashes.json" + self.assertIsNone(fresh_cache(cache)) + cache.write_text(json.dumps(self._fresh({}))) + self.assertIsNone(fresh_cache(cache)) + cache.write_text(json.dumps(self._fresh({"neogeo": {}}))) + self.assertEqual(fresh_cache(cache)["commit"], "abc") + # A timestamp without a time zone crashed the FBNeo reader. + cache.write_text(json.dumps({"fetched_at": "2026-11-20T00:00:00", + "bios_sets": {"neogeo": {}}})) + self.assertIsNone(fresh_cache(cache)) + cache.write_text("{") + self.assertIsNone(fresh_cache(cache))