mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-28 20:38:52 -06:00
refactor: share the target scrapers' fetch and CLI
This commit is contained in:
1 parent
6f8b8dedb2
commit
738bb5bc07
11 files changed
+82
-238
No files matched your search
@@ -5,12 +5,17 @@ Auto-detects *_targets_scraper.py files and exposes their scrapers.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
import importlib
|
import importlib
|
||||||
import pkgutil
|
import pkgutil
|
||||||
import re
|
import re
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.github import github_token
|
||||||
|
|
||||||
|
|
||||||
class BaseTargetScraper(ABC):
|
class BaseTargetScraper(ABC):
|
||||||
"""Base class for target scrapers."""
|
"""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] = {}
|
_scrapers: dict[str, type] = {}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,14 +16,12 @@ its pack shipped the Nintendo DS firmware anyway.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, timezone
|
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 ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS
|
||||||
from ..base_scraper import fetch_bytes
|
from ..base_scraper import fetch_bytes
|
||||||
from ..batocera_scraper import _not_cores
|
from ..batocera_scraper import _not_cores
|
||||||
@@ -126,24 +124,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(
|
target_cli(Scraper, "Scrape AmberELEC per-device cores")
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ Sources (batocera-linux/buildroot, at the submodule commit the tag pins):
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
@@ -29,7 +28,7 @@ import yaml
|
|||||||
|
|
||||||
from model.safeparse import yaml_load_upstream
|
from model.safeparse import yaml_load_upstream
|
||||||
|
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, fetch_text, target_cli
|
||||||
from ..base_scraper import github_headers
|
from ..base_scraper import github_headers
|
||||||
|
|
||||||
PLATFORM_NAME = "batocera"
|
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*(?:#.*)?$")
|
_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:
|
def _fetch_present(url: str) -> str | None:
|
||||||
"""A file's text, or None when the server answers that it does not exist."""
|
"""A file's text, or None when the server answers that it does not exist."""
|
||||||
try:
|
try:
|
||||||
return _fetch(url)
|
return fetch_text(url)
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
if isinstance(e.__cause__, urllib.error.HTTPError) and e.__cause__.code == 404:
|
if isinstance(e.__cause__, urllib.error.HTTPError) and e.__cause__.code == 404:
|
||||||
return None
|
return None
|
||||||
@@ -90,7 +79,7 @@ def _fetch_present(url: str) -> str | None:
|
|||||||
|
|
||||||
|
|
||||||
def _fetch_json(url: str) -> list | dict:
|
def _fetch_json(url: str) -> list | dict:
|
||||||
text = _fetch(url, headers=github_headers())
|
text = fetch_text(url, headers=github_headers())
|
||||||
try:
|
try:
|
||||||
return json.loads(text)
|
return json.loads(text)
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
@@ -499,7 +488,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
continue
|
continue
|
||||||
seen.add(name)
|
seen.add(name)
|
||||||
try:
|
try:
|
||||||
text = _fetch(self._raw(f"configs/{name}"))
|
text = fetch_text(self._raw(f"configs/{name}"))
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
if optional:
|
if optional:
|
||||||
continue
|
continue
|
||||||
@@ -566,7 +555,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
for entry in listing.get("tree", []):
|
for entry in listing.get("tree", []):
|
||||||
if re.search(r"(^|/)retroarch\.cfg$", entry["path"]):
|
if re.search(r"(^|/)retroarch\.cfg$", entry["path"]):
|
||||||
raw = f"https://raw.githubusercontent.com/{repo}/{ref}/{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
|
return found
|
||||||
|
|
||||||
def _buildroot_rules(self) -> list[tuple[str, str, str]]:
|
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}"
|
raw = f"https://raw.githubusercontent.com/{self.BUILDROOT_REPO}/{sha}"
|
||||||
rules: list[tuple[str, str, str]] = []
|
rules: list[tuple[str, str, str]] = []
|
||||||
for path in BUILDROOT_KCONFIG:
|
for path in BUILDROOT_KCONFIG:
|
||||||
rules += _parse_owned_selects(_fetch(f"{raw}/{path}"))
|
rules += _parse_owned_selects(fetch_text(f"{raw}/{path}"))
|
||||||
return rules
|
return rules
|
||||||
|
|
||||||
def build_selection(self, tag: str | None = None) -> BuildSelection:
|
def build_selection(self, tag: str | None = None) -> BuildSelection:
|
||||||
@@ -611,7 +600,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
print(" fetching es_systems.yml...", file=sys.stderr)
|
print(" fetching es_systems.yml...", file=sys.stderr)
|
||||||
es_systems_url = self._raw(self.ES_SYSTEMS_PATH)
|
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:
|
if not es_text:
|
||||||
raise RuntimeError(f"empty es_systems.yml from {es_systems_url}")
|
raise RuntimeError(f"empty es_systems.yml from {es_systems_url}")
|
||||||
package_to_emulators = _parse_es_systems(es_text)
|
package_to_emulators = _parse_es_systems(es_text)
|
||||||
@@ -624,7 +613,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
images_by_flag = _parse_images(config_in_text)
|
images_by_flag = _parse_images(config_in_text)
|
||||||
if not images_by_flag:
|
if not images_by_flag:
|
||||||
raise RuntimeError(f"no target image list parsed from {self.CONFIG_IN_PATH}")
|
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())
|
self._shipped_retroarch_cfgs())
|
||||||
if disabled:
|
if disabled:
|
||||||
print(f" core downloader off: {disabled}", file=sys.stderr)
|
print(f" core downloader off: {disabled}", file=sys.stderr)
|
||||||
@@ -689,28 +678,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main(scraper_class: type[Scraper] = Scraper) -> None:
|
def main(scraper_class: type[Scraper] = Scraper) -> None:
|
||||||
parser = argparse.ArgumentParser(
|
target_cli(scraper_class, f"Scrape {scraper_class.PLATFORM} per-board emulator targets", "emulators")
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -10,21 +10,16 @@ Sources:
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import yaml
|
|
||||||
|
|
||||||
from core.github import github_token
|
|
||||||
from model.safeparse import yaml_load
|
from model.safeparse import yaml_load
|
||||||
|
|
||||||
from ..emudeck_launchers import SCRIPT_SUFFIXES, emulator_of_script
|
from ..emudeck_launchers import SCRIPT_SUFFIXES, emulator_of_script
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, fetch_text, forge_headers, target_cli
|
||||||
|
|
||||||
PLATFORM_NAME = "emudeck"
|
PLATFORM_NAME = "emudeck"
|
||||||
|
|
||||||
@@ -37,17 +32,7 @@ WINDOWS_API = (
|
|||||||
RETROARCH_TARGETS = Path(__file__).resolve().parents[3] / "platforms" / "targets" / "retroarch.yml"
|
RETROARCH_TARGETS = Path(__file__).resolve().parents[3] / "platforms" / "targets" / "retroarch.yml"
|
||||||
|
|
||||||
def _fetch(url: str) -> str:
|
def _fetch(url: str) -> str:
|
||||||
headers = {"User-Agent": "retrobios-scraper/1.0"}
|
return fetch_text(url, forge_headers(url))
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def _list_emuscripts(api_url: str) -> list[str]:
|
def _list_emuscripts(api_url: str) -> list[str]:
|
||||||
@@ -148,25 +133,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Scrape EmuDeck emulator targets")
|
target_cli(Scraper, "Scrape EmuDeck emulator targets", "emulators")
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -25,16 +25,14 @@ shipped their firmware anyway.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from typing import NamedTuple
|
from typing import NamedTuple
|
||||||
|
|
||||||
import yaml
|
|
||||||
|
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, target_cli
|
||||||
from ..base_scraper import fetch_bytes, github_headers
|
from ..base_scraper import fetch_bytes, github_headers
|
||||||
from ..batocera_scraper import _not_cores
|
from ..batocera_scraper import _not_cores
|
||||||
from ..emuelec_systems import (
|
from ..emuelec_systems import (
|
||||||
@@ -639,24 +637,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(
|
target_cli(Scraper, "Scrape EmuELEC per-device cores")
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -12,15 +12,13 @@ a target list, its pack shipped their firmware anyway.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import yaml
|
|
||||||
|
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, target_cli
|
||||||
from ..base_scraper import fetch_bytes, github_headers
|
from ..base_scraper import fetch_bytes, github_headers
|
||||||
|
|
||||||
PLATFORM_NAME = "lakka"
|
PLATFORM_NAME = "lakka"
|
||||||
@@ -259,24 +257,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(
|
target_cli(Scraper, "Scrape Lakka per-device cores")
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import yaml
|
|
||||||
|
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, target_cli
|
||||||
from ..base_scraper import fetch_bytes
|
from ..base_scraper import fetch_bytes
|
||||||
from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores
|
from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores
|
||||||
|
|
||||||
@@ -99,22 +97,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Scrape Recalbox per-board cores")
|
target_cli(Scraper, "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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -23,13 +23,11 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, fetch_text
|
||||||
|
|
||||||
PLATFORM_NAME = "retroarch"
|
PLATFORM_NAME = "retroarch"
|
||||||
|
|
||||||
@@ -100,20 +98,9 @@ class Scraper(BaseTargetScraper):
|
|||||||
def __init__(self, url: str = BUILDBOT_URL) -> None:
|
def __init__(self, url: str = BUILDBOT_URL) -> None:
|
||||||
super().__init__(url=url)
|
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]:
|
def _fetch_cores_for_target(self, path: str) -> list[str]:
|
||||||
url = f"{self.url}{path}/"
|
url = f"{self.url}{path}/"
|
||||||
html = self._fetch_url(url)
|
html = fetch_text(url)
|
||||||
cores: list[str] = []
|
cores: list[str] = []
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
for match in _HREF_RE.finditer(html):
|
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]:
|
def _fetch_cores_for_recipe(self, recipe_path: str) -> list[str]:
|
||||||
url = f"{RECIPE_BASE_URL}{recipe_path}"
|
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:
|
def fetch_targets(self) -> dict:
|
||||||
targets: dict[str, dict] = {}
|
targets: dict[str, dict] = {}
|
||||||
|
|||||||
@@ -9,18 +9,14 @@ to determine which platforms each package supports.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import yaml
|
|
||||||
|
|
||||||
from ..retropie_scraper import core_name
|
from ..retropie_scraper import core_name
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, fetch_text, forge_headers, target_cli
|
||||||
|
|
||||||
PLATFORM_NAME = "retropie"
|
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:
|
def _fetch(url: str, accept: str = "text/plain") -> str:
|
||||||
headers = {"User-Agent": "retrobios-scraper/1.0", "Accept": accept}
|
return fetch_text(url, forge_headers(url, 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
|
|
||||||
|
|
||||||
|
|
||||||
def _is_available(flags_str: str, platform: str) -> bool:
|
def _is_available(flags_str: str, platform: str) -> bool:
|
||||||
@@ -183,28 +167,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(
|
target_cli(Scraper, "Scrape RetroPie package targets from scriptmodules")
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -14,15 +14,13 @@ target list, its pack shipped the PS2, GameCube and PS3 firmware anyway.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import yaml
|
|
||||||
|
|
||||||
from . import BaseTargetScraper
|
from . import BaseTargetScraper, target_cli
|
||||||
from ..base_scraper import fetch_bytes, github_headers
|
from ..base_scraper import fetch_bytes, github_headers
|
||||||
from ..rocknix_packages import standalone_emulators
|
from ..rocknix_packages import standalone_emulators
|
||||||
|
|
||||||
@@ -295,22 +293,7 @@ class Scraper(BaseTargetScraper):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Scrape ROCKNIX per-device cores")
|
target_cli(Scraper, "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))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -90,8 +90,8 @@ class FailedRequestsStopTheScrape(unittest.TestCase):
|
|||||||
retropie_targets_scraper,
|
retropie_targets_scraper,
|
||||||
retroarch_targets_scraper,
|
retroarch_targets_scraper,
|
||||||
):
|
):
|
||||||
with self.subTest(scraper=module.__name__), mock.patch.object(
|
with self.subTest(scraper=module.__name__), mock.patch(
|
||||||
module.urllib.request, "urlopen", _refuse
|
"urllib.request.urlopen", _refuse
|
||||||
), self.assertRaises(RuntimeError):
|
), self.assertRaises(RuntimeError):
|
||||||
module.Scraper().fetch_targets()
|
module.Scraper().fetch_targets()
|
||||||
|
|
||||||
@@ -107,8 +107,8 @@ class FailedRequestsStopTheScrape(unittest.TestCase):
|
|||||||
return b"[]"
|
return b"[]"
|
||||||
|
|
||||||
for module in (emudeck_targets_scraper, retropie_targets_scraper):
|
for module in (emudeck_targets_scraper, retropie_targets_scraper):
|
||||||
with self.subTest(scraper=module.__name__), mock.patch.object(
|
with self.subTest(scraper=module.__name__), mock.patch(
|
||||||
module.urllib.request, "urlopen", lambda *_a, **_k: _Empty()
|
"urllib.request.urlopen", lambda *_a, **_k: _Empty()
|
||||||
), self.assertRaises(RuntimeError):
|
), self.assertRaises(RuntimeError):
|
||||||
module.Scraper().fetch_targets()
|
module.Scraper().fetch_targets()
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user