From 0332f6149a3954c39249675eebfcaff155cdb821 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:15:35 +0100 Subject: [PATCH] refactor: read RetroPie scripts from one tarball script_members in retropie_scraper yields every shell script of a RetroPie-Setup tarball. The platform scraper, the exporter and the target scraper read the scripts through it. The target scraper fetched one contents listing per section and about 200 raw files; it now reads the tarball of the pinned revision in one request. On the cached tarball the three produce the same module ids, scripts, BIOS-bearing scripts and targets as before. The targets file keeps its source URL. --- scripts/exporter/retropie_exporter.py | 24 ++---- scripts/scraper/retropie_scraper.py | 75 +++++++++++-------- .../targets/retropie_targets_scraper.py | 59 +++++++-------- tests/test_target_scrapers.py | 53 +++++++++---- 4 files changed, 114 insertions(+), 97 deletions(-) diff --git a/scripts/exporter/retropie_exporter.py b/scripts/exporter/retropie_exporter.py index 641138392..d15b3995f 100644 --- a/scripts/exporter/retropie_exporter.py +++ b/scripts/exporter/retropie_exporter.py @@ -13,15 +13,14 @@ to document from scratch is reported, not drafted. from __future__ import annotations -import io import re import sys -import tarfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from model.profiles import load_emulator_profiles +from scraper.retropie_scraper import script_members from .base_exporter import BaseExporter from resolve.reconcile import NativeFile, NativeSystem, Report, search_order @@ -92,22 +91,11 @@ class Exporter(BaseExporter[str]): @staticmethod def unpack(raw: bytes) -> dict[str, str]: """Keep the scriptmodules that say anything about BIOS files.""" - found: dict[str, str] = {} - with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive: - for member in archive: - if not member.isfile() or not member.name.endswith(".sh"): - continue - relative = member.name.split("/", 1)[-1] - if not relative.startswith("scriptmodules/"): - continue - handle = archive.extractfile(member) - if handle is None: - continue - text = handle.read().decode("utf-8", errors="replace") - # xm7, np2pi, quasi88 and five more write "bios". - if "bios" in text.lower(): - found[relative] = text - return found + # xm7, np2pi, quasi88 and five more write "bios". + return { + relative: text for relative, text in script_members(raw) + if relative.startswith("scriptmodules/") and "bios" in text.lower() + } def _core_index(self) -> dict[str, dict[str, str]]: """Module id (without its lr- prefix) to the profile it stands for, diff --git a/scripts/scraper/retropie_scraper.py b/scripts/scraper/retropie_scraper.py index 3ee6d0c8d..8c9107faf 100644 --- a/scripts/scraper/retropie_scraper.py +++ b/scripts/scraper/retropie_scraper.py @@ -26,6 +26,7 @@ from __future__ import annotations import io import re import tarfile +from collections.abc import Iterator from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head, fetch_bytes from .retropie_launchers import SCRIPTMODULES @@ -60,6 +61,24 @@ def core_name(module_id: str) -> str: return module_id +def fetch_archive(url: str) -> bytes: + """The RetroPie-Setup tarball at *url*, refused past MAX_ARCHIVE.""" + return fetch_bytes(url, timeout=60, max_bytes=MAX_ARCHIVE) + + +def script_members(raw: bytes) -> Iterator[tuple[str, str]]: + """(path in the repository, text) of every shell script of a + RetroPie-Setup tarball. The platform scraper, the target scraper and + the exporter read the scripts here.""" + with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive: + for member in archive: + if not member.isfile() or not member.name.endswith(".sh"): + continue + handle = archive.extractfile(member) + if handle is not None: + yield member.name.split("/", 1)[-1], handle.read().decode("utf-8", errors="replace") + + class Scraper(BaseScraper): """Scraper for the RetroPie package list.""" @@ -76,7 +95,7 @@ class Scraper(BaseScraper): self._scripts: dict[str, str] = {} def _fetch_archive(self) -> bytes: - return fetch_bytes(self.url, timeout=60, max_bytes=MAX_ARCHIVE) + return fetch_archive(self.url) def module_ids(self, payload: bytes | None = None) -> list[str]: """Every package RetroPie ships, by the id its script declares.""" @@ -85,38 +104,28 @@ class Scraper(BaseScraper): raw = payload if payload is not None else self._fetch_archive() found: set[str] = set() - with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive: - for member in archive: - if not member.isfile() or not member.name.endswith(".sh"): - continue - relative = member.name.split("/", 1)[-1] - parts = relative.split("/") - is_version_file = relative == _VERSION_FILE - is_package = ( - len(parts) == 3 - and parts[0] == "scriptmodules" - and parts[1] in _PACKAGE_DIRS - ) - is_launch_script = ( - len(parts) == 4 and parts[0] == SCRIPTMODULES and parts[1] in _SCRIPT_SECTIONS - ) - if not (is_version_file or is_package or is_launch_script): - continue - handle = archive.extractfile(member) - if handle is None: - continue - text = handle.read().decode("utf-8", errors="replace") - if is_package or is_launch_script: - self._scripts[relative] = text - if is_launch_script: - continue - match = (_VERSION if is_version_file else _MODULE_ID).search(text) - if not match: - continue - if is_version_file: - self._version = match.group(1) - else: - found.add(match.group(1)) + for relative, text in script_members(raw): + parts = relative.split("/") + is_version_file = relative == _VERSION_FILE + is_package = ( + len(parts) == 3 + and parts[0] == "scriptmodules" + and parts[1] in _PACKAGE_DIRS + ) + is_launch_script = ( + len(parts) == 4 and parts[0] == SCRIPTMODULES and parts[1] in _SCRIPT_SECTIONS + ) + if is_package or is_launch_script: + self._scripts[relative] = text + if not (is_version_file or is_package): + continue + match = (_VERSION if is_version_file else _MODULE_ID).search(text) + if not match: + continue + if is_version_file: + self._version = match.group(1) + else: + found.add(match.group(1)) if not found: raise ValueError(f"{self.url}: no rp_module_id under {SCRIPTMODULES}/") diff --git a/scripts/scraper/targets/retropie_targets_scraper.py b/scripts/scraper/targets/retropie_targets_scraper.py index 0fecefd0d..415979515 100644 --- a/scripts/scraper/targets/retropie_targets_scraper.py +++ b/scripts/scraper/targets/retropie_targets_scraper.py @@ -1,7 +1,7 @@ """Scraper for RetroPie package availability per platform. Source: https://github.com/RetroPie/RetroPie-Setup/tree//scriptmodules, -read at the revision platforms/retropie.yml was scraped at. +read from the tarball of the revision platforms/retropie.yml was scraped at. Parses rp_module_id and rp_module_flags from each scriptmodule of the package sections the platform list reads (emulators, libretrocores, ports) to determine which platforms each package supports. @@ -9,23 +9,20 @@ to determine which platforms each package supports. from __future__ import annotations -import json import re import sys +import tarfile from datetime import datetime, timezone - -from ..retropie_scraper import core_name -from . import BaseTargetScraper, fetch_text, forge_headers, target_cli +from ..retropie_scraper import SOURCE_URL, core_name, fetch_archive, script_members +from . import BaseTargetScraper, target_cli PLATFORM_NAME = "retropie" +# Written as the targets file's source: the scriptmodules tree at the pin. GITHUB_API_URL = ( "https://api.github.com/repos/RetroPie/RetroPie-Setup/contents/scriptmodules" ) -RAW_BASE_URL = ( - "https://raw.githubusercontent.com/RetroPie/RetroPie-Setup/{rev}/scriptmodules/" -) # The sections the platform scraper reads: a standalone package missing here # is filtered out of every targeted pack. PACKAGE_DIRS = ("emulators", "libretrocores", "ports") @@ -62,8 +59,11 @@ _MODULE_ID_RE = re.compile(r'rp_module_id\s*=\s*["\']([^"\']+)["\']') _MODULE_FLAGS_RE = re.compile(r'rp_module_flags\s*=\s*["\']([^"\']*)["\']') -def _fetch(url: str, accept: str = "text/plain") -> str: - return fetch_text(url, forge_headers(url, accept)) +def _fetch_archive(url: str) -> bytes: + try: + return fetch_archive(url) + except (ConnectionError, ValueError) as exc: + raise RuntimeError(str(exc)) from exc def _is_available(flags_str: str, platform: str) -> bool: @@ -112,33 +112,32 @@ class Scraper(BaseTargetScraper): self._revision = self.pinned_revision(PLATFORM_NAME) return self._revision - def _list_scriptmodules(self) -> list[str]: - """Return section/filename for every .sh of the package sections.""" - names: list[str] = [] + def _scriptmodules(self) -> dict[str, str]: + """section/filename to text for every .sh of the package sections, + read from the tarball of the pinned revision in one request.""" + url = SOURCE_URL.format(rev=self.revision) + modules: dict[str, str] = {} + try: + for relative, text in script_members(_fetch_archive(url)): + parts = relative.split("/") + if len(parts) == 3 and parts[0] == "scriptmodules" and parts[1] in PACKAGE_DIRS: + modules[f"{parts[1]}/{parts[2]}"] = text + except tarfile.TarError as exc: + raise RuntimeError(f"{url}: {exc}") from exc for section in PACKAGE_DIRS: - url = f"{self.url}/{section}?ref={self.revision}" - entries = json.loads(_fetch(url, accept="application/vnd.github+json")) - listed = [ - f"{section}/{e['name']}" for e in entries if e.get("name", "").endswith(".sh") - ] - if not listed: - raise RuntimeError(f"no scriptmodules listed at {url}") - names.extend(listed) - return names - - def _fetch_module(self, filename: str) -> str: - return _fetch(f"{RAW_BASE_URL.format(rev=self.revision)}{filename}") + if not any(name.startswith(f"{section}/") for name in modules): + raise RuntimeError(f"no scriptmodules under {section}/ in {url}") + return dict(sorted(modules.items())) def fetch_targets(self) -> dict: - print(" listing RetroPie scriptmodules...", file=sys.stderr) - filenames = self._list_scriptmodules() + print(" reading RetroPie scriptmodules...", file=sys.stderr) + modules = self._scriptmodules() # A libretro and a standalone package can share a name (lr-dosbox, # dosbox): a core list names each once. platform_cores: dict[str, set[str]] = {p: set() for p in PLATFORM_FLAGS} - for filename in filenames: - content = self._fetch_module(filename) + for filename, content in modules.items(): module_id, flags = _parse_module(content) if not module_id: print(f" warning: no rp_module_id in {filename}", file=sys.stderr) @@ -148,7 +147,7 @@ class Scraper(BaseTargetScraper): if _is_available(flags, platform): platform_cores[platform].add(core_name(module_id)) - print(f" parsed {len(filenames)} scriptmodules", file=sys.stderr) + print(f" parsed {len(modules)} scriptmodules", file=sys.stderr) targets: dict[str, dict] = {} for platform, arch in ARCH_MAP.items(): diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index ad19623f6..f1cbb598f 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -13,6 +13,7 @@ import tests import io import json import os +import tarfile import unittest import urllib.error from pathlib import Path @@ -645,32 +646,41 @@ class RetroPieModuleFlags(unittest.TestCase): self.assertIs(available(flags, platform), expected) def test_standalone_sections_are_listed_and_keep_their_id(self): - listings = { - "emulators": [{"name": "dosbox-staging.sh"}, {"name": "dosbox.sh"}], - "libretrocores": [{"name": "lr-beetle-psx.sh"}, {"name": "lr-dosbox.sh"}], - "ports": [{"name": "openbor.sh"}], - } modules = { "emulators/dosbox-staging.sh": 'rp_module_id="dosbox-staging"\nrp_module_flags="sdl2"', "libretrocores/lr-beetle-psx.sh": 'rp_module_id="lr-beetle-psx"', "libretrocores/lr-dosbox.sh": 'rp_module_id="lr-dosbox"', "emulators/dosbox.sh": 'rp_module_id="dosbox"\nrp_module_flags="sdl1 !mali"', "ports/openbor.sh": 'rp_module_id="openbor"\nrp_module_flags="sdl1 !mali !x11"', + # Neither a package section nor a package script. + "supplementary/runcommand.sh": 'rp_module_id="runcommand"', + "emulators/dosbox/launch.sh": 'rp_module_id="nested"', } - - def fake_fetch(url, **_kwargs): - section = url.split("?", 1)[0].rstrip("/").rsplit("/", 1)[-1] - if section in listings: - return json.dumps(listings[section]) - return modules[url.split("scriptmodules/", 1)[1]] - - with mock.patch.object(retropie_targets_scraper, "_fetch", fake_fetch): + archive = _retropie_tarball(modules) + with mock.patch.object(retropie_targets_scraper, "_fetch_archive", lambda _url: archive): targets = retropie_targets_scraper.Scraper().fetch_targets()["targets"] self.assertEqual( targets["rpi4"]["cores"], ["beetle_psx", "dosbox", "dosbox-staging", "openbor"] ) self.assertEqual(targets["x86_64"]["cores"], ["beetle_psx", "dosbox", "dosbox-staging"]) + def test_a_section_without_scripts_stops_the_scrape(self): + archive = _retropie_tarball({"emulators/dosbox.sh": 'rp_module_id="dosbox"'}) + with mock.patch.object(retropie_targets_scraper, "_fetch_archive", lambda _url: archive), \ + self.assertRaisesRegex(RuntimeError, "libretrocores"): + retropie_targets_scraper.Scraper().fetch_targets() + + +def _retropie_tarball(modules: dict[str, str]) -> bytes: + """A RetroPie-Setup tarball as codeload serves it, scripts under scriptmodules/.""" + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as archive: + for name, text in modules.items(): + data = text.encode() + info = tarfile.TarInfo(f"RetroPie-Setup-abc/scriptmodules/{name}") + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + return buffer.getvalue() class TargetsReadThePlatformRevision(unittest.TestCase): @@ -693,9 +703,20 @@ class TargetsReadThePlatformRevision(unittest.TestCase): def test_retropie_reads_its_codeload_pin(self): pin = retropie_targets_scraper.Scraper.pinned_revision("retropie") self.assertRegex(pin, r"^[0-9a-f]{40}$") - urls = self._urls(retropie_targets_scraper, retropie_targets_scraper.Scraper()) - self.assertTrue(urls) - self.assertTrue(all(pin in url for url in urls), urls) + seen: list[str] = [] + archive = _retropie_tarball({ + f"{section}/x.sh": 'rp_module_id="lr-mgba"' + for section in retropie_targets_scraper.PACKAGE_DIRS + }) + + def fetch(url): + seen.append(url) + return archive + + with mock.patch.object(retropie_targets_scraper, "_fetch_archive", fetch): + retropie_targets_scraper.Scraper().fetch_targets() + self.assertEqual(len(seen), 1) + self.assertIn(pin, seen[0]) def test_emudeck_steamos_reads_its_pin(self): pin = emudeck_targets_scraper.Scraper.pinned_revision("emudeck")