From 738bb5bc07c19fcb956ae6ac5d98ae6c80561e16 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 target scrapers' fetch and CLI --- scripts/scraper/targets/__init__.py | 50 +++++++++++++++++++ .../targets/amberelec_targets_scraper.py | 23 +-------- .../targets/batocera_targets_scraper.py | 50 ++++--------------- .../targets/emudeck_targets_scraper.py | 39 ++------------- .../targets/emuelec_targets_scraper.py | 23 +-------- .../scraper/targets/lakka_targets_scraper.py | 23 +-------- .../targets/recalbox_targets_scraper.py | 21 +------- .../targets/retroarch_targets_scraper.py | 19 ++----- .../targets/retropie_targets_scraper.py | 43 ++-------------- .../targets/rocknix_targets_scraper.py | 21 +------- tests/test_target_scrapers.py | 8 +-- 11 files changed, 82 insertions(+), 238 deletions(-) diff --git a/scripts/scraper/targets/__init__.py b/scripts/scraper/targets/__init__.py index 2c6fbd777..eb36a11f7 100644 --- a/scripts/scraper/targets/__init__.py +++ b/scripts/scraper/targets/__init__.py @@ -5,12 +5,17 @@ Auto-detects *_targets_scraper.py files and exposes their scrapers. from __future__ import annotations +import argparse import importlib import pkgutil import re +import urllib.error +import urllib.request from abc import ABC, abstractmethod from pathlib import Path +from core.github import github_token + class BaseTargetScraper(ABC): """Base class for target scrapers.""" @@ -66,6 +71,51 @@ class BaseTargetScraper(ABC): ) +def fetch_text(url: str, headers: dict[str, str] | None = None) -> str: + """GET a URL as UTF-8 text, RuntimeError with the URL when it fails.""" + try: + req = urllib.request.Request(url, headers=headers or {"User-Agent": "retrobios-scraper/1.0"}) + with urllib.request.urlopen(req, timeout=30) as resp: + return resp.read().decode("utf-8") + except urllib.error.URLError as e: + # A target written from a failed request loses its cores in silence. + raise RuntimeError(f"cannot fetch {url}: {e}") from e + + +def forge_headers(url: str, accept: str | None = None) -> dict[str, str]: + """Request headers, with the GitHub token when the URL is api.github.com.""" + headers = {"User-Agent": "retrobios-scraper/1.0"} + if accept is not None: + headers["Accept"] = accept + token = github_token() + if token and "api.github.com" in url: + headers["Authorization"] = f"Bearer {token}" + return headers + + +def target_cli(scraper_class: type[BaseTargetScraper], description: str, unit: str = "cores") -> None: + """The command line every target scraper shares: --dry-run prints each + target and its count of `unit`, --output writes the YAML, else it is printed.""" + import yaml + + parser = argparse.ArgumentParser(allow_abbrev=False, description=description) + parser.add_argument("--dry-run", action="store_true", help="Show target summary") + parser.add_argument("--output", "-o", help="Output YAML file") + args = parser.parse_args() + + scraper = scraper_class() + data = scraper.fetch_targets() + if args.dry_run: + for name, info in data["targets"].items(): + print(f" {name} ({info['architecture']}): {len(info['cores'])} {unit}") + return + if args.output: + scraper.write_output(data, args.output) + print(f"Written to {args.output}") + return + print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + + _scrapers: dict[str, type] = {} diff --git a/scripts/scraper/targets/amberelec_targets_scraper.py b/scripts/scraper/targets/amberelec_targets_scraper.py index 38eeb0e7c..cb1df8ea8 100644 --- a/scripts/scraper/targets/amberelec_targets_scraper.py +++ b/scripts/scraper/targets/amberelec_targets_scraper.py @@ -16,14 +16,12 @@ its pack shipped the Nintendo DS firmware anyway. from __future__ import annotations -import argparse import re import sys from datetime import datetime, timezone -import yaml -from . import BaseTargetScraper +from . import BaseTargetScraper, target_cli from ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS from ..base_scraper import fetch_bytes from ..batocera_scraper import _not_cores @@ -126,24 +124,7 @@ class Scraper(BaseTargetScraper): def main() -> None: - parser = argparse.ArgumentParser( - allow_abbrev=False, description="Scrape AmberELEC per-device cores" - ) - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = Scraper() - data = scraper.fetch_targets() - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} cores") - return - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(Scraper, "Scrape AmberELEC per-device cores") if __name__ == "__main__": diff --git a/scripts/scraper/targets/batocera_targets_scraper.py b/scripts/scraper/targets/batocera_targets_scraper.py index 411a47eeb..94921c641 100644 --- a/scripts/scraper/targets/batocera_targets_scraper.py +++ b/scripts/scraper/targets/batocera_targets_scraper.py @@ -15,7 +15,6 @@ Sources (batocera-linux/buildroot, at the submodule commit the tag pins): from __future__ import annotations -import argparse import json import re import sys @@ -29,7 +28,7 @@ import yaml from model.safeparse import yaml_load_upstream -from . import BaseTargetScraper +from . import BaseTargetScraper, fetch_text, target_cli from ..base_scraper import github_headers PLATFORM_NAME = "batocera" @@ -69,20 +68,10 @@ _IF_RE = re.compile(r"^if\s+(.*)$") _DEFAULT_Y_RE = re.compile(r"^\s*default\s+y\s*(?:#.*)?$") -def _fetch(url: str, headers: dict | None = None) -> str: - h = headers or {"User-Agent": "retrobios-scraper/1.0"} - try: - req = urllib.request.Request(url, headers=h) - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise RuntimeError(f"cannot fetch {url}: {e}") from e - - def _fetch_present(url: str) -> str | None: """A file's text, or None when the server answers that it does not exist.""" try: - return _fetch(url) + return fetch_text(url) except RuntimeError as e: if isinstance(e.__cause__, urllib.error.HTTPError) and e.__cause__.code == 404: return None @@ -90,7 +79,7 @@ def _fetch_present(url: str) -> str | None: def _fetch_json(url: str) -> list | dict: - text = _fetch(url, headers=github_headers()) + text = fetch_text(url, headers=github_headers()) try: return json.loads(text) except json.JSONDecodeError as e: @@ -499,7 +488,7 @@ class Scraper(BaseTargetScraper): continue seen.add(name) try: - text = _fetch(self._raw(f"configs/{name}")) + text = fetch_text(self._raw(f"configs/{name}")) except RuntimeError: if optional: continue @@ -566,7 +555,7 @@ class Scraper(BaseTargetScraper): for entry in listing.get("tree", []): if re.search(r"(^|/)retroarch\.cfg$", entry["path"]): raw = f"https://raw.githubusercontent.com/{repo}/{ref}/{entry['path']}" - found[prefix + entry["path"]] = _fetch(raw) + found[prefix + entry["path"]] = fetch_text(raw) return found def _buildroot_rules(self) -> list[tuple[str, str, str]]: @@ -578,7 +567,7 @@ class Scraper(BaseTargetScraper): raw = f"https://raw.githubusercontent.com/{self.BUILDROOT_REPO}/{sha}" rules: list[tuple[str, str, str]] = [] for path in BUILDROOT_KCONFIG: - rules += _parse_owned_selects(_fetch(f"{raw}/{path}")) + rules += _parse_owned_selects(fetch_text(f"{raw}/{path}")) return rules def build_selection(self, tag: str | None = None) -> BuildSelection: @@ -611,7 +600,7 @@ class Scraper(BaseTargetScraper): print(" fetching es_systems.yml...", file=sys.stderr) es_systems_url = self._raw(self.ES_SYSTEMS_PATH) - es_text = _fetch(es_systems_url) + es_text = fetch_text(es_systems_url) if not es_text: raise RuntimeError(f"empty es_systems.yml from {es_systems_url}") package_to_emulators = _parse_es_systems(es_text) @@ -624,7 +613,7 @@ class Scraper(BaseTargetScraper): images_by_flag = _parse_images(config_in_text) if not images_by_flag: raise RuntimeError(f"no target image list parsed from {self.CONFIG_IN_PATH}") - disabled = downloader_disabled(_fetch(self._raw(self.RETROARCH_MK)), + disabled = downloader_disabled(fetch_text(self._raw(self.RETROARCH_MK)), self._shipped_retroarch_cfgs()) if disabled: print(f" core downloader off: {disabled}", file=sys.stderr) @@ -689,28 +678,7 @@ class Scraper(BaseTargetScraper): def main(scraper_class: type[Scraper] = Scraper) -> None: - parser = argparse.ArgumentParser( - allow_abbrev=False, - description=f"Scrape {scraper_class.PLATFORM} per-board emulator targets" - ) - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = scraper_class() - data = scraper.fetch_targets() - - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} emulators") - return - - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(scraper_class, f"Scrape {scraper_class.PLATFORM} per-board emulator targets", "emulators") if __name__ == "__main__": diff --git a/scripts/scraper/targets/emudeck_targets_scraper.py b/scripts/scraper/targets/emudeck_targets_scraper.py index 092f435b8..903020bdc 100644 --- a/scripts/scraper/targets/emudeck_targets_scraper.py +++ b/scripts/scraper/targets/emudeck_targets_scraper.py @@ -10,21 +10,16 @@ Sources: from __future__ import annotations -import argparse import json import sys -import urllib.error -import urllib.request from datetime import datetime, timezone from pathlib import Path -import yaml -from core.github import github_token from model.safeparse import yaml_load from ..emudeck_launchers import SCRIPT_SUFFIXES, emulator_of_script -from . import BaseTargetScraper +from . import BaseTargetScraper, fetch_text, forge_headers, target_cli PLATFORM_NAME = "emudeck" @@ -37,17 +32,7 @@ WINDOWS_API = ( RETROARCH_TARGETS = Path(__file__).resolve().parents[3] / "platforms" / "targets" / "retroarch.yml" def _fetch(url: str) -> str: - headers = {"User-Agent": "retrobios-scraper/1.0"} - token = github_token() - if token and "api.github.com" in url: - headers["Authorization"] = f"Bearer {token}" - try: - req = urllib.request.Request(url, headers=headers) - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - # A target written from a failed request loses its cores in silence. - raise RuntimeError(f"cannot fetch {url}: {e}") from e + return fetch_text(url, forge_headers(url)) def _list_emuscripts(api_url: str) -> list[str]: @@ -148,25 +133,7 @@ class Scraper(BaseTargetScraper): def main() -> None: - parser = argparse.ArgumentParser(allow_abbrev=False, description="Scrape EmuDeck emulator targets") - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = Scraper() - data = scraper.fetch_targets() - - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} emulators") - return - - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(Scraper, "Scrape EmuDeck emulator targets", "emulators") if __name__ == "__main__": diff --git a/scripts/scraper/targets/emuelec_targets_scraper.py b/scripts/scraper/targets/emuelec_targets_scraper.py index 1bb975520..92aa1e088 100644 --- a/scripts/scraper/targets/emuelec_targets_scraper.py +++ b/scripts/scraper/targets/emuelec_targets_scraper.py @@ -25,16 +25,14 @@ shipped their firmware anyway. from __future__ import annotations -import argparse import json import re import sys from datetime import datetime, timezone from typing import NamedTuple -import yaml -from . import BaseTargetScraper +from . import BaseTargetScraper, target_cli from ..base_scraper import fetch_bytes, github_headers from ..batocera_scraper import _not_cores from ..emuelec_systems import ( @@ -639,24 +637,7 @@ class Scraper(BaseTargetScraper): def main() -> None: - parser = argparse.ArgumentParser( - allow_abbrev=False, description="Scrape EmuELEC per-device cores" - ) - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = Scraper() - data = scraper.fetch_targets() - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} cores") - return - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(Scraper, "Scrape EmuELEC per-device cores") if __name__ == "__main__": diff --git a/scripts/scraper/targets/lakka_targets_scraper.py b/scripts/scraper/targets/lakka_targets_scraper.py index eae64d338..ca5f817d5 100644 --- a/scripts/scraper/targets/lakka_targets_scraper.py +++ b/scripts/scraper/targets/lakka_targets_scraper.py @@ -12,15 +12,13 @@ a target list, its pack shipped their firmware anyway. from __future__ import annotations -import argparse import json import re import sys from datetime import datetime, timezone -import yaml -from . import BaseTargetScraper +from . import BaseTargetScraper, target_cli from ..base_scraper import fetch_bytes, github_headers PLATFORM_NAME = "lakka" @@ -259,24 +257,7 @@ class Scraper(BaseTargetScraper): def main() -> None: - parser = argparse.ArgumentParser( - allow_abbrev=False, description="Scrape Lakka per-device cores" - ) - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = Scraper() - data = scraper.fetch_targets() - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} cores") - return - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(Scraper, "Scrape Lakka per-device cores") if __name__ == "__main__": diff --git a/scripts/scraper/targets/recalbox_targets_scraper.py b/scripts/scraper/targets/recalbox_targets_scraper.py index e0e940c5c..1eb9e742b 100644 --- a/scripts/scraper/targets/recalbox_targets_scraper.py +++ b/scripts/scraper/targets/recalbox_targets_scraper.py @@ -13,15 +13,13 @@ target list, a Pi 3 pack carried the firmware of emulators only x86_64 builds. from __future__ import annotations -import argparse import json import re import sys from datetime import datetime, timezone -import yaml -from . import BaseTargetScraper +from . import BaseTargetScraper, target_cli from ..base_scraper import fetch_bytes from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores @@ -99,22 +97,7 @@ class Scraper(BaseTargetScraper): def main() -> None: - parser = argparse.ArgumentParser(allow_abbrev=False, description="Scrape Recalbox per-board cores") - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = Scraper() - data = scraper.fetch_targets() - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} cores") - return - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(Scraper, "Scrape Recalbox per-board cores") if __name__ == "__main__": diff --git a/scripts/scraper/targets/retroarch_targets_scraper.py b/scripts/scraper/targets/retroarch_targets_scraper.py index a277809c3..98d6cf6b2 100644 --- a/scripts/scraper/targets/retroarch_targets_scraper.py +++ b/scripts/scraper/targets/retroarch_targets_scraper.py @@ -23,13 +23,11 @@ from __future__ import annotations import argparse import re import sys -import urllib.error -import urllib.request from datetime import datetime, timezone import yaml -from . import BaseTargetScraper +from . import BaseTargetScraper, fetch_text PLATFORM_NAME = "retroarch" @@ -100,20 +98,9 @@ class Scraper(BaseTargetScraper): def __init__(self, url: str = BUILDBOT_URL) -> None: super().__init__(url=url) - def _fetch_url(self, url: str) -> str: - try: - req = urllib.request.Request( - url, headers={"User-Agent": "retrobios-scraper/1.0"} - ) - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - # A target written from a failed request loses its cores in silence. - raise RuntimeError(f"cannot fetch {url}: {e}") from e - def _fetch_cores_for_target(self, path: str) -> list[str]: url = f"{self.url}{path}/" - html = self._fetch_url(url) + html = fetch_text(url) cores: list[str] = [] seen: set[str] = set() for match in _HREF_RE.finditer(html): @@ -145,7 +132,7 @@ class Scraper(BaseTargetScraper): def _fetch_cores_for_recipe(self, recipe_path: str) -> list[str]: url = f"{RECIPE_BASE_URL}{recipe_path}" - return self._parse_recipe_cores(self._fetch_url(url)) + return self._parse_recipe_cores(fetch_text(url)) def fetch_targets(self) -> dict: targets: dict[str, dict] = {} diff --git a/scripts/scraper/targets/retropie_targets_scraper.py b/scripts/scraper/targets/retropie_targets_scraper.py index 8ebc2af86..0fecefd0d 100644 --- a/scripts/scraper/targets/retropie_targets_scraper.py +++ b/scripts/scraper/targets/retropie_targets_scraper.py @@ -9,18 +9,14 @@ to determine which platforms each package supports. from __future__ import annotations -import argparse import json import re import sys -import urllib.error -import urllib.request from datetime import datetime, timezone -import yaml from ..retropie_scraper import core_name -from . import BaseTargetScraper +from . import BaseTargetScraper, fetch_text, forge_headers, target_cli PLATFORM_NAME = "retropie" @@ -67,19 +63,7 @@ _MODULE_FLAGS_RE = re.compile(r'rp_module_flags\s*=\s*["\']([^"\']*)["\']') def _fetch(url: str, accept: str = "text/plain") -> str: - headers = {"User-Agent": "retrobios-scraper/1.0", "Accept": accept} - from core.github import github_token - - token = github_token() - if token and "api.github.com" in url: - headers["Authorization"] = f"Bearer {token}" - try: - req = urllib.request.Request(url, headers=headers) - with urllib.request.urlopen(req, timeout=30) as resp: - return resp.read().decode("utf-8") - except urllib.error.URLError as e: - # A target written from a failed request loses its cores in silence. - raise RuntimeError(f"cannot fetch {url}: {e}") from e + return fetch_text(url, forge_headers(url, accept)) def _is_available(flags_str: str, platform: str) -> bool: @@ -183,28 +167,7 @@ class Scraper(BaseTargetScraper): def main() -> None: - parser = argparse.ArgumentParser( - allow_abbrev=False, - description="Scrape RetroPie package targets from scriptmodules" - ) - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = Scraper() - data = scraper.fetch_targets() - - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} cores") - return - - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(Scraper, "Scrape RetroPie package targets from scriptmodules") if __name__ == "__main__": diff --git a/scripts/scraper/targets/rocknix_targets_scraper.py b/scripts/scraper/targets/rocknix_targets_scraper.py index f7e808576..527eb57dc 100644 --- a/scripts/scraper/targets/rocknix_targets_scraper.py +++ b/scripts/scraper/targets/rocknix_targets_scraper.py @@ -14,15 +14,13 @@ target list, its pack shipped the PS2, GameCube and PS3 firmware anyway. from __future__ import annotations -import argparse import json import re import sys from datetime import datetime, timezone -import yaml -from . import BaseTargetScraper +from . import BaseTargetScraper, target_cli from ..base_scraper import fetch_bytes, github_headers from ..rocknix_packages import standalone_emulators @@ -295,22 +293,7 @@ class Scraper(BaseTargetScraper): def main() -> None: - parser = argparse.ArgumentParser(allow_abbrev=False, description="Scrape ROCKNIX per-device cores") - parser.add_argument("--dry-run", action="store_true", help="Show target summary") - parser.add_argument("--output", "-o", help="Output YAML file") - args = parser.parse_args() - - scraper = Scraper() - data = scraper.fetch_targets() - if args.dry_run: - for name, info in data["targets"].items(): - print(f" {name} ({info['architecture']}): {len(info['cores'])} cores") - return - if args.output: - scraper.write_output(data, args.output) - print(f"Written to {args.output}") - return - print(yaml.dump(data, default_flow_style=False, sort_keys=False)) + target_cli(Scraper, "Scrape ROCKNIX per-device cores") if __name__ == "__main__": diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 750bd8f5e..e94c85805 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -90,8 +90,8 @@ class FailedRequestsStopTheScrape(unittest.TestCase): retropie_targets_scraper, retroarch_targets_scraper, ): - with self.subTest(scraper=module.__name__), mock.patch.object( - module.urllib.request, "urlopen", _refuse + with self.subTest(scraper=module.__name__), mock.patch( + "urllib.request.urlopen", _refuse ), self.assertRaises(RuntimeError): module.Scraper().fetch_targets() @@ -107,8 +107,8 @@ class FailedRequestsStopTheScrape(unittest.TestCase): return b"[]" for module in (emudeck_targets_scraper, retropie_targets_scraper): - with self.subTest(scraper=module.__name__), mock.patch.object( - module.urllib.request, "urlopen", lambda *_a, **_k: _Empty() + with self.subTest(scraper=module.__name__), mock.patch( + "urllib.request.urlopen", lambda *_a, **_k: _Empty() ), self.assertRaises(RuntimeError): module.Scraper().fetch_targets()