From 6f8b8dedb2fe6bac55a5831c47d00be3fc5fae5a Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:02:18 +0100 Subject: [PATCH] refactor: share the scrapers' fetch helpers --- scripts/scraper/amberelec_scraper.py | 28 ++++------------- scripts/scraper/base_scraper.py | 46 ++++++++++++++++------------ scripts/scraper/batocera_scraper.py | 37 +++++++++------------- scripts/scraper/coreinfo_scraper.py | 23 ++++++-------- scripts/scraper/emudeck_scraper.py | 26 +++------------- scripts/scraper/emuelec_scraper.py | 20 +++--------- scripts/scraper/knulli_scraper.py | 25 +++++---------- scripts/scraper/libretro_scraper.py | 10 ++---- scripts/scraper/mame_hash_scraper.py | 11 ++----- scripts/scraper/retrobat_scraper.py | 16 +++------- scripts/scraper/rocknix_scraper.py | 14 ++------- tests/test_scraper_contract.py | 4 ++- 12 files changed, 89 insertions(+), 171 deletions(-) diff --git a/scripts/scraper/amberelec_scraper.py b/scripts/scraper/amberelec_scraper.py index 1ce5dfbe2..09cce6ae4 100644 --- a/scripts/scraper/amberelec_scraper.py +++ b/scripts/scraper/amberelec_scraper.py @@ -30,19 +30,17 @@ the scripts its standalone table runs and the configs their packages install. from __future__ import annotations -import json import re -import urllib.error -import urllib.request from .amberelec_launchers import extract_launchers -from .base_scraper import BaseScraper, BiosRequirement, github_headers +from .base_scraper import BaseScraper, BiosRequirement, fetch_text, github_json from .batocera_scraper import ( SYSTEM_SLUG_MAP as BATOCERA_SLUGS, ) from .batocera_scraper import ( _not_cores, extract_systems_dict, + is_checkbios_script, platform_systems, requirements_from_systems, ) @@ -93,12 +91,7 @@ def prerelease_commit(body: str) -> str: def fetch_newest_prerelease() -> tuple[str, str]: """(tag, commit) of the newest AmberELEC prerelease.""" url = f"https://api.github.com/repos/{PRERELEASE_REPO}/releases?per_page=1" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=15) as resp: - releases = json.loads(resp.read()) - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise RuntimeError(f"cannot list the releases of {PRERELEASE_REPO}: {e}") from e + releases = github_json(url, f"cannot list the releases of {PRERELEASE_REPO}") if not releases or not releases[0].get("tag_name"): raise RuntimeError(f"{PRERELEASE_REPO} lists no release") return releases[0]["tag_name"], prerelease_commit(releases[0].get("body", "")) @@ -114,17 +107,8 @@ class Scraper(BaseScraper): self.tag, self.commit = fetch_newest_prerelease() super().__init__(url=url or SOURCE_TEMPLATE.format(ref=self.commit)) - def _fetch_text(self, url: str) -> str: - req = urllib.request.Request(url, headers={"User-Agent": "retrobios-scraper/1.0"}) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - def validate_format(self, raw_data: str) -> bool: - has_dict = re.search(r"^systems\s*=\s*\{", raw_data, re.MULTILINE) is not None - return has_dict and "def checkBios" in raw_data and '"biosFiles"' in raw_data + return is_checkbios_script(raw_data) def fetch_requirements(self) -> list[BiosRequirement]: raw = self._fetch_raw() @@ -140,7 +124,7 @@ class Scraper(BaseScraper): ) # es_systems.cfg gives each its in menu order # (atarist, lines 267-288: retroarch's hatari, then HATARISA). - es_systems = xml_systems(self._fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.commit))) + es_systems = xml_systems(fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.commit))) not_cores = _not_cores(PLATFORM_NAME) cores, standalone, dual = es_cores(es_systems, RUNNERS, BUILDS_OF, not_cores) attach_system_cores(systems, system_cores(es_systems, RUNNERS, not_cores)) @@ -160,7 +144,7 @@ class Scraper(BaseScraper): "dual_mode_cores": dual, "systems": systems, "launchers": extract_launchers( - lambda path: self._fetch_text(_RAW.format(ref=self.commit) + path) + lambda path: fetch_text(_RAW.format(ref=self.commit) + path) ), } diff --git a/scripts/scraper/base_scraper.py b/scripts/scraper/base_scraper.py index b08032863..fa8ab86b6 100644 --- a/scripts/scraper/base_scraper.py +++ b/scripts/scraper/base_scraper.py @@ -15,7 +15,7 @@ import yaml from abc import ABC, abstractmethod from dataclasses import dataclass, field from pathlib import Path -from typing import Callable, NoReturn, Protocol +from typing import Any, Callable, NoReturn, Protocol from core.github import github_token from core.artifacts import write_text_atomic @@ -311,6 +311,29 @@ def github_headers() -> dict[str, str]: return headers +def fetch_text(url: str) -> str: + """GET a platform file as UTF-8 text, ConnectionError when it cannot be read.""" + req = urllib.request.Request(url, headers={"User-Agent": "retrobios-scraper/1.0"}) + try: + with urllib.request.urlopen(req, timeout=30) as resp: + return resp.read().decode("utf-8") + except urllib.error.URLError as e: + raise ConnectionError(f"Failed to fetch {url}: {e}") from e + + +def github_json( + url: str, failure: str, timeout: int = 15, error: type[Exception] = RuntimeError +) -> Any: + """An api.github.com answer, parsed. A request or a body that fails raises + `error` with `failure` and the cause: a scrape never goes on without it.""" + try: + req = urllib.request.Request(url, headers=github_headers()) + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read()) + except (urllib.error.URLError, json.JSONDecodeError) as e: + raise error(f"{failure}: {e}") from e + + def fetch_github_latest_version(repo: str) -> str: """Return the tag of the latest release of a GitHub repo. @@ -318,12 +341,7 @@ def fetch_github_latest_version(repo: str) -> str: the release it was read from cannot be patched back by the exporter. """ url = f"https://api.github.com/repos/{repo}/releases/latest" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=15) as resp: - tag = json.loads(resp.read()).get("tag_name", "") - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise RuntimeError(f"cannot read the latest release of {repo}: {e}") from e + tag = github_json(url, f"cannot read the latest release of {repo}").get("tag_name", "") if not tag: raise RuntimeError(f"the latest release of {repo} names no tag") return tag @@ -337,12 +355,7 @@ def fetch_branch_head(repo: str, branch: str) -> str: not whatever the branch has become. Raises like the release lookup. """ url = f"https://api.github.com/repos/{repo}/commits/{branch}" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=15) as resp: - sha = json.loads(resp.read()).get("sha", "") - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise RuntimeError(f"cannot read the head of {repo}@{branch}: {e}") from e + sha = github_json(url, f"cannot read the head of {repo}@{branch}").get("sha", "") if not re.fullmatch(r"[0-9a-f]{40}", sha or ""): raise RuntimeError(f"{repo}@{branch} answered no commit sha") return sha @@ -538,12 +551,7 @@ def fetch_github_latest_tag(repo: str, prefix: str = "") -> str: a reason to scrape a branch under it. """ url = f"https://api.github.com/repos/{repo}/tags?per_page=50" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=15) as resp: - tags = json.loads(resp.read()) - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise RuntimeError(f"cannot read the tags of {repo}: {e}") from e + tags = github_json(url, f"cannot read the tags of {repo}") names = [tag["name"] for tag in tags if tag["name"].startswith(prefix)] if not names: raise RuntimeError(f"{repo} has no tag starting with {prefix!r}") diff --git a/scripts/scraper/batocera_scraper.py b/scripts/scraper/batocera_scraper.py index a0907b939..c80baa90f 100644 --- a/scripts/scraper/batocera_scraper.py +++ b/scripts/scraper/batocera_scraper.py @@ -12,8 +12,6 @@ import ast import json import re import sys -import urllib.error -import urllib.request from collections.abc import Callable from pathlib import Path @@ -26,7 +24,8 @@ from model.safeparse import yaml_load_upstream from .base_scraper import ( BaseScraper, BiosRequirement, - github_headers, + fetch_text, + github_json, md5_field, requirement_entry, ) @@ -59,12 +58,7 @@ def fetch_stable_tag() -> str: it was read from, and the exporter patches that revision. """ url = "https://api.github.com/repos/batocera-linux/batocera.linux/tags?per_page=100" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=15) as resp: - tags = json.loads(resp.read()) - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise RuntimeError(f"cannot list batocera tags: {e}") from e + tags = github_json(url, "cannot list batocera tags") tag = pick_stable_tag([tag["name"] for tag in tags]) if not tag: raise RuntimeError("no stable batocera tag among the latest 100") @@ -420,6 +414,13 @@ def extract_systems_dict(raw: str) -> dict: raise ValueError(f"Failed to parse systems dict: {e}") from e +def is_checkbios_script(raw_data: str) -> bool: + """A batocera-systems script as its forks ship it: the `systems` dict of + biosFiles and the checkBios that reads it.""" + has_dict = re.search(r"^systems\s*=\s*\{", raw_data, re.MULTILINE) is not None + return has_dict and "def checkBios" in raw_data and '"biosFiles"' in raw_data + + def requirements_from_systems( systems: dict, slug_map: dict[str, str], strip: str = "bios/" ) -> list[BiosRequirement]: @@ -611,20 +612,12 @@ class Scraper(BaseScraper): it or its launcher runs a program from the BIOS folder. """ return configgen_cores( - self._fetch_text(CONFIGGEN_DEFAULTS_URL.format(tag=self.tag)), - self._fetch_text(ES_SYSTEMS_URL.format(tag=self.tag)), + fetch_text(CONFIGGEN_DEFAULTS_URL.format(tag=self.tag)), + fetch_text(ES_SYSTEMS_URL.format(tag=self.tag)), _not_cores(), built, ) - def _fetch_text(self, url: str) -> str: - req = urllib.request.Request(url, headers={"User-Agent": "retrobios-scraper/1.0"}) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - def fetch_requirements(self) -> list[BiosRequirement]: """Parse batocera-systems and return BIOS requirements.""" raw = self._fetch_raw() @@ -649,7 +642,7 @@ class Scraper(BaseScraper): ) launchers = extract_launchers( - lambda path: self._fetch_text(f"{_RAW_BASE}/{self.tag}/{path}") + lambda path: fetch_text(f"{_RAW_BASE}/{self.tag}/{path}") ) selection = BoardTargets().build_selection(self.tag) built = boards_build(selection, launchers) @@ -657,7 +650,7 @@ class Scraper(BaseScraper): cores, standalone, dual = self._fetch_cores(built) installable = installable_cores(selection, cores, standalone, dual) libretro_systems = es_systems_libretro_systems( - self._fetch_text(ES_SYSTEMS_URL.format(tag=self.tag)), _not_cores() + fetch_text(ES_SYSTEMS_URL.format(tag=self.tag)), _not_cores() ) result = { "platform": "Batocera", @@ -681,7 +674,7 @@ class Scraper(BaseScraper): result["libretro_systems"] = libretro_systems result["launchers"] = launchers result["configs_root"] = configs_root( - Configgen(lambda path: self._fetch_text(f"{_RAW_BASE}/{self.tag}/{path}")) + Configgen(lambda path: fetch_text(f"{_RAW_BASE}/{self.tag}/{path}")) ) return result diff --git a/scripts/scraper/coreinfo_scraper.py b/scripts/scraper/coreinfo_scraper.py index e4e1eed6f..188e37780 100644 --- a/scripts/scraper/coreinfo_scraper.py +++ b/scripts/scraper/coreinfo_scraper.py @@ -14,7 +14,6 @@ Complements libretro_scraper (System.dat) with: from __future__ import annotations import importlib -import json import os import re import sys @@ -31,7 +30,7 @@ from .base_scraper import ( BaseScraper, BiosRequirement, fetch_github_latest_version, - github_headers, + github_json, ) PLATFORM_NAME = "libretro_coreinfo" @@ -210,18 +209,14 @@ class Scraper(BaseScraper): """Fetch list of all .info files from GitHub API.""" # Use the tree API to get all files at once url = f"{GITHUB_API}/git/trees/master?recursive=1" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=30) as resp: - data = json.loads(resp.read()) - - return [ - item["path"] - for item in data.get("tree", []) - if item["path"].endswith("_libretro.info") - ] - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise ConnectionError(f"Failed to list core-info files: {e}") from e + data = github_json( + url, "Failed to list core-info files", timeout=30, error=ConnectionError + ) + return [ + item["path"] + for item in data.get("tree", []) + if item["path"].endswith("_libretro.info") + ] def _fetch_info_file(self, filename: str) -> dict: """Fetch and parse a single .info file. diff --git a/scripts/scraper/emudeck_scraper.py b/scripts/scraper/emudeck_scraper.py index f1acd4209..5cfe7417f 100644 --- a/scripts/scraper/emudeck_scraper.py +++ b/scripts/scraper/emudeck_scraper.py @@ -14,15 +14,14 @@ from __future__ import annotations import csv import io import re -import urllib.error -import urllib.request from .base_scraper import ( BaseScraper, BiosRequirement, fetch_branch_head, fetch_github_latest_version, - github_headers, + fetch_text, + github_json, requirement_entry, ) from .emudeck_launchers import emulator_of_script, extract_launchers @@ -202,15 +201,6 @@ _RE_LOCAL_HASHES = re.compile( ) -def _fetch_url(url: str) -> str: - req = urllib.request.Request(url, headers={"User-Agent": "retrobios-scraper/1.0"}) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - - def launcher_revision(url: str) -> str: """The commit a checkBIOS.sh URL is read at.""" found = re.search(r"/dragoonDorise/EmuDeck/([0-9a-f]{40})/", url) @@ -258,7 +248,7 @@ class Scraper(BaseScraper): def _fetch_script(self) -> str: if self._raw_script is not None: return self._raw_script - self._raw_script = _fetch_url(self.checkbios_url) + self._raw_script = fetch_text(self.checkbios_url) return self._raw_script def _fetch_csv(self, sheet: str) -> str: @@ -266,7 +256,7 @@ class Scraper(BaseScraper): return self._csv_cache[sheet] url = f"{self.csv_base_url}/{sheet}" try: - data = _fetch_url(url) + data = fetch_text(url) except ConnectionError: data = "" self._csv_cache[sheet] = data @@ -495,18 +485,12 @@ class Scraper(BaseScraper): named as their profiles are: the launcher layer and the SteamOS target are read at that revision too. """ - import json api_url = ( "https://api.github.com/repos/dragoonDorise/EmuDeck/" f"contents/functions/EmuScripts?ref={revision}" ) - try: - req = urllib.request.Request(api_url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=30) as resp: - data = json.loads(resp.read()) - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise RuntimeError(f"cannot list EmuDeck EmuScripts: {e}") from e + data = github_json(api_url, "cannot list EmuDeck EmuScripts", timeout=30) cores: list[str] = [] seen: set[str] = set() diff --git a/scripts/scraper/emuelec_scraper.py b/scripts/scraper/emuelec_scraper.py index 6c848d71b..9f6eb6687 100644 --- a/scripts/scraper/emuelec_scraper.py +++ b/scripts/scraper/emuelec_scraper.py @@ -27,16 +27,15 @@ Verification (batocera-systems at the release tag): from __future__ import annotations import re -import urllib.error -import urllib.request -from .base_scraper import BaseScraper, BiosRequirement, fetch_github_latest_version +from .base_scraper import BaseScraper, BiosRequirement, fetch_github_latest_version, fetch_text from .batocera_scraper import ( SYSTEM_SLUG_MAP as BATOCERA_SLUGS, ) from .batocera_scraper import ( _not_cores, extract_systems_dict, + is_checkbios_script, platform_systems, requirements_from_systems, ) @@ -111,17 +110,8 @@ class Scraper(BaseScraper): self.tag = "" if url else fetch_github_latest_version(REPO) super().__init__(url=url or SOURCE_TEMPLATE.format(ref=self.tag)) - def _fetch_text(self, url: str) -> str: - req = urllib.request.Request(url, headers={"User-Agent": "retrobios-scraper/1.0"}) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - def validate_format(self, raw_data: str) -> bool: - has_dict = re.search(r"^systems\s*=\s*\{", raw_data, re.MULTILINE) is not None - return has_dict and "def checkBios" in raw_data and '"biosFiles"' in raw_data + return is_checkbios_script(raw_data) def fetch_requirements(self) -> list[BiosRequirement]: raw = self._fetch_raw() @@ -139,8 +129,8 @@ class Scraper(BaseScraper): # lines 3610-3660: libretro pcsx_rearmed_32b, pcsx_rearmed, # swanstation, then Duckstation). es_systems = with_ports( - json_systems(self._fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.tag))), - port_engines(self._fetch_text(PORTS_TEMPLATE.format(ref=self.tag))), + json_systems(fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.tag))), + port_engines(fetch_text(PORTS_TEMPLATE.format(ref=self.tag))), ) not_cores = _not_cores(PLATFORM_NAME) cores, standalone, dual = es_cores(es_systems, RUNNERS, BUILDS_OF, not_cores) diff --git a/scripts/scraper/knulli_scraper.py b/scripts/scraper/knulli_scraper.py index 1c4695d7c..22f8ddad0 100644 --- a/scripts/scraper/knulli_scraper.py +++ b/scripts/scraper/knulli_scraper.py @@ -27,11 +27,10 @@ where it is older or its own. from __future__ import annotations -import re import urllib.error import urllib.request -from .base_scraper import BaseScraper, BiosRequirement, fetch_github_latest_version +from .base_scraper import BaseScraper, BiosRequirement, fetch_github_latest_version, fetch_text from .batocera_scraper import ( SYSTEM_SLUG_MAP as BATOCERA_SLUGS, ) @@ -43,6 +42,7 @@ from .batocera_scraper import ( es_systems_libretro_systems, extract_systems_dict, installable_cores, + is_checkbios_script, platform_systems, records_run, requirements_from_systems, @@ -84,14 +84,6 @@ class Scraper(BaseScraper): self.tag = "" if url else fetch_github_latest_version(REPO) super().__init__(url=url or SOURCE_TEMPLATE.format(ref=self.tag)) - def _fetch_text(self, url: str) -> str: - req = urllib.request.Request(url, headers={"User-Agent": "retrobios-scraper/1.0"}) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - def submodule_revision(self) -> str: """The batocera.linux commit KNULLI's batocera submodule pins at the tag.""" import json @@ -110,8 +102,7 @@ class Scraper(BaseScraper): return str(found["sha"]) def validate_format(self, raw_data: str) -> bool: - has_dict = re.search(r"^systems\s*=\s*\{", raw_data, re.MULTILINE) is not None - return has_dict and "def checkBios" in raw_data and '"biosFiles"' in raw_data + return is_checkbios_script(raw_data) def fetch_requirements(self) -> list[BiosRequirement]: raw = self._fetch_raw() @@ -126,13 +117,13 @@ class Scraper(BaseScraper): # es_systems.yml files machine selectors and plugins under an # emulator as Batocera's does: Batocera's list of them applies, with # KNULLI's own. - defaults = self._fetch_text(CONFIGGEN_DEFAULTS_TEMPLATE.format(ref=self.tag)) - es_systems = self._fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.tag)) + defaults = fetch_text(CONFIGGEN_DEFAULTS_TEMPLATE.format(ref=self.tag)) + es_systems = fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.tag)) dropped = _not_cores("batocera") | _not_cores(PLATFORM_NAME) revision = self.submodule_revision() launchers = extract_launchers( - lambda path: self._fetch_text(_RAW.format(ref=self.tag) + path), - lambda path: self._fetch_text(_BATOCERA_RAW.format(ref=revision) + path), + lambda path: fetch_text(_RAW.format(ref=self.tag) + path), + lambda path: fetch_text(_BATOCERA_RAW.format(ref=revision) + path), ) # What runs is what at least one board builds, read by the targets # scraper from the Kconfig of KNULLI's tree and its batocera and @@ -170,7 +161,7 @@ class Scraper(BaseScraper): result["libretro_systems"] = es_systems_libretro_systems(es_systems, dropped) result["launchers"] = launchers result["configs_root"] = configs_root( - knulli_configgen(lambda path: self._fetch_text(_RAW.format(ref=self.tag) + path)) + knulli_configgen(lambda path: fetch_text(_RAW.format(ref=self.tag) + path)) ) return result diff --git a/scripts/scraper/libretro_scraper.py b/scripts/scraper/libretro_scraper.py index e42949c92..b923e5a03 100644 --- a/scripts/scraper/libretro_scraper.py +++ b/scripts/scraper/libretro_scraper.py @@ -17,7 +17,7 @@ from .base_scraper import ( BiosRequirement, fetch_branch_head, fetch_github_latest_version, - github_headers, + github_json, requirement_entry, ) from .dat_parser import parse_dat, parse_dat_metadata, validate_dat_format @@ -106,15 +106,9 @@ SYSTEM_SLUG_MAP = { def _core_info_files() -> list[str]: """Paths of every .info file in libretro-core-info, or RuntimeError.""" - import json url = "https://api.github.com/repos/libretro/libretro-core-info/git/trees/master?recursive=1" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=30) as resp: - tree = json.loads(resp.read()) - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise RuntimeError(f"cannot list libretro-core-info: {e}") from e + tree = github_json(url, "cannot list libretro-core-info", timeout=30) info_files = [ item["path"] for item in tree.get("tree", []) diff --git a/scripts/scraper/mame_hash_scraper.py b/scripts/scraper/mame_hash_scraper.py index 821394bf7..23120df61 100644 --- a/scripts/scraper/mame_hash_scraper.py +++ b/scripts/scraper/mame_hash_scraper.py @@ -24,7 +24,6 @@ from typing import Any import yaml -from core.github import github_token from model.registry import list_registered_platforms from model.platforms import load_platform_config from model.profiles import source_yaml_paths @@ -33,6 +32,7 @@ from model.safeparse import yaml_load from core import upstream +from .base_scraper import github_headers from ._hash_merge import ( _build_contents, _build_source_ref, @@ -168,16 +168,9 @@ def _get_release_tag() -> str: version.cpp is generated at build time, not in the repo. A failed lookup raises: "unknown" was cached for a day and written as core_version. """ - headers = { - "User-Agent": "retrobios-scraper/1.0", - "Accept": "application/vnd.github.v3+json", - } - token = github_token() - if token: - headers["Authorization"] = f"Bearer {token}" url = "https://api.github.com/repos/mamedev/mame/releases/latest" try: - req = urllib.request.Request(url, headers=headers) + req = urllib.request.Request(url, headers=github_headers()) with urllib.request.urlopen(req, timeout=10) as resp: tag = json.loads(resp.read()).get("tag_name", "") except (urllib.error.URLError, json.JSONDecodeError, OSError) as exc: diff --git a/scripts/scraper/retrobat_scraper.py b/scripts/scraper/retrobat_scraper.py index bd20bd19d..f094e9a1b 100644 --- a/scripts/scraper/retrobat_scraper.py +++ b/scripts/scraper/retrobat_scraper.py @@ -10,8 +10,6 @@ from __future__ import annotations import json import re -import urllib.error -import urllib.request from pathlib import Path from .base_scraper import ( @@ -20,6 +18,7 @@ from .base_scraper import ( fetch_branch_head, fetch_bytes, fetch_github_latest_version, + fetch_text, requirement_entry, ) from .batocera_scraper import SYSTEM_SLUG_MAP as BATOCERA_SLUGS @@ -296,15 +295,10 @@ class Scraper(BaseScraper): version = fetch_github_latest_version(GITHUB_REPO) es_url = ES_SYSTEMS_URL.format(tag=version) - request = urllib.request.Request(es_url, headers={"User-Agent": "retrobios-scraper/1.0"}) - try: - with urllib.request.urlopen(request, timeout=30) as resp: - es_text = resp.read().decode("utf-8") - cores, standalone = es_systems_cores(es_text) - dual = es_systems_dual(es_text) - libretro_systems = es_systems_libretro_systems(es_text) - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {es_url}: {e}") from e + es_text = fetch_text(es_url) + cores, standalone = es_systems_cores(es_text) + dual = es_systems_dual(es_text) + libretro_systems = es_systems_libretro_systems(es_text) if not cores: raise RuntimeError(f"es_systems.cfg at {version} names no core") diff --git a/scripts/scraper/rocknix_scraper.py b/scripts/scraper/rocknix_scraper.py index 2c7387a7b..25a6b98ba 100644 --- a/scripts/scraper/rocknix_scraper.py +++ b/scripts/scraper/rocknix_scraper.py @@ -21,6 +21,7 @@ from .base_scraper import ( BaseScraper, BiosRequirement, fetch_github_latest_version, + github_json, md5_field, requirement_entry, ) @@ -168,19 +169,8 @@ class Scraper(BaseScraper): def _fetch_standalone(self) -> list[str]: """The packages of projects/ROCKNIX/packages/emulators/standalone.""" - import json - import urllib.error - import urllib.request - - from .base_scraper import github_headers - url = STANDALONE_TREE_URL.format(ref=self.tag or "next") - req = urllib.request.Request(url, headers=github_headers()) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - listing = json.loads(resp.read()) - except (urllib.error.URLError, json.JSONDecodeError) as e: - raise ConnectionError(f"Failed to list {url}: {e}") from e + listing = github_json(url, f"Failed to list {url}", timeout=30, error=ConnectionError) packages = [item["name"] for item in listing if item.get("type") == "dir"] if not packages: raise RuntimeError(f"no standalone emulator package at {url}") diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index 8bdeb771e..119e5858c 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -787,10 +787,12 @@ 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. + # romset_dat_importer._api_json, which holds the token, and the + # scrapers through base_scraper.github_json. and ("Request(" in source or "urlopen(" in source or path.suffix == ".sh") and "GITHUB_TOKEN" not in source and "github_headers(" not in source + and "github_json(" not in source and "github_token(" not in source ) self.assertEqual(silent, [])