refactor: share the target scrapers' fetch and CLI

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 13:38:44 +01:00
1 parent 6f8b8dedb2
commit 738bb5bc07
11 files changed
+82 -238

No files matched your search

+50
View File
@@ -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] = {}
@@ -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__":
@@ -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__":
@@ -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__":
@@ -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__":
@@ -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__":
@@ -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__":
@@ -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] = {}
@@ -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__":
@@ -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__":