From f61c2cb7d4c23f902569be26e95634e0b0faaadf Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:18:32 +0100 Subject: [PATCH] refactor: one network layer for the scrapers Each network job had several copies. One is kept per job and every caller uses it. - Source revision: model.sourcerevision (source_revision, required_revision, platform_revision) replaces BaseTargetScraper's pattern list, the exporter's _REVISION, the four launcher_revision copies and RetroBat's own YAML reader. It reads the union of the shapes: GitHub raw, blob and tree with or without a path after the revision, GitLab raw, blob, tree and archive, codeload tar.gz and zip. The target scrapers now answer for RetroDECK, NextUI, MinUI and MyMinUI, whose tree URLs end at the commit, and the exporter reads GitLab blob and tree and codeload zip. EmuDeck and RetroBat still require a 40-hex commit, and each launcher reader requires its own repository in the URL. - Latest release: fetch_github_latest_version, type-checked, is the only lookup. mame_hash_scraper, romset_dat_importer and the Lakka target scraper call it. romset_dat_importer's NoReleaseError is gone: a release without a tag raises RuntimeError. - Tree listing: github_tree and tree_entries refuse a truncated or unreadable listing. The libretro and core-info scrapers share core_info_files and fetch_info_file, with libretro's refusal of an empty listing. The core-info listing and the RetroDECK, ROCKNIX launcher and libretro listings were not checked for truncation before. - GET: fetch_bytes is the one request path. fetch_text, fetch_present (None on 404 only), github_json and download are built on it, so every read retries 429 and 5xx, caps the body and raises FetchError, a ConnectionError carrying the HTTP status. The target scrapers' own fetch_text raised RuntimeError: they now raise FetchError, and an optional Batocera board include is skipped on 404 only, not on any failure. The exporter's originals, MiSTer, RetroPie, redump and the buildbot index go through it too. - Headers: core.upstream.forge_headers is the one builder. The token goes to api.github.com and raw.githubusercontent.com, the host compared whole, as Bearer. A URL that only names api.github.com in its query got the scrapers' token before, and profile_sync sent its token to github.com, whose release downloads redirect to asset storage with the header. Scraper reads of raw files now carry the token. - Submodule commit: submodule_commit checks that the path is a submodule. Batocera's target scraper accepted any contents answer with a sha, a directory's tree sha included. - Download: download streams through a scratch file renamed into place, retries like fetch_bytes, can keep an existing file and returns the Content-Disposition. It replaces the _download of romset_dat_importer and game_dat_importer. --- scripts/core/upstream.py | 31 +- scripts/exporter/originals.py | 31 +- scripts/model/sourcerevision.py | 68 +++++ scripts/scraper/arcade_parent_importer.py | 7 +- scripts/scraper/base_scraper.py | 269 +++++++++++++----- scripts/scraper/buildbot_system.py | 7 +- scripts/scraper/coreinfo_scraper.py | 67 ++--- scripts/scraper/emudeck_scraper.py | 11 +- scripts/scraper/emuelec_scraper.py | 13 +- scripts/scraper/game_dat_importer.py | 23 +- scripts/scraper/knulli_scraper.py | 27 +- scripts/scraper/libretro_scraper.py | 39 +-- scripts/scraper/mame_hash_scraper.py | 35 +-- scripts/scraper/minui_scraper.py | 15 +- scripts/scraper/misterfpga_scraper.py | 14 +- scripts/scraper/redump_dat_scraper.py | 11 +- scripts/scraper/retrobat_scraper.py | 17 +- scripts/scraper/retrodeck_scraper.py | 62 +--- scripts/scraper/retropie_scraper.py | 16 +- scripts/scraper/rocknix_scraper.py | 23 +- scripts/scraper/romm_scraper.py | 4 +- scripts/scraper/romset_dat_importer.py | 57 +--- scripts/scraper/shell_launchers.py | 10 +- scripts/scraper/targets/__init__.py | 52 +--- .../targets/amberelec_targets_scraper.py | 6 +- .../targets/batocera_targets_scraper.py | 63 +--- .../targets/emuelec_targets_scraper.py | 17 +- .../scraper/targets/lakka_targets_scraper.py | 27 +- .../targets/recalbox_targets_scraper.py | 4 +- .../targets/rocknix_targets_scraper.py | 26 +- tests/test_atomic_artifacts.py | 4 +- tests/test_hash_merge.py | 2 +- tests/test_launchers_emudeck.py | 11 +- tests/test_launchers_emuelec.py | 11 +- tests/test_launchers_retrobat.py | 11 +- tests/test_launchers_rocknix.py | 11 +- tests/test_retrodeck_scraper_errors.py | 6 +- tests/test_romset_recipes.py | 6 +- tests/test_scraper_contract.py | 7 +- tests/test_scraper_network.py | 264 +++++++++++++++++ tests/test_target_scrapers.py | 62 ++-- tests/test_tool_messages.py | 2 +- tests/test_upstream.py | 12 +- 43 files changed, 791 insertions(+), 670 deletions(-) create mode 100644 scripts/model/sourcerevision.py create mode 100644 tests/test_scraper_network.py diff --git a/scripts/core/upstream.py b/scripts/core/upstream.py index 96264ce5b..b56f1c0ee 100644 --- a/scripts/core/upstream.py +++ b/scripts/core/upstream.py @@ -38,9 +38,10 @@ RETRY_BACKOFF = (0.5, 2.0) # a few hundred requests into a pass and serves again a minute later. RATE_LIMIT_WAITS = (5.0, 20.0, 60.0) RATE_LIMIT_WAIT_CAP = 120.0 -GITHUB_HOSTS = frozenset( - {"github.com", "api.github.com", "raw.githubusercontent.com"} -) +# The hosts the GitHub token is sent to. github.com is not one: a release +# download there redirects to asset storage, and urllib carries the header +# across the redirect. +TOKEN_HOSTS = frozenset({"api.github.com", "raw.githubusercontent.com"}) _HOSTS: dict[str, tuple[str, str, str]] = { "github.com": ( @@ -224,21 +225,31 @@ def content_url(repo: Repo, sha: str, path: str) -> str: return f"{repo.api_base}/repos/{repo.owner}/{repo.name}/raw/{quoted}?ref={sha}" -def _headers(url: str, accept_json: bool = False) -> dict[str, str]: - """Request headers. GITHUB_TOKEN is only ever sent to GitHub.""" - headers = {"User-Agent": USER_AGENT} - if accept_json: - headers["Accept"] = "application/json" - if urllib.parse.urlsplit(url).netloc in GITHUB_HOSTS: +def forge_headers( + url: str, accept: str | None = None, user_agent: str = USER_AGENT +) -> dict[str, str]: + """Request headers for a forge URL, the GitHub token on TOKEN_HOSTS only. + + The host is compared whole: a lookalike such as github.com.example or + a query string naming api.github.com gets no token. + """ + headers = {"User-Agent": user_agent} + if accept is not None: + headers["Accept"] = accept + if urllib.parse.urlsplit(url).hostname in TOKEN_HOSTS: from core.github import github_token # GITHUB_TOKEN, else the one gh is logged in with. token = github_token() if token: - headers["Authorization"] = f"token {token}" + headers["Authorization"] = f"Bearer {token}" return headers +def _headers(url: str, accept_json: bool = False) -> dict[str, str]: + return forge_headers(url, "application/json" if accept_json else None) + + def _http_failure(url: str, exc: urllib.error.HTTPError) -> UpstreamError: """Classify an HTTP error. Only a real quota signal is fatal. diff --git a/scripts/exporter/originals.py b/scripts/exporter/originals.py index 4dfa413bf..d9326c16f 100644 --- a/scripts/exporter/originals.py +++ b/scripts/exporter/originals.py @@ -9,7 +9,6 @@ import http.client import json import re import tarfile -import urllib.request import zipfile import zlib from collections.abc import Callable @@ -17,6 +16,8 @@ from pathlib import Path from core.artifacts import file_lock, write_bytes_atomic, write_text_atomic from core.cli import InputMissing +from model.sourcerevision import source_revision +from scraper.base_scraper import fetch_bytes from .base_exporter import BaseExporter DEFAULT_CACHE = ".cache/upstream-native" @@ -141,11 +142,12 @@ def fetch( and _load_sources(index).get(key, url) == url ): return destination.read_bytes() - request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT}) - with urllib.request.urlopen(request, timeout=60) as response: - payload = response.read(_MAX_BYTES + 1) - if len(payload) > _MAX_BYTES: - raise OriginalUnreadable(f"{url}: response larger than {_MAX_BYTES} bytes") + try: + payload = fetch_bytes( + url, {"User-Agent": _USER_AGENT}, timeout=60, max_bytes=_MAX_BYTES + ) + except ValueError as exc: + raise OriginalUnreadable(f"{url}: response larger than {_MAX_BYTES} bytes") from exc # An error page served with 200 replaced a good archive and was then # served on every run: what does not read is never cached. if check is not None: @@ -220,23 +222,6 @@ def wanted_sources( } -_REVISION = ( - re.compile(r"^https://raw\.githubusercontent\.com/[^/]+/[^/]+/([^/]+)/"), - re.compile(r"^https://github\.com/[^/]+/[^/]+/(?:tree|blob)/([^/]+)"), - re.compile(r"^https://gitlab\.com/.+?/-/(?:raw|archive)/([^/]+)/"), - re.compile(r"^https://codeload\.github\.com/[^/]+/[^/]+/tar\.gz/([^/]+)$"), -) - - -def source_revision(source: str) -> str: - """The revision a platform YAML's source: URL names, '' when none.""" - for pattern in _REVISION: - match = pattern.match(source) - if match: - return match.group(1) - return "" - - def unpinned(wanted: dict[str, str], scraped: dict | None) -> list[str]: """Every file the export would read off the revision the YAML records. diff --git a/scripts/model/sourcerevision.py b/scripts/model/sourcerevision.py new file mode 100644 index 000000000..7f9f351b3 --- /dev/null +++ b/scripts/model/sourcerevision.py @@ -0,0 +1,68 @@ +"""The upstream revision a platform YAML's `source:` URL names. + +A scraper writes the URL of the file it read at the tag or commit it read +it at. The target scrapers, the launcher extractors and the exporter all +read that revision back, so the URL shapes are recognised in one place. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +from model.safeparse import yaml_load + +# Each pattern captures the revision. A trailing file path is optional: a +# tree URL names the whole repository at a commit (RetroDECK, MinUI). +_REVISION_PATTERNS = ( + re.compile(r"^https://raw\.githubusercontent\.com/[^/]+/[^/]+/([^/]+)(?:/|$)"), + re.compile(r"^https://github\.com/[^/]+/[^/]+/(?:blob|tree)/([^/]+)(?:/|$)"), + re.compile(r"^https://gitlab\.com/.+?/-/(?:raw|blob|tree|archive)/([^/]+)(?:/|$)"), + re.compile(r"^https://codeload\.github\.com/[^/]+/[^/]+/(?:tar\.gz|zip)/([^/]+)$"), +) +_COMMIT = re.compile(r"[0-9a-f]{40}") + + +def source_revision(url: str) -> str: + """The tag or commit a forge URL is read at, '' when it names none.""" + for pattern in _REVISION_PATTERNS: + match = pattern.match(url) + if match: + return match.group(1) + return "" + + +def required_revision(url: str, repo: str = "", commit: bool = False) -> str: + """The revision `url` names, ValueError when it names none. + + `repo` (owner/name) refuses a URL of another repository, `commit` + refuses a tag or a branch where only a commit pins the read. + """ + revision = source_revision(url) + if repo and f"/{repo}/" not in url: + revision = "" + if commit and not _COMMIT.fullmatch(revision): + revision = "" + if not revision: + kind = "commit" if commit else "revision" + raise ValueError(f"{url} names no {repo + ' ' if repo else ''}{kind}") + return revision + + +def platform_revision(platform_file: Path, repo: str = "", commit: bool = False) -> str: + """The revision a platform YAML was scraped at, RuntimeError when its + source names none (`repo` and `commit` as for required_revision). + + A target list or a launcher extraction describes the same release as + the platform's BIOS list: moving to a new release is a rescrape of the + platform first. + """ + with platform_file.open(encoding="utf-8") as handle: + source = str((yaml_load(handle) or {}).get("source") or "") + try: + return required_revision(source, repo, commit) + except ValueError as exc: + raise RuntimeError( + f"platforms/{platform_file.name} names no pinned revision in its " + f"source ({source!r}): rescrape the platform first" + ) from exc diff --git a/scripts/scraper/arcade_parent_importer.py b/scripts/scraper/arcade_parent_importer.py index fc2412fe1..7c9a692dc 100644 --- a/scripts/scraper/arcade_parent_importer.py +++ b/scripts/scraper/arcade_parent_importer.py @@ -55,12 +55,12 @@ from core.artifacts import write_if_changed from model.profiles import load_emulator_profiles from core.cli import run_cli from core.hashing import compute_hashes +from .base_scraper import download from .romset_dat_importer import ( LISTXML_CHUNK, MAME_LISTXML_URL, BlobMismatchError, _api_json, - _download, _listxml_opener, _machine_roms, fetch_pack, @@ -913,7 +913,8 @@ def fetch_driver_source( if not tarball.is_file(): raise FileNotFoundError(f"{tarball} is not cached") else: - _download(f"https://codeload.github.com/{slug}/tar.gz/{commit}", tarball) + download(f"https://codeload.github.com/{slug}/tar.gz/{commit}", tarball, + skip_existing=True) source = read_driver_source(tarball) if not offline: listing = _api_json(f"https://api.github.com/repos/{slug}/git/trees/{commit}") @@ -996,7 +997,7 @@ def fetch_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tuple f"https://raw.githubusercontent.com/{slug}/{commit}/" f"{urllib.parse.quote(path)}" ) - _download(url, destination) + download(url, destination, skip_existing=True) if git_blob_sha(destination.read_bytes()) != item["sha"]: destination.unlink() raise BlobMismatchError(f"{url} is not blob {item['sha']}") diff --git a/scripts/scraper/base_scraper.py b/scripts/scraper/base_scraper.py index 6be3793f6..db91261a5 100644 --- a/scripts/scraper/base_scraper.py +++ b/scripts/scraper/base_scraper.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import http.client import inspect import json import re @@ -15,10 +16,11 @@ import yaml from abc import ABC, abstractmethod from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Callable, NoReturn, Protocol +from typing import Any, Callable, NoReturn, Protocol, TypeVar from core.github import github_token -from core.artifacts import write_text_atomic +from core.artifacts import copy_stream_atomic, write_text_atomic +from core.upstream import forge_headers as upstream_headers from model.safeparse import yaml_load @@ -152,39 +154,196 @@ def _read_limited(resp: _Readable, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes: return b"".join(chunks) +SCRAPER_AGENT = "retrobios-scraper/1.0" +GITHUB_API = "https://api.github.com" + # Statuses a forge answers when it asks the client to slow down. _RETRYABLE = frozenset({429, 502, 503, 504}) +_T = TypeVar("_T") + + +class FetchError(ConnectionError): + """A GET that failed. `status` is the HTTP status the server answered, + None when no answer came (DNS, refused connection, timeout).""" + + def __init__(self, url: str, reason: object, status: int | None = None) -> None: + super().__init__(f"Failed to fetch {url}: {reason}") + self.url = url + self.status = status + + +def forge_headers(url: str, accept: str | None = None) -> dict[str, str]: + """Request headers for `url`: the GitHub token goes to GitHub's API and + raw hosts only, compared whole (core.upstream.forge_headers).""" + return upstream_headers(url, accept, SCRAPER_AGENT) + + +def github_headers() -> dict[str, str]: + """Headers for api.github.com, authenticated when a token is set. + + Anonymous calls share a quota of 60 per hour, so a scrape run after a + few others gets 403 for every request. + """ + return forge_headers(GITHUB_API, "application/vnd.github.v3+json") + + +def _open( + request: urllib.request.Request, + consume: Callable[[http.client.HTTPResponse], _T], + timeout: float, + attempts: int = 5, + sleep: Callable[[float], None] | None = None, +) -> _T: + """Open `request` and hand the response to `consume`, waiting out a rate + limit: the wait is the server's Retry-After when it gives one, else 2, + 4, 8, 16 s. A header the request does not set comes from + forge_headers().""" + url = request.full_url + for name, value in forge_headers(url).items(): + if not request.has_header(name.capitalize()): + request.add_header(name, value) + for attempt in range(attempts): + try: + with urllib.request.urlopen(request, timeout=timeout) as resp: + return consume(resp) + except urllib.error.HTTPError as e: + if e.code not in _RETRYABLE or attempt == attempts - 1: + raise FetchError(url, e, e.code) from e + retry_after = e.headers.get("Retry-After", "") if e.headers else "" + delay = float(retry_after) if retry_after.isdigit() else 2.0 ** (attempt + 1) + (sleep or time.sleep)(min(delay, 120.0)) + except (urllib.error.URLError, http.client.HTTPException, TimeoutError) as e: + raise FetchError(url, e) from e + raise AssertionError("unreachable") + def fetch_bytes( url: str, headers: dict[str, str] | None = None, attempts: int = 5, - sleep: Callable[[float], None] = time.sleep, + sleep: Callable[[float], None] | None = None, data: bytes | None = None, + timeout: float = 30, + max_bytes: int = MAX_RESPONSE_SIZE, ) -> bytes: """GET a URL, waiting out a rate limit instead of failing the scrape. GitLab answers 429 after about a hundred raw-file reads, and Recalbox's - cores live in one system.ini per system: the scrape died midway. The - wait is the server's Retry-After when it gives one, else 2, 4, 8, 16 s. + cores live in one system.ini per system: the scrape died midway. A + failure raises FetchError, a body over `max_bytes` ValueError. `headers` + add to or replace forge_headers(url). """ - request = urllib.request.Request( - url, data=data, headers={"User-Agent": "retrobios-scraper/1.0", **(headers or {})} - ) - for attempt in range(attempts): - try: - with urllib.request.urlopen(request, timeout=30) as resp: - return _read_limited(resp) - except urllib.error.HTTPError as e: - if e.code not in _RETRYABLE or attempt == attempts - 1: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - retry_after = e.headers.get("Retry-After", "") if e.headers else "" - delay = float(retry_after) if retry_after.isdigit() else 2.0 ** (attempt + 1) - sleep(min(delay, 120.0)) - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - raise AssertionError("unreachable") + request = urllib.request.Request(url, data=data, headers=headers or {}) + return _open(request, lambda resp: _read_limited(resp, max_bytes), timeout, attempts, sleep) + + +def fetch_text(url: str, headers: dict[str, str] | None = None) -> str: + """GET a file as UTF-8 text, FetchError when it cannot be read.""" + return fetch_bytes(url, headers).decode("utf-8") + + +def fetch_present(url: str, headers: dict[str, str] | None = None) -> str | None: + """A file's text, None when the server answers that it does not exist. + + Only a 404 says so: a 429, a 503 or a dropped connection is no answer + and raises, else the file would be written up as absent. + """ + try: + return fetch_text(url, headers) + except FetchError as e: + if e.status == 404: + return None + raise + + +def download( + url: str, + destination: Path, + headers: dict[str, str] | None = None, + skip_existing: bool = False, + timeout: float = 300, +) -> str: + """Stream `url` into `destination`, whole or not at all, and return the + response's Content-Disposition ("" when absent or when skipped). + + The bytes go through a scratch file renamed into place, so a reader or + an interrupted run never sees half an archive. `skip_existing` keeps a + file already there without asking the server. + """ + if skip_existing and destination.is_file(): + return "" + destination.parent.mkdir(parents=True, exist_ok=True) + + def save(resp: http.client.HTTPResponse) -> str: + copy_stream_atomic(resp, str(destination)) + return resp.headers.get("Content-Disposition", "") or "" + + return _open(urllib.request.Request(url, headers=headers or {}), save, timeout) + + +def github_json( + url: str, failure: str, timeout: float = 30, 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: + return json.loads(fetch_bytes(url, github_headers(), timeout=timeout)) + except (ConnectionError, ValueError) as e: + raise error(f"{failure}: {e}") from e + + +def github_tree(repo: str, ref: str, recursive: bool = True) -> list[dict]: + """Every entry of a GitHub repository's tree at `ref`, the whole tree or + its top level only.""" + url = f"{GITHUB_API}/repos/{repo}/git/trees/{ref}" + ("?recursive=1" if recursive else "") + return tree_entries(github_json(url, f"cannot list {repo} at {ref}"), repo, ref) + + +def tree_entries(payload: object, repo: str, ref: str) -> list[dict]: + """The entries of a git/trees answer, RuntimeError when it is not one or + comes back truncated. + + A partial tree drops files without a word, and whatever is written from + it loses them too. + """ + entries = payload.get("tree") if isinstance(payload, dict) else None + if not isinstance(payload, dict) or not isinstance(entries, list): + raise RuntimeError(f"the {repo} tree at {ref} is unreadable") + if payload.get("truncated"): + raise RuntimeError(f"the {repo} tree at {ref} is truncated") + return [entry for entry in entries + if isinstance(entry, dict) and isinstance(entry.get("path"), str)] + + +def submodule_commit(repo: str, path: str, ref: str) -> str: + """The commit the submodule at `path` of a GitHub repository pins at `ref`. + + RuntimeError when the path is not a submodule: a directory's contents + answer carries a sha too, the sha of a tree, which then read as a + commit of the submodule's repository. + """ + url = f"{GITHUB_API}/repos/{repo}/contents/{path}?ref={ref}" + found = github_json(url, f"cannot read {path} of {repo} at {ref}") + is_link = isinstance(found, dict) and found.get("type") == "submodule" + sha = found.get("sha") if is_link else None + if not isinstance(sha, str) or not sha: + raise RuntimeError(f"{path} of {repo} at {ref} is not a submodule") + return sha + + +def fetch_github_latest_version(repo: str) -> str: + """Return the tag of the latest release of a GitHub repo. + + Raises instead of returning a fallback: a platform YAML written without + the release it was read from cannot be patched back by the exporter. + """ + url = f"{GITHUB_API}/repos/{repo}/releases/latest" + release = github_json(url, f"cannot read the latest release of {repo}") + tag = release.get("tag_name") if isinstance(release, dict) else None + if not isinstance(tag, str) or not tag: + raise RuntimeError(f"the latest release of {repo} names no tag") + return tag def json_object(raw: str) -> dict | None: @@ -342,59 +501,6 @@ class BaseScraper(ABC): ... -def github_headers() -> dict[str, str]: - """Headers for api.github.com, authenticated when a token is set. - - Anonymous calls share a quota of 60 per hour, so a scrape run after a - few others gets 403 for every request. - """ - headers = { - "User-Agent": "retrobios-scraper/1.0", - "Accept": "application/vnd.github.v3+json", - } - # GITHUB_TOKEN, else the token gh is logged in with. - token = github_token() - if token: - headers["Authorization"] = f"Bearer {token}" - 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. - - Raises instead of returning a fallback: a platform YAML written without - the release it was read from cannot be patched back by the exporter. - """ - url = f"https://api.github.com/repos/{repo}/releases/latest" - 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 - - def fetch_branch_head(repo: str, branch: str) -> str: """The commit a branch of a GitHub repo points at right now. @@ -402,9 +508,10 @@ def fetch_branch_head(repo: str, branch: str) -> str: so the exporter later patches the revision the data was read from and not whatever the branch has become. Raises like the release lookup. """ - url = f"https://api.github.com/repos/{repo}/commits/{branch}" - 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 ""): + url = f"{GITHUB_API}/repos/{repo}/commits/{branch}" + commit = github_json(url, f"cannot read the head of {repo}@{branch}") + sha = commit.get("sha") if isinstance(commit, dict) else None + if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}", sha): raise RuntimeError(f"{repo}@{branch} answered no commit sha") return sha @@ -598,9 +705,13 @@ def fetch_github_latest_tag(repo: str, prefix: str = "") -> str: Raises like fetch_github_latest_version: a tag that cannot be read is not a reason to scrape a branch under it. """ - url = f"https://api.github.com/repos/{repo}/tags?per_page=50" + url = f"{GITHUB_API}/repos/{repo}/tags?per_page=50" tags = github_json(url, f"cannot read the tags of {repo}") - names = [tag["name"] for tag in tags if tag["name"].startswith(prefix)] + names = [ + tag["name"] for tag in (tags if isinstance(tags, list) else []) + if isinstance(tag, dict) and isinstance(tag.get("name"), str) + and tag["name"].startswith(prefix) + ] if not names: raise RuntimeError(f"{repo} has no tag starting with {prefix!r}") return names[0] diff --git a/scripts/scraper/buildbot_system.py b/scripts/scraper/buildbot_system.py index d4f9e493e..875cbd186 100644 --- a/scripts/scraper/buildbot_system.py +++ b/scripts/scraper/buildbot_system.py @@ -12,6 +12,7 @@ import urllib.request from model.safeparse import yaml_load from model.registry import load_versions +from .base_scraper import fetch_text log = logging.getLogger(__name__) @@ -26,11 +27,7 @@ DEFAULT_REGISTRY = "platforms/_data_dirs.yml" def fetch_index() -> set[str]: """Fetch .index from buildbot, return set of ZIP filenames.""" - req = urllib.request.Request(INDEX_URL, headers={"User-Agent": USER_AGENT}) - with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp: - return { - line.strip() for line in resp.read().decode().splitlines() if line.strip() - } + return {line.strip() for line in fetch_text(INDEX_URL).splitlines() if line.strip()} def load_tracked_entries( diff --git a/scripts/scraper/coreinfo_scraper.py b/scripts/scraper/coreinfo_scraper.py index 91b269de9..e2d0a3f39 100644 --- a/scripts/scraper/coreinfo_scraper.py +++ b/scripts/scraper/coreinfo_scraper.py @@ -17,8 +17,6 @@ import importlib import os import re import sys -import urllib.error -import urllib.request if not __package__: # Allow running directly: python scripts/scraper/coreinfo_scraper.py @@ -32,12 +30,13 @@ from .base_scraper import ( BaseScraper, BiosRequirement, fetch_github_latest_version, - github_json, + fetch_text, + github_tree, ) PLATFORM_NAME = "libretro_coreinfo" -GITHUB_API = "https://api.github.com/repos/libretro/libretro-core-info" +CORE_INFO_REPO = "libretro/libretro-core-info" RAW_BASE = "https://raw.githubusercontent.com/libretro/libretro-core-info/master" CORE_SYSTEM_MAP = { @@ -200,6 +199,29 @@ def _extract_md5_from_notes(info: dict) -> dict[str, str]: return md5_map +def core_info_files() -> list[str]: + """Paths of every .info file in libretro-core-info, RuntimeError when the + listing names none.""" + info_files = [ + entry["path"] + for entry in github_tree(CORE_INFO_REPO, "master") + if entry["path"].endswith("_libretro.info") + ] + if not info_files: + raise RuntimeError(f"no .info file in {CORE_INFO_REPO}") + return info_files + + +def fetch_info_file(filename: str) -> dict: + """A .info file of libretro-core-info, parsed. + + A file the listing names and the fetch cannot read is an error: read + as empty, the core dropped out of the result and --compare-db counted + none of its firmware missing. + """ + return _parse_info_file(fetch_text(f"{RAW_BASE}/{filename}")) + + class Scraper(BaseScraper): """Scraper for libretro-core-info firmware declarations.""" @@ -207,45 +229,14 @@ class Scraper(BaseScraper): super().__init__() self._info_files: dict[str, dict] | None = None - def _fetch_info_list(self) -> list[str]: - """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" - 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. - - A file the listing names and the fetch cannot read is an error: read - as empty, the core dropped out of the result and --compare-db - counted none of its firmware missing. - """ - url = f"{RAW_BASE}/{filename}" - try: - req = urllib.request.Request( - url, headers={"User-Agent": "retrobios-scraper/1.0"} - ) - with urllib.request.urlopen(req, timeout=15) as resp: - content = resp.read().decode("utf-8") - except (urllib.error.URLError, TimeoutError) as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - return _parse_info_file(content) - def fetch_requirements(self) -> list[BiosRequirement]: """Fetch firmware requirements from all core .info files.""" - info_files = self._fetch_info_list() + info_files = core_info_files() requirements = [] seen = set() for filename in info_files: - info = self._fetch_info_file(filename) + info = fetch_info_file(filename) firmware_list = _extract_firmware(info) if not firmware_list: @@ -315,7 +306,7 @@ def main() -> None: try: reqs = scraper.fetch_requirements() - except ConnectionError as e: + except (ConnectionError, RuntimeError) as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) diff --git a/scripts/scraper/emudeck_scraper.py b/scripts/scraper/emudeck_scraper.py index 14e7d7865..593c3e21c 100644 --- a/scripts/scraper/emudeck_scraper.py +++ b/scripts/scraper/emudeck_scraper.py @@ -15,6 +15,7 @@ import csv import io import re +from model.sourcerevision import required_revision from .base_scraper import ( BaseScraper, BiosRequirement, @@ -201,14 +202,6 @@ RE_LOCAL_HASHES = re.compile( ) -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) - if found is None: - raise ValueError(f"{url} names no EmuDeck commit") - return found.group(1) - - RETROARCH_SCRIPT = "functions/EmuScripts/emuDeckRetroArch.sh" @@ -442,7 +435,7 @@ class Scraper(BaseScraper): version = fetch_github_latest_version("dragoonDorise/EmuDeck") - revision = launcher_revision(self.checkbios_url) + revision = required_revision(self.checkbios_url, EMUDECK_REPO, commit=True) cores = self._fetch_installed_emulators(revision) standalone = [core for core in cores if core != "retroarch"] tree = RepoTree.github(EMUDECK_REPO, revision) diff --git a/scripts/scraper/emuelec_scraper.py b/scripts/scraper/emuelec_scraper.py index e8d86f6eb..066e29617 100644 --- a/scripts/scraper/emuelec_scraper.py +++ b/scripts/scraper/emuelec_scraper.py @@ -26,8 +26,7 @@ Verification (batocera-systems at the release tag): from __future__ import annotations -import re - +from model.sourcerevision import required_revision from .base_scraper import fetch_github_latest_version, fetch_text from .batocera_scraper import ( SYSTEM_SLUG_MAP as BATOCERA_SLUGS, @@ -92,14 +91,6 @@ SYSTEM_SLUG_MAP = { } -def launcher_revision(url: str) -> str: - """The tag or commit a batocera-systems URL is read at.""" - found = re.search(rf"/{REPO}/([^/]+)/packages/", url) - if found is None: - raise ValueError(f"{url} names no {REPO} revision") - return found.group(1) - - class Scraper(CheckBiosScraper): """Scraper for EmuELEC's batocera-systems.""" @@ -132,7 +123,7 @@ class Scraper(CheckBiosScraper): # Runners (retroarch, retrorun) and the launcher's own spellings are # no ES core name: only a record of an emulator no image carries goes. launchers = [ - r for r in extract_launchers(RepoTree.github(REPO, launcher_revision(self.url))) + r for r in extract_launchers(RepoTree.github(REPO, required_revision(self.url, REPO))) if not set(str(r["emulator"]).split(", ")) <= unbuilt ] return { diff --git a/scripts/scraper/game_dat_importer.py b/scripts/scraper/game_dat_importer.py index ca0893638..4a8ba94be 100644 --- a/scripts/scraper/game_dat_importer.py +++ b/scripts/scraper/game_dat_importer.py @@ -29,7 +29,6 @@ import gzip import json import re import sys -import urllib.request import zipfile from collections.abc import Iterator from dataclasses import dataclass @@ -39,12 +38,12 @@ from pathlib import Path if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path: sys.path.insert(0, _SCRIPTS_DIR) -from core.artifacts import copy_stream_atomic, write_if_changed, write_text_atomic +from core.artifacts import write_if_changed, write_text_atomic from model.safeparse import parse_untrusted_xml from model.region import REGIONS, WORLD from model.region import NOINTRO -from .base_scraper import github_headers +from .base_scraper import download, github_json SOURCES = ("no-intro", "redump") CACHE_DIR = Path(".cache") / "game-dats" @@ -286,15 +285,6 @@ class NotCachedError(RuntimeError): """An offline run asked for a download the cache does not hold.""" -def _download(url: str, destination: Path, headers: dict[str, str] | None = None) -> dict[str, str]: - """Stream url to destination and return the response headers kept.""" - destination.parent.mkdir(parents=True, exist_ok=True) - request = urllib.request.Request(url, headers={"User-Agent": "retrobios", **(headers or {})}) - with urllib.request.urlopen(request, timeout=300) as response: - copy_stream_atomic(response, str(destination)) - return {"content_disposition": response.headers.get("Content-Disposition", "")} - - def _today() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%d") @@ -309,15 +299,13 @@ def fetch_nointro(cache_dir: Path, offline: bool, refresh: bool) -> tuple[Path, return pack, meta if offline: raise NotCachedError(f"{meta_path} or its pack is not cached") - request = urllib.request.Request(NOINTRO_RELEASE_API, headers=github_headers()) - with urllib.request.urlopen(request, timeout=60) as response: - release = json.loads(response.read()) + release = github_json(NOINTRO_RELEASE_API, "cannot read the No-Intro release") asset = next(a for a in release["assets"] if a["name"] == NOINTRO_ASSET) stamp = asset["updated_at"].replace(":", "").replace("-", "") file = f"no-intro-{stamp}.zip" pack = cache_dir / file if not pack.is_file(): - _download(asset["browser_download_url"], pack) + download(asset["browser_download_url"], pack) if pack.stat().st_size != asset["size"]: pack.unlink() raise RuntimeError(f"{NOINTRO_ASSET}: size differs from the release's {asset['size']}") @@ -342,8 +330,7 @@ def fetch_redump(code: str, cache_dir: Path, offline: bool, refresh: bool) -> tu if offline: raise NotCachedError(f"{pack} is not cached") url = REDUMP_DATFILE_URL.format(code=code) - kept = _download(url, pack) - match = DISPOSITION.search(kept["content_disposition"]) + match = DISPOSITION.search(download(url, pack)) if not match: raise RuntimeError(f"{url} answered without a datfile name") meta = {"file": match["file"], "url": url, "fetched": _today()} diff --git a/scripts/scraper/knulli_scraper.py b/scripts/scraper/knulli_scraper.py index a9756d58e..06e7a0221 100644 --- a/scripts/scraper/knulli_scraper.py +++ b/scripts/scraper/knulli_scraper.py @@ -27,13 +27,11 @@ where it is older or its own. from __future__ import annotations -import urllib.error -import urllib.request - from .base_scraper import ( fetch_github_latest_version, fetch_text, optional_core_lists, + submodule_commit, ) from .batocera_scraper import ( SYSTEM_SLUG_MAP as BATOCERA_SLUGS, @@ -58,8 +56,7 @@ PLATFORM_NAME = "knulli" REPO = "knulli-cfw/knulli-linux" _RAW = "https://raw.githubusercontent.com/knulli-cfw/knulli-linux/{ref}/" -# The batocera.linux revision KNULLI's submodule pins, and its files. -_SUBMODULE = "https://api.github.com/repos/knulli-cfw/knulli-linux/contents/{path}?ref={ref}" +# The files of the batocera.linux revision KNULLI's submodule pins. _BATOCERA_RAW = "https://raw.githubusercontent.com/batocera-linux/batocera.linux/{ref}/" SOURCE_TEMPLATE = _RAW + "package/system/knulli-scripts/scripts/knulli-systems" CONFIGGEN_DEFAULTS_TEMPLATE = ( @@ -88,23 +85,6 @@ class Scraper(CheckBiosScraper): self.tag = "" if url else fetch_github_latest_version(REPO) super().__init__(url=url or SOURCE_TEMPLATE.format(ref=self.tag)) - def submodule_revision(self) -> str: - """The batocera.linux commit KNULLI's batocera submodule pins at the tag.""" - import json - - from .base_scraper import github_headers - - url = _SUBMODULE.format(path=BATOCERA_SUBMODULE, ref=self.tag) - req = urllib.request.Request(url, headers=github_headers()) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - found = json.loads(resp.read().decode("utf-8")) - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e - if not isinstance(found, dict) or found.get("type") != "submodule" or not found.get("sha"): - raise RuntimeError(f"{url}: {BATOCERA_SUBMODULE} is not a submodule") - return str(found["sha"]) - def generate_platform_yaml(self) -> dict: systems = self.platform_systems() # es_systems.yml files machine selectors and plugins under an @@ -113,7 +93,8 @@ class Scraper(CheckBiosScraper): 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() + # The batocera.linux commit KNULLI's batocera submodule pins at the tag. + revision = submodule_commit(REPO, BATOCERA_SUBMODULE, self.tag) launchers = extract_launchers( lambda path: fetch_text(_RAW.format(ref=self.tag) + path), lambda path: fetch_text(_BATOCERA_RAW.format(ref=revision) + path), diff --git a/scripts/scraper/libretro_scraper.py b/scripts/scraper/libretro_scraper.py index ce2464f7e..6032dcd14 100644 --- a/scripts/scraper/libretro_scraper.py +++ b/scripts/scraper/libretro_scraper.py @@ -8,8 +8,6 @@ Hash: SHA1 primary from __future__ import annotations -import urllib.error -import urllib.request from typing import TypedDict from .base_scraper import ( @@ -17,7 +15,6 @@ from .base_scraper import ( BiosRequirement, fetch_branch_head, fetch_github_latest_version, - github_json, systems_from_requirements, ) from .dat_parser import parse_dat, parse_dat_metadata, validate_dat_format @@ -104,21 +101,6 @@ SYSTEM_SLUG_MAP = { } -def _core_info_files() -> list[str]: - """Paths of every .info file in libretro-core-info, or RuntimeError.""" - - url = "https://api.github.com/repos/libretro/libretro-core-info/git/trees/master?recursive=1" - tree = github_json(url, "cannot list libretro-core-info", timeout=30) - info_files = [ - item["path"] - for item in tree.get("tree", []) - if item["path"].endswith("_libretro.info") - ] - if not info_files: - raise RuntimeError(f"no .info file in {url}") - return info_files - - class _ExtraSystem(TypedDict): """A system System.dat lacks, with the files RetroArch needs for it.""" @@ -196,30 +178,15 @@ class Scraper(BaseScraper): def _fetch_core_metadata(self) -> dict[str, dict]: """Fetch per-core metadata from libretro-core-info .info files.""" - from .coreinfo_scraper import CORE_SYSTEM_MAP + from .coreinfo_scraper import CORE_SYSTEM_MAP, core_info_files, fetch_info_file metadata: dict[str, dict] = {} - for filename in _core_info_files(): + for filename in core_info_files(): core_name = filename.replace("_libretro.info", "") system_slug = CORE_SYSTEM_MAP.get(core_name) if not system_slug or system_slug in metadata: continue - info_url = f"https://raw.githubusercontent.com/libretro/libretro-core-info/master/{filename}" - try: - req = urllib.request.Request( - info_url, headers={"User-Agent": "retrobios-scraper/1.0"} - ) - with urllib.request.urlopen(req, timeout=10) as resp: - content = resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise RuntimeError(f"cannot fetch {info_url}: {e}") from e - - info = {} - for line in content.split("\n"): - key, sep, value = line.strip().partition(" = ") - if sep: - info[key.strip()] = value.strip().strip('"') - + info = fetch_info_file(filename) if int(info.get("firmware_count", "0")) == 0: continue metadata[system_slug] = { diff --git a/scripts/scraper/mame_hash_scraper.py b/scripts/scraper/mame_hash_scraper.py index 8ec12fe1d..6bdfe76b6 100644 --- a/scripts/scraper/mame_hash_scraper.py +++ b/scripts/scraper/mame_hash_scraper.py @@ -15,8 +15,6 @@ import re import shutil import subprocess import sys -import urllib.error -import urllib.request from collections import Counter from datetime import datetime, timezone from pathlib import Path @@ -32,7 +30,7 @@ from model.safeparse import yaml_load from core import upstream -from .base_scraper import github_headers +from .base_scraper import download, fetch_github_latest_version from ._hash_merge import ( _build_contents, _build_source_ref, @@ -72,7 +70,8 @@ _FLOPPY_SOURCE = "src/devices/imagedev/floppy.cpp" # Where a device set goes when only machines no seed places load it: MAME # starts such a machine from its set name, as an arcade folder passes one. UNPLACED_SYSTEM = "arcade" -_REPO_URL = "https://github.com/mamedev/mame.git" +MAME_REPO = "mamedev/mame" +_REPO_URL = f"https://github.com/{MAME_REPO}.git" _STALE_HOURS = 24 @@ -158,26 +157,12 @@ def _sparse_clone(tag: str) -> None: def _get_version() -> str: - """The latest MAME release version, such as 0.289.""" - return _parse_version_tag(_get_release_tag()) - - -def _get_release_tag() -> str: - """The latest MAME release tag, from the GitHub API. + """The latest MAME release version, such as 0.289. 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. """ - url = "https://api.github.com/repos/mamedev/mame/releases/latest" - try: - 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: - raise RuntimeError(f"cannot read the MAME release from {url}: {exc}") from exc - if not tag: - raise RuntimeError(f"no tag_name in {url}") - return tag + return _parse_version_tag(fetch_github_latest_version(MAME_REPO)) def _parse_version_tag(tag: str) -> str: @@ -313,7 +298,7 @@ def _fetch_hashes(force: bool) -> dict[str, Any]: return cache try: - tag = _get_release_tag() + tag = fetch_github_latest_version(MAME_REPO) _sparse_clone(tag) bios_sets = parse_mame_source_tree(str(_CLONE_DIR)) version = _parse_version_tag(tag) @@ -406,12 +391,12 @@ def fetch_release_listxml(version: str) -> Path: 0.289 is the tag mame0289 and the asset mame0289lx.zip. """ - from .romset_dat_importer import MAME_LISTXML_URL, _download + from .romset_dat_importer import MAME_LISTXML_URL tag = "mame" + version.replace(".", "") - return _download( - MAME_LISTXML_URL.format(tag=tag), REPO_ROOT / ".cache" / "dats" / f"{tag}lx.zip" - ) + listxml = REPO_ROOT / ".cache" / "dats" / f"{tag}lx.zip" + download(MAME_LISTXML_URL.format(tag=tag), listxml, skip_existing=True) + return listxml def release_profile( diff --git a/scripts/scraper/minui_scraper.py b/scripts/scraper/minui_scraper.py index 4dfb299d3..8a79d52b6 100644 --- a/scripts/scraper/minui_scraper.py +++ b/scripts/scraper/minui_scraper.py @@ -35,6 +35,7 @@ from .base_scraper import ( fetch_branch_head, fetch_bytes, github_headers, + tree_entries, ) PLATFORM_NAME = "minui" @@ -255,10 +256,6 @@ def platform_config( } -def _fetch_with_headers(url: str, headers: dict[str, str] | None = None) -> bytes: - return fetch_bytes(url, headers=headers) - - class Scraper(BaseScraper): """Pak scraper for one frontend of the MinUI family.""" @@ -270,7 +267,7 @@ class Scraper(BaseScraper): url: str | None = None, fetch: Callable[[str, dict[str, str] | None], bytes] | None = None, ) -> None: - self._fetch = fetch or _fetch_with_headers + self._fetch = fetch or fetch_bytes self.revision = "" if url is None: self.revision = fetch_branch_head(self.variant.repo, self.variant.branch) @@ -298,11 +295,11 @@ class Scraper(BaseScraper): return self._config if not self.revision: self.revision = self.url.rstrip("/").rsplit("/", 1)[-1] - tree = self._api(f"git/trees/{self.revision}?recursive=1") - if tree.get("truncated"): - raise RuntimeError(f"{self.variant.repo}@{self.revision}: tree listing truncated") + tree = tree_entries( + self._api(f"git/trees/{self.revision}?recursive=1"), self.variant.repo, self.revision + ) paths = [ - item["path"] for item in tree.get("tree", []) + item["path"] for item in tree if item.get("type") == "blob" and ( _PAK.match(item["path"]) diff --git a/scripts/scraper/misterfpga_scraper.py b/scripts/scraper/misterfpga_scraper.py index ad9c53bb9..0b5e0055a 100644 --- a/scripts/scraper/misterfpga_scraper.py +++ b/scripts/scraper/misterfpga_scraper.py @@ -23,16 +23,14 @@ from __future__ import annotations import io import json -import urllib.error -import urllib.request import zipfile from datetime import datetime, timezone from .base_scraper import ( BaseScraper, BiosRequirement, - _read_limited, fetch_branch_head, + fetch_bytes, json_object, requirement_entry, ) @@ -132,15 +130,7 @@ class Scraper(BaseScraper): """Fetch bios_db.json.zip and return the JSON it contains.""" if self._raw_data is not None: return self._raw_data - req = urllib.request.Request( - self.url, headers={"User-Agent": "retrobios-scraper/1.0"} - ) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - payload = _read_limited(resp) - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {self.url}: {e}") from e - with zipfile.ZipFile(io.BytesIO(payload)) as archive: + with zipfile.ZipFile(io.BytesIO(fetch_bytes(self.url))) as archive: self._raw_data = archive.read(DB_MEMBER).decode("utf-8") return self._raw_data diff --git a/scripts/scraper/redump_dat_scraper.py b/scripts/scraper/redump_dat_scraper.py index 08042c4b4..5af5d306d 100644 --- a/scripts/scraper/redump_dat_scraper.py +++ b/scripts/scraper/redump_dat_scraper.py @@ -17,13 +17,11 @@ from __future__ import annotations import argparse import re import sys -import urllib.error -import urllib.request from datetime import datetime, timezone from pathlib import Path from model.dumpcatalog import write_provenance_snapshot -from .base_scraper import _read_limited +from .base_scraper import fetch_bytes from .logiqx_parser import parse_logiqx, validate_logiqx_format BASE_URL = "https://redump.info" @@ -31,12 +29,7 @@ DOWNLOADS_URL = f"{BASE_URL}/downloads" def _fetch(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 _read_limited(resp).decode("utf-8", "replace") - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e + return fetch_bytes(url).decode("utf-8", "replace") def discover_bios_datfiles(downloads_html: str) -> list[str]: diff --git a/scripts/scraper/retrobat_scraper.py b/scripts/scraper/retrobat_scraper.py index 2b484cca6..4ac76f826 100644 --- a/scripts/scraper/retrobat_scraper.py +++ b/scripts/scraper/retrobat_scraper.py @@ -11,6 +11,7 @@ from __future__ import annotations import re from pathlib import Path +from model.sourcerevision import platform_revision, required_revision from .base_scraper import ( BaseScraper, BiosRequirement, @@ -112,25 +113,13 @@ def es_systems_libretro_systems(text: str) -> dict[str, list[str]]: return {core: sorted(systems) for core, systems in sorted(found.items())} -def launcher_revision(url: str) -> str: - """The emulatorLauncher commit a source URL is pinned to.""" - found = re.search(r"/emulatorlauncher/([0-9a-f]{40})/", url) - if found is None: - raise ValueError(f"{url} names no emulatorLauncher commit") - return found.group(1) - - def pinned_revision(platform_file: Path = PLATFORM_FILE) -> str: """The emulatorLauncher commit platforms/retrobat.yml was read from. A rescrape reads this commit unless told to move, so a change to an extractor shows in the diff alone, without upstream's commits since. """ - from model.safeparse import yaml_load - - with platform_file.open(encoding="utf-8") as fh: - source = str((yaml_load(fh) or {}).get("source") or "") - return launcher_revision(source) + return platform_revision(platform_file, LAUNCHER_REPO, commit=True) def resolve_revision(revision: str | None) -> str: @@ -294,7 +283,7 @@ class Scraper(BaseScraper): "systems": systems, # The systems each libretro core runs for: its save folders. "libretro_systems": libretro_systems, - "launchers": fetch_launchers(launcher_revision(self.url)), + "launchers": fetch_launchers(required_revision(self.url, LAUNCHER_REPO, commit=True)), } diff --git a/scripts/scraper/retrodeck_scraper.py b/scripts/scraper/retrodeck_scraper.py index 26aebe5d8..409c7f670 100644 --- a/scripts/scraper/retrodeck_scraper.py +++ b/scripts/scraper/retrodeck_scraper.py @@ -31,8 +31,6 @@ import importlib import json import re import sys -import urllib.error -import urllib.request from pathlib import Path if not __package__: @@ -45,9 +43,10 @@ from .base_scraper import ( BaseScraper, BiosRequirement, fetch_branch_head, - fetch_bytes, fetch_github_latest_version, - github_headers, + fetch_present, + fetch_text, + github_tree, json_object, requirement_entry, ) @@ -56,7 +55,6 @@ from .retrodeck_launchers import extract_launchers PLATFORM_NAME = "retrodeck" COMPONENTS_REPO = "RetroDECK/components" COMPONENTS_BRANCH = "main" -COMPONENTS_API_URL = "https://api.github.com/repos/" + COMPONENTS_REPO + "/git/trees/{rev}" RAW_BASE = "https://raw.githubusercontent.com/" + COMPONENTS_REPO + "/{rev}" SKIP_DIRS = {"archive_later", "archive_old", "automation-tools", ".github"} @@ -412,31 +410,10 @@ class Scraper(BaseScraper): def _fetch_remote_manifests(self) -> list[tuple[str, dict]]: """Fetch component manifests via GitHub API.""" - from core.github import github_token - - token = github_token() - headers = {"User-Agent": "retrobios-scraper/1.0"} - if token: - headers["Authorization"] = f"token {token}" - - try: - req = urllib.request.Request( - COMPONENTS_API_URL.format(rev=self.revision), headers=headers - ) - with urllib.request.urlopen(req, timeout=30) as resp: - tree = json.loads(resp.read().decode()) - except (urllib.error.HTTPError, urllib.error.URLError) as e: - raise ConnectionError(f"Failed to fetch component tree: {e}") from e - - if tree.get("truncated"): - # A partial tree lists some components: writing the YAML from it - # drops the others' systems without a word. - raise ConnectionError("GitHub tree response truncated") - component_dirs = [ item["path"] - for item in tree.get("tree", []) - if item["type"] == "tree" and item["path"] not in SKIP_DIRS + for item in github_tree(COMPONENTS_REPO, self.revision, recursive=False) + if item.get("type") == "tree" and item["path"] not in SKIP_DIRS ] manifests: list[tuple[str, dict]] = [] @@ -446,17 +423,12 @@ class Scraper(BaseScraper): # Only a 404 says the component has no manifest. A 429, a 503 or # a dropped connection is no answer: skipping it wrote # retrodeck.yml without that component's systems, exit code 0. + text = fetch_present(url) + if text is None: + print(" no manifest", file=sys.stderr) + continue try: - req = urllib.request.Request(url, headers=headers) - with urllib.request.urlopen(req, timeout=15) as resp: - data = json.loads(resp.read().decode()) - except urllib.error.HTTPError as e: - if e.code == 404: - print(" no manifest", file=sys.stderr) - continue - raise ConnectionError(f"{url}: HTTP {e.code}") from e - except urllib.error.URLError as e: - raise ConnectionError(f"{url}: {e.reason}") from e + data = json.loads(text) except json.JSONDecodeError as e: raise ValueError(f"{url}: not JSON: {e}") from e manifests.append((comp, data)) @@ -492,17 +464,7 @@ class Scraper(BaseScraper): local = Path(self.manifests_dir) / path text = local.read_text(encoding="utf-8") if local.is_file() else None else: - url = f"{RAW_BASE.format(rev=self.revision)}/{path}" - try: - req = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(req, timeout=30) as resp: - text = resp.read().decode("utf-8") - except urllib.error.HTTPError as e: - if e.code != 404: - raise ConnectionError(f"{url}: HTTP {e.code}") from e - text = None - except urllib.error.URLError as e: - raise ConnectionError(f"{url}: {e.reason}") from e + text = fetch_present(f"{RAW_BASE.format(rev=self.revision)}/{path}") self._files[path] = text return text @@ -544,7 +506,7 @@ class Scraper(BaseScraper): (automation-tools/alchemist/desired_versions.sh, ES_DE_DESIRED_VERSION). """ tag = fetch_github_latest_version(ES_DE_REPO) - text = fetch_bytes(ES_DE_SYSTEMS_URL.format(rev=tag)).decode("utf-8") + text = fetch_text(ES_DE_SYSTEMS_URL.format(rev=tag)) return es_systems_libretro_systems(text) def generate_platform_yaml(self) -> dict: diff --git a/scripts/scraper/retropie_scraper.py b/scripts/scraper/retropie_scraper.py index 44ca42a21..3ee6d0c8d 100644 --- a/scripts/scraper/retropie_scraper.py +++ b/scripts/scraper/retropie_scraper.py @@ -26,10 +26,8 @@ from __future__ import annotations import io import re import tarfile -import urllib.error -import urllib.request -from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head +from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head, fetch_bytes from .retropie_launchers import SCRIPTMODULES from .retropie_launchers import SECTIONS as _SCRIPT_SECTIONS from .retropie_launchers import extract_launchers @@ -78,17 +76,7 @@ class Scraper(BaseScraper): self._scripts: dict[str, str] = {} def _fetch_archive(self) -> bytes: - request = urllib.request.Request( - self.url, headers={"User-Agent": "retrobios-scraper/1.0"} - ) - try: - with urllib.request.urlopen(request, timeout=60) as response: - payload = response.read(MAX_ARCHIVE + 1) - except urllib.error.URLError as exc: - raise ConnectionError(f"Failed to fetch {self.url}: {exc}") from exc - if len(payload) > MAX_ARCHIVE: - raise ValueError(f"{self.url}: response larger than {MAX_ARCHIVE} bytes") - return payload + return fetch_bytes(self.url, timeout=60, max_bytes=MAX_ARCHIVE) def module_ids(self, payload: bytes | None = None) -> list[str]: """Every package RetroPie ships, by the id its script declares.""" diff --git a/scripts/scraper/rocknix_scraper.py b/scripts/scraper/rocknix_scraper.py index 25a6b98ba..a9450ac1b 100644 --- a/scripts/scraper/rocknix_scraper.py +++ b/scripts/scraper/rocknix_scraper.py @@ -17,10 +17,12 @@ from __future__ import annotations import re +from model.sourcerevision import required_revision from .base_scraper import ( BaseScraper, BiosRequirement, fetch_github_latest_version, + fetch_text, github_json, md5_field, requirement_entry, @@ -51,14 +53,6 @@ STANDALONE_TREE_URL = ( ) -def launcher_revision(url: str) -> str: - """The tag or commit a rocknix-systems URL is read at.""" - found = re.search(r"/ROCKNIX/distribution/([^/]+)/projects/", url) - if found is None: - raise ValueError(f"{url} names no ROCKNIX/distribution revision") - return found.group(1) - - # ROCKNIX system key -> retrobios system ID SYSTEM_SLUG_MAP = { "xbox": "microsoft-xbox", @@ -161,7 +155,7 @@ class Scraper(BaseScraper): the targets scraper, where every libretro profile counted before. A standalone package no device carries is not run either. """ - builds = DeviceTargets().device_builds(self.tag or launcher_revision(self.url)) + builds = DeviceTargets().device_builds(self.tag or required_revision(self.url, GITHUB_REPO)) libretro = sorted({core for _arch, lr, _sa in builds.values() for core in lr}) carried = set(standalone_emulators(sorted({p for *_rest, sa in builds.values() for p in sa}))) standalone = [name for name in standalone if name in carried] @@ -178,15 +172,8 @@ class Scraper(BaseScraper): def _fetch_emulators_mk(self) -> str: """The package.mk that adds each emulator and core to es_systems.""" - import urllib.error - import urllib.request - url = EMULATORS_MK_URL.format(ref=self.tag or "next") - try: - with urllib.request.urlopen(url, timeout=30) as resp: - text = resp.read().decode("utf-8") - except urllib.error.URLError as e: - raise ConnectionError(f"Failed to fetch {url}: {e}") from e + text = fetch_text(url) if "add_emu_core" not in text: raise RuntimeError(f"no add_emu_core line in {url}") return text @@ -267,7 +254,7 @@ class Scraper(BaseScraper): "systems": systems, # Read at the revision the BIOS list comes from. "launchers": extract_launchers( - RepoTree.github(GITHUB_REPO, launcher_revision(self.url)) + RepoTree.github(GITHUB_REPO, required_revision(self.url, GITHUB_REPO)) ), } diff --git a/scripts/scraper/romm_scraper.py b/scripts/scraper/romm_scraper.py index 50ac6dd07..9264413af 100644 --- a/scripts/scraper/romm_scraper.py +++ b/scripts/scraper/romm_scraper.py @@ -28,8 +28,8 @@ import sys from .base_scraper import ( BaseScraper, BiosRequirement, - fetch_bytes, fetch_github_latest_version, + fetch_text, json_object, systems_from_requirements, ) @@ -247,7 +247,7 @@ class Scraper(BaseScraper): # Firmware.verify_file_hashes: size, then md5, sha1 or crc. "hash_rule": "size_and_any_hash", "cores": parse_player_cores( - fetch_bytes(CORES_URL.format(tag=self.tag)).decode("utf-8") + fetch_text(CORES_URL.format(tag=self.tag)) ), "systems": systems, } diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index e4c8e276d..e6276131a 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -32,12 +32,9 @@ from __future__ import annotations import argparse import hashlib import json -import os import re -import shutil import sys import urllib.parse -import urllib.request import zipfile from collections.abc import Callable, Iterator from dataclasses import dataclass @@ -50,6 +47,7 @@ from model.profiles import load_emulator_profiles from model.platforms import load_platform_config from core.cli import add_repo_inputs, run_cli from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot +from .base_scraper import download, fetch_github_latest_version, github_json from .logiqx_parser import LogiqxDat, parse_logiqx MAX_MEMBER_SIZE = 200 * 1024 * 1024 @@ -481,37 +479,20 @@ def _iter_dat_contents(pack: Path) -> Iterator[tuple[str, bytes]]: MAME_LISTXML_URL = ( "https://github.com/mamedev/mame/releases/download/{tag}/{tag}lx.zip" ) -MAME_LATEST_API = "https://api.github.com/repos/mamedev/mame/releases/latest" +MAME_REPO = "mamedev/mame" FBNEO_API = "https://api.github.com/repos/libretro/FBNeo" def _api_json(url: str) -> object: - from .base_scraper import github_headers - - request = urllib.request.Request(url, headers=github_headers()) - with urllib.request.urlopen(request, timeout=60) as response: - return json.load(response) - - -class NoReleaseError(ValueError): - def __init__(self) -> None: - super().__init__("the newest MAME release carries no tag") - - -def latest_mame_tag() -> str: - """Tag of the newest MAME release, the one ``--fetch`` takes by default.""" - payload = _api_json(MAME_LATEST_API) - tag = payload.get("tag_name") if isinstance(payload, dict) else None - if not tag: - raise NoReleaseError - return str(tag) + """An api.github.com answer, ConnectionError when it cannot be read.""" + return github_json(url, f"cannot read {url}", timeout=60, error=ConnectionError) def fetch_tag(source: str, requested: str) -> str: """The revision a ``--fetch`` names: bare, the newest MAME release or the tip of FBNeo's default branch.""" if source == "mame" and requested == "latest": - tag = latest_mame_tag() + tag = fetch_github_latest_version(MAME_REPO) print(f" Derniere release MAME : {tag}") return tag return requested @@ -529,25 +510,6 @@ def git_blob_sha(data: bytes) -> str: return digest.hexdigest() -def _download(url: str, destination: Path) -> Path: - """Fetch *url* to *destination* unless it is already there.""" - if destination.is_file(): - return destination - destination.parent.mkdir(parents=True, exist_ok=True) - request = urllib.request.Request(url, headers={"User-Agent": "retrobios"}) - scratch = destination.with_suffix(destination.suffix + f".{os.getpid()}.part") - try: - with urllib.request.urlopen(request, timeout=300) as response, scratch.open( - "wb" - ) as handle: - shutil.copyfileobj(response, handle) - scratch.replace(destination) - finally: - if scratch.exists(): - scratch.unlink() - return destination - - def fetch_pack( source: str, tag: str, cache_dir: Path ) -> tuple[Path, dict[str, str]]: @@ -560,10 +522,9 @@ def fetch_pack( FBNeo, whose files change under a constant header version. """ if source == "mame": - return ( - _download(MAME_LISTXML_URL.format(tag=tag), cache_dir / f"{tag}lx.zip"), - {}, - ) + listxml = cache_dir / f"{tag}lx.zip" + download(MAME_LISTXML_URL.format(tag=tag), listxml, skip_existing=True) + return listxml, {} # The revision is resolved to a commit first and everything is read at # that commit: a branch URL is served through a CDN cache, so the bytes @@ -587,7 +548,7 @@ def fetch_pack( # only while its blob sha is the one the repository lists. if destination.is_file() and git_blob_sha(destination.read_bytes()) != item["sha"]: destination.unlink() - _download(item["download_url"], destination) + download(item["download_url"], destination, skip_existing=True) if git_blob_sha(destination.read_bytes()) != item["sha"]: destination.unlink() raise BlobMismatchError( diff --git a/scripts/scraper/shell_launchers.py b/scripts/scraper/shell_launchers.py index aeb6d7097..2d29a7a4f 100644 --- a/scripts/scraper/shell_launchers.py +++ b/scripts/scraper/shell_launchers.py @@ -10,14 +10,13 @@ gone, so a rewrite upstream stops the scrape instead of publishing nothing. from __future__ import annotations -import json import re from collections.abc import Callable, Iterable from dataclasses import dataclass, field from model.sourceref import span -from .base_scraper import fetch_bytes, github_headers +from .base_scraper import fetch_bytes, github_tree from .configgen_launchers import Launcher, LauncherPatternMissing NAME = r"[A-Za-z_][A-Za-z0-9_]*" @@ -734,13 +733,12 @@ class RepoTree: return fetch_bytes(url).decode("utf-8-sig") def listdir(path: str) -> dict[str, Entry]: - url = f"https://api.github.com/repos/{repo}/git/trees/{rev}:{path}" try: - listing = json.loads(fetch_bytes(url, headers=github_headers())) - except ConnectionError as e: + listing = github_tree(repo, f"{rev}:{path}", recursive=False) + except RuntimeError as e: raise LauncherPatternMissing(path, f"directory ({e})") from e entries = {} - for item in listing.get("tree", []): + for item in listing: if item["mode"] == "120000": entries[item["path"]] = Entry("link", read(f"{path}/{item['path']}").strip()) else: diff --git a/scripts/scraper/targets/__init__.py b/scripts/scraper/targets/__init__.py index eb36a11f7..ab7e72305 100644 --- a/scripts/scraper/targets/__init__.py +++ b/scripts/scraper/targets/__init__.py @@ -8,13 +8,17 @@ 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 +from model.sourcerevision import platform_revision + +# Every target scraper reads the network through the platform scrapers' +# helpers: one retry policy, one size cap, one token rule. +from ..base_scraper import fetch_text, forge_headers + +__all__ = ["BaseTargetScraper", "discover_target_scrapers", "fetch_text", "forge_headers", + "target_cli"] class BaseTargetScraper(ABC): @@ -37,26 +41,10 @@ class BaseTargetScraper(ABC): filtered 10.1.1 systems. Moving to a new release is a rescrape of the platform first. """ - import yaml - directory = Path(platforms_dir) if platforms_dir else ( Path(__file__).resolve().parents[3] / "platforms" ) - with open(directory / f"{platform}.yml", encoding="utf-8") as handle: - source = str((yaml.safe_load(handle) or {}).get("source", "")) - for pattern in ( - r"^https://raw\.githubusercontent\.com/[^/]+/[^/]+/([^/]+)/", - r"^https://github\.com/[^/]+/[^/]+/(?:blob|tree)/([^/]+)/", - r"^https://gitlab\.com/.+?/-/(?:raw|blob|tree)/([^/]+)/", - r"^https://codeload\.github\.com/[^/]+/[^/]+/(?:tar\.gz|zip)/([^/]+)$", - ): - match = re.match(pattern, source) - if match: - return match.group(1) - raise RuntimeError( - f"platforms/{platform}.yml names no pinned revision in its source " - f"({source!r}): rescrape the platform first" - ) + return platform_revision(directory / f"{platform}.yml") def write_output(self, data: dict, output_path: str) -> None: """Write target data to YAML file.""" @@ -71,28 +59,6 @@ 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.""" diff --git a/scripts/scraper/targets/amberelec_targets_scraper.py b/scripts/scraper/targets/amberelec_targets_scraper.py index cb1df8ea8..02b3045b6 100644 --- a/scripts/scraper/targets/amberelec_targets_scraper.py +++ b/scripts/scraper/targets/amberelec_targets_scraper.py @@ -23,7 +23,7 @@ from datetime import datetime, timezone from . import BaseTargetScraper, target_cli from ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS -from ..base_scraper import fetch_bytes +from ..base_scraper import fetch_text from ..batocera_scraper import _not_cores from ..es_emulators import es_cores, xml_systems @@ -104,12 +104,12 @@ class Scraper(BaseTargetScraper): self.ref = "" def _raw(self, path: str) -> str: - return fetch_bytes(f"{RAW_BASE.format(ref=self.ref)}/{path}").decode("utf-8") + return fetch_text(f"{RAW_BASE.format(ref=self.ref)}/{path}") def fetch_targets(self) -> dict: self.ref = self.pinned_revision(PLATFORM_NAME) extra, keep = extra_cores(self._raw(META_MK)) - es_systems = fetch_bytes(ES_SYSTEMS_TEMPLATE.format(ref=self.ref)).decode("utf-8") + es_systems = fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.ref)) targets: dict[str, dict] = {} for device, arch in sorted(devices(self._raw("Makefile")).items()): cores = device_cores(es_systems, extra, device in keep) diff --git a/scripts/scraper/targets/batocera_targets_scraper.py b/scripts/scraper/targets/batocera_targets_scraper.py index 94921c641..080b5887b 100644 --- a/scripts/scraper/targets/batocera_targets_scraper.py +++ b/scripts/scraper/targets/batocera_targets_scraper.py @@ -15,11 +15,8 @@ Sources (batocera-linux/buildroot, at the submodule commit the tag pins): from __future__ import annotations -import json import re import sys -import urllib.error -import urllib.request from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from datetime import datetime, timezone @@ -28,8 +25,8 @@ import yaml from model.safeparse import yaml_load_upstream -from . import BaseTargetScraper, fetch_text, target_cli -from ..base_scraper import github_headers +from . import BaseTargetScraper, target_cli +from ..base_scraper import fetch_present, fetch_text, github_json, github_tree, submodule_commit PLATFORM_NAME = "batocera" @@ -68,24 +65,6 @@ _IF_RE = re.compile(r"^if\s+(.*)$") _DEFAULT_Y_RE = re.compile(r"^\s*default\s+y\s*(?:#.*)?$") -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_text(url) - except RuntimeError as e: - if isinstance(e.__cause__, urllib.error.HTTPError) and e.__cause__.code == 404: - return None - raise - - -def _fetch_json(url: str) -> list | dict: - text = fetch_text(url, headers=github_headers()) - try: - return json.loads(text) - except json.JSONDecodeError as e: - raise RuntimeError(f"cannot parse {url}: {e}") from e - - def _normalise_condition(raw: str) -> str: """Strip backslash-continuations and collapse whitespace.""" return re.sub(r"\\\n\s*", " ", raw).strip() @@ -454,12 +433,12 @@ class Scraper(BaseTargetScraper): def _raw(self, path: str) -> str: return f"https://raw.githubusercontent.com/{self.REPO}/{self.tag}/{path}" - def _api(self, path: str) -> str: - return f"https://api.github.com/repos/{self.REPO}/contents/{path}?ref={self.tag}" - def _list_boards(self) -> list[str]: """List *.board files from configs/ via GitHub API.""" - data = _fetch_json(self._api("configs")) + data = github_json( + f"https://api.github.com/repos/{self.REPO}/contents/configs?ref={self.tag}", + f"cannot list configs/ at {self.tag}", + ) boards = [ item["name"] for item in data @@ -487,12 +466,12 @@ class Scraper(BaseTargetScraper): if name in seen: continue seen.add(name) - try: - text = fetch_text(self._raw(f"configs/{name}")) - except RuntimeError: + found = fetch_present(self._raw(f"configs/{name}")) + if found is None: if optional: continue - raise + raise RuntimeError(f"configs/{name} is absent at {self.tag}") + text = found flags |= set(_BOARD_FLAG_RE.findall(text)) if target is None: m = _TARGET_FLAG_RE.search(text) @@ -511,10 +490,7 @@ class Scraper(BaseTargetScraper): """ bases: list[tuple[str, str]] = [] for prefix, repo in self.SUBMODULES.items(): - pin = _fetch_json(self._api(prefix.rstrip("/"))) - sha = pin.get("sha") if isinstance(pin, dict) else None - if not sha: - raise RuntimeError(f"no {prefix.rstrip('/')} submodule commit at {self.tag}") + sha = submodule_commit(self.REPO, prefix.rstrip("/"), self.tag) bases.append((prefix, f"https://raw.githubusercontent.com/{repo}/{sha}/")) def url(path: str) -> str: @@ -528,7 +504,7 @@ class Scraper(BaseTargetScraper): pending = ["Config.in"] with ThreadPoolExecutor(max_workers=8) as pool: while pending: - found = dict(zip(pending, pool.map(lambda path: _fetch_present(url(path)), pending))) + found = dict(zip(pending, pool.map(lambda path: fetch_present(url(path)), pending))) absent += [path for path, text in found.items() if text is None] files.update((path, text or "") for path, text in found.items()) pending = sorted({src for text in found.values() if text @@ -543,16 +519,10 @@ class Scraper(BaseTargetScraper): """Every retroarch.cfg the tree ships, its submodules included.""" repos = [("", self.REPO, self.tag)] for prefix, repo in self.SUBMODULES.items(): - pin = _fetch_json(self._api(prefix.rstrip("/"))) - if not isinstance(pin, dict) or not isinstance(pin.get("sha"), str): - raise RuntimeError(f"no submodule commit for {prefix} at {self.tag}") - repos.append((prefix, repo, pin["sha"])) + repos.append((prefix, repo, submodule_commit(self.REPO, prefix.rstrip("/"), self.tag))) found: dict[str, str] = {} for prefix, repo, ref in repos: - listing = _fetch_json(f"https://api.github.com/repos/{repo}/git/trees/{ref}?recursive=1") - if not isinstance(listing, dict) or listing.get("truncated"): - raise RuntimeError(f"{repo} tree at {ref} is unreadable or truncated") - for entry in listing.get("tree", []): + for entry in github_tree(repo, ref): if re.search(r"(^|/)retroarch\.cfg$", entry["path"]): raw = f"https://raw.githubusercontent.com/{repo}/{ref}/{entry['path']}" found[prefix + entry["path"]] = fetch_text(raw) @@ -560,10 +530,7 @@ class Scraper(BaseTargetScraper): def _buildroot_rules(self) -> list[tuple[str, str, str]]: """Buildroot's selects for the symbols the tree tests, at its pin.""" - pin = _fetch_json(self._api("buildroot")) - sha = pin.get("sha") if isinstance(pin, dict) else None - if not sha: - raise RuntimeError(f"no buildroot submodule commit at {self.tag}") + sha = submodule_commit(self.REPO, "buildroot", self.tag) raw = f"https://raw.githubusercontent.com/{self.BUILDROOT_REPO}/{sha}" rules: list[tuple[str, str, str]] = [] for path in BUILDROOT_KCONFIG: diff --git a/scripts/scraper/targets/emuelec_targets_scraper.py b/scripts/scraper/targets/emuelec_targets_scraper.py index 92aa1e088..825db6ec5 100644 --- a/scripts/scraper/targets/emuelec_targets_scraper.py +++ b/scripts/scraper/targets/emuelec_targets_scraper.py @@ -33,7 +33,7 @@ from typing import NamedTuple from . import BaseTargetScraper, target_cli -from ..base_scraper import fetch_bytes, github_headers +from ..base_scraper import fetch_text, github_json from ..batocera_scraper import _not_cores from ..emuelec_systems import ( BUILDS_OF, @@ -601,7 +601,7 @@ class Scraper(BaseTargetScraper): self.ref = "" def _raw(self, path: str) -> str: - return fetch_bytes(RAW.format(ref=self.ref, path=path)).decode("utf-8") + return fetch_text(RAW.format(ref=self.ref, path=path)) def fetch_targets(self) -> dict: return self.device_targets() @@ -610,15 +610,18 @@ class Scraper(BaseTargetScraper): """The targets file, read at `ref`, by default the revision platforms/emuelec.yml was scraped at.""" self.ref = ref or self.pinned_revision(PLATFORM_NAME) - release = json.loads( - fetch_bytes(RELEASE_API.format(ref=self.ref), headers=github_headers()) + release = github_json( + RELEASE_API.format(ref=self.ref), f"cannot read the {self.ref} release" ) - devices = release_devices([asset["name"] for asset in release.get("assets", [])]) + assets = release.get("assets") if isinstance(release, dict) else None + if not isinstance(assets, list): + raise RuntimeError(f"the {self.ref} release lists no asset") + devices = release_devices([asset["name"] for asset in assets]) meta = read_metapackage(self._raw(META_MK), self._raw(OPTIONS)) paths = sorted({i.path for installs in PROVIDERS.values() for i in installs}) archs = check_installs({path: self._raw(path) for path in paths}) - es_json = fetch_bytes(ES_SYSTEMS_TEMPLATE.format(ref=self.ref)).decode("utf-8") - ports = port_engines(fetch_bytes(PORTS_TEMPLATE.format(ref=self.ref)).decode("utf-8")) + es_json = fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.ref)) + ports = port_engines(fetch_text(PORTS_TEMPLATE.format(ref=self.ref))) es_mk = self._raw(ES_MK) check_names(with_ports(es_systems_for(es_json, es_mk, "Amlogic-ng"), ports)) targets: dict[str, dict] = {} diff --git a/scripts/scraper/targets/lakka_targets_scraper.py b/scripts/scraper/targets/lakka_targets_scraper.py index ca5f817d5..987c664f5 100644 --- a/scripts/scraper/targets/lakka_targets_scraper.py +++ b/scripts/scraper/targets/lakka_targets_scraper.py @@ -12,20 +12,18 @@ a target list, its pack shipped their firmware anyway. from __future__ import annotations -import json import re import sys from datetime import datetime, timezone from . import BaseTargetScraper, target_cli -from ..base_scraper import fetch_bytes, github_headers +from ..base_scraper import fetch_github_latest_version, fetch_text, github_tree PLATFORM_NAME = "lakka" REPO = "libretro/Lakka-LibreELEC" RAW_BASE = "https://raw.githubusercontent.com/" + REPO + "/{tag}" -API_BASE = "https://api.github.com/repos/" + REPO CORES_MK = "packages/lakka/libretro_cores/package.mk" _IF_RE = re.compile(r"^(if|elif)\s+\[\s+(.*?)\s+\];?\s*(?:then)?\s*$") @@ -207,33 +205,22 @@ class Scraper(BaseTargetScraper): self.paths: set[str] = set() def _raw(self, path: str) -> str: - return fetch_bytes(f"{RAW_BASE.format(tag=self.tag)}/{path}").decode("utf-8") - - def _latest_tag(self) -> str: - release = json.loads(fetch_bytes(f"{API_BASE}/releases/latest", headers=github_headers())) - tag = release.get("tag_name") if isinstance(release, dict) else None - if not tag: - raise RuntimeError(f"{REPO} names no latest release") - return tag + return fetch_text(f"{RAW_BASE.format(tag=self.tag)}/{path}") def _devices(self) -> list[tuple[str, str]]: - tree = json.loads(fetch_bytes( - f"{API_BASE}/git/trees/{self.tag}?recursive=1", headers=github_headers() - )) - if tree.get("truncated"): - raise RuntimeError(f"the {self.tag} tree listing is truncated") - self.paths = {item.get("path", "") for item in tree.get("tree", [])} + tree = github_tree(REPO, self.tag) + self.paths = {item["path"] for item in tree} found = sorted({ (match.group(1), match.group(2)) - for item in tree.get("tree", []) - if (match := re.match(r"^projects/([^/]+)/devices/([^/]+)/options$", item.get("path", ""))) + for item in tree + if (match := re.match(r"^projects/([^/]+)/devices/([^/]+)/options$", item["path"])) }) if not found: raise RuntimeError(f"no projects/*/devices/*/options at {self.tag}") return found def fetch_targets(self) -> dict: - self.tag = self._latest_tag() + self.tag = fetch_github_latest_version(REPO) cores_mk = self._raw(CORES_MK) targets: dict[str, dict] = {} for project, device in self._devices(): diff --git a/scripts/scraper/targets/recalbox_targets_scraper.py b/scripts/scraper/targets/recalbox_targets_scraper.py index 1eb9e742b..e7b767ba2 100644 --- a/scripts/scraper/targets/recalbox_targets_scraper.py +++ b/scripts/scraper/targets/recalbox_targets_scraper.py @@ -20,7 +20,7 @@ from datetime import datetime, timezone from . import BaseTargetScraper, target_cli -from ..base_scraper import fetch_bytes +from ..base_scraper import fetch_bytes, fetch_text from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores PLATFORM_NAME = "recalbox" @@ -79,7 +79,7 @@ class Scraper(BaseTargetScraper): targets: dict[str, dict] = {} for board, name in sorted(boards.items()): - defconfig = fetch_bytes(DEFCONFIG_URL.format(tag=tag, name=name)).decode("utf-8") + defconfig = fetch_text(DEFCONFIG_URL.format(tag=tag, name=name)) enabled = enabled_packages(defconfig) cores: set[str] = set() for text in inis: diff --git a/scripts/scraper/targets/rocknix_targets_scraper.py b/scripts/scraper/targets/rocknix_targets_scraper.py index 527eb57dc..33673ba29 100644 --- a/scripts/scraper/targets/rocknix_targets_scraper.py +++ b/scripts/scraper/targets/rocknix_targets_scraper.py @@ -14,20 +14,20 @@ target list, its pack shipped the PS2, GameCube and PS3 firmware anyway. from __future__ import annotations -import json import re import sys from datetime import datetime, timezone from . import BaseTargetScraper, target_cli -from ..base_scraper import fetch_bytes, github_headers +from ..base_scraper import fetch_text, github_json, github_tree from ..rocknix_packages import standalone_emulators PLATFORM_NAME = "rocknix" RAW_BASE = "https://raw.githubusercontent.com/ROCKNIX/distribution/{tag}" -GITHUB_API = "https://api.github.com/repos/ROCKNIX/distribution/contents" +REPO = "ROCKNIX/distribution" +GITHUB_API = f"https://api.github.com/repos/{REPO}/contents" EMULATORS_MK = "projects/ROCKNIX/packages/virtual/emulators/package.mk" DEVICES_DIR = "projects/ROCKNIX/devices" @@ -214,27 +214,19 @@ class Scraper(BaseTargetScraper): self.tag = "" def _raw(self, path: str) -> str: - return fetch_bytes(f"{RAW_BASE.format(tag=self.tag)}/{path}").decode("utf-8") + return fetch_text(f"{RAW_BASE.format(tag=self.tag)}/{path}") def _devices(self) -> list[str]: - import json - - listing = json.loads(fetch_bytes( - f"{GITHUB_API}/{DEVICES_DIR}?ref={self.tag}", headers=github_headers() - )) - devices = [item["name"] for item in listing if item.get("type") == "dir"] + url = f"{GITHUB_API}/{DEVICES_DIR}?ref={self.tag}" + listing = github_json(url, f"cannot list {DEVICES_DIR} at {self.tag}") + devices = [item["name"] for item in listing + if isinstance(item, dict) and item.get("type") == "dir"] if not devices: raise RuntimeError(f"no device in {DEVICES_DIR} at {self.tag}") return sorted(devices) def _tree(self) -> list[str]: - listing = json.loads(fetch_bytes( - f"https://api.github.com/repos/ROCKNIX/distribution/git/trees/{self.tag}?recursive=1", - headers=github_headers(), - )) - if listing.get("truncated"): - raise RuntimeError(f"ROCKNIX tree at {self.tag} is truncated") - return [entry["path"] for entry in listing.get("tree", [])] + return [entry["path"] for entry in github_tree(REPO, self.tag)] def device_builds(self, tag: str | None = None) -> dict[str, tuple[str, list[str], list[str]]]: """{device: (architecture, libretro cores, standalone packages)}. diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index d3c902504..a49a2b2df 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -15,6 +15,7 @@ import os import sys import tempfile import unittest +import urllib.request from pathlib import Path from unittest import mock @@ -131,7 +132,6 @@ class TheNativeIndexKeepsEveryPlatform(unittest.TestCase): import io import json - from exporter import originals from exporter.originals import SOURCES_INDEX, fetch with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as directory: @@ -150,7 +150,7 @@ class TheNativeIndexKeepsEveryPlatform(unittest.TestCase): return Response(b"payload") with mock.patch.object( - originals.urllib.request, "urlopen", other_run_records_meanwhile + urllib.request, "urlopen", other_run_records_meanwhile ): fetch("https://a", root / "batocera" / "file", index) recorded = json.loads(index.read_text()) diff --git a/tests/test_hash_merge.py b/tests/test_hash_merge.py index b6980a64c..6b20399f5 100644 --- a/tests/test_hash_merge.py +++ b/tests/test_hash_merge.py @@ -434,7 +434,7 @@ class TheScraperClonesTheReleaseItLabels(unittest.TestCase): from scripts.scraper import mame_hash_scraper as scraper calls: list[list[str]] = [] - with mock.patch.object(scraper, "_get_release_tag", return_value="mame0289"), \ + with mock.patch.object(scraper, "fetch_github_latest_version", return_value="mame0289"), \ mock.patch.object(scraper, "_run_git", side_effect=lambda args, cwd=None: calls.append(args)), \ mock.patch.object(scraper, "parse_mame_source_tree", diff --git a/tests/test_launchers_emudeck.py b/tests/test_launchers_emudeck.py index 4a1b85dfb..1108503cc 100644 --- a/tests/test_launchers_emudeck.py +++ b/tests/test_launchers_emudeck.py @@ -17,7 +17,7 @@ from pathlib import Path import yaml from scraper import emudeck_launchers as el -from scraper.emudeck_scraper import launcher_revision +from model.sourcerevision import required_revision from scraper.shell_launchers import LauncherPatternMissing, RepoTree, words REPO_ROOT = Path(__file__).resolve().parent.parent @@ -234,6 +234,11 @@ def tree(**scripts: str) -> RepoTree: return RepoTree.from_files(files) +def revision_of(url: str) -> str: + return required_revision(url, repo="dragoonDorise/EmuDeck", commit=True) + + + class WrittenIntoTheConfig(unittest.TestCase): def test_ares_firmware_follows_the_rewritten_prefix(self): colecovision, pcecd = (r.entry() for r in el.ares(tree(**{"emuDeckares.sh": ARES_SH}))) @@ -412,9 +417,9 @@ class Helpers(unittest.TestCase): "https://raw.githubusercontent.com/dragoonDorise/EmuDeck/" "dddb30229adbbd54d5ff7283cfd70e11c4322c26/functions/checkBIOS.sh" ) - self.assertEqual(launcher_revision(url), "dddb30229adbbd54d5ff7283cfd70e11c4322c26") + self.assertEqual(revision_of(url), "dddb30229adbbd54d5ff7283cfd70e11c4322c26") with self.assertRaises(ValueError): - launcher_revision( + revision_of( "https://raw.githubusercontent.com/dragoonDorise/EmuDeck/main/functions/checkBIOS.sh" ) diff --git a/tests/test_launchers_emuelec.py b/tests/test_launchers_emuelec.py index 620be9c78..74401d0a5 100644 --- a/tests/test_launchers_emuelec.py +++ b/tests/test_launchers_emuelec.py @@ -18,7 +18,7 @@ from pathlib import Path import yaml from scraper import emuelec_launchers as el -from scraper.emuelec_scraper import launcher_revision +from model.sourcerevision import required_revision from scraper.shell_launchers import LauncherPatternMissing, RepoTree REPO_ROOT = Path(__file__).resolve().parent.parent @@ -452,6 +452,11 @@ def ref(path: str, lines: str) -> str: return f"{path}:{lines}" +def revision_of(url: str) -> str: + return required_revision(url, repo="EmuELEC/EmuELEC") + + + class Dispatch(unittest.TestCase): def test_each_script_is_named_after_the_core_that_starts_it(self): runs = el.Runs(tree()) @@ -680,11 +685,11 @@ class Revision(unittest.TestCase): "https://raw.githubusercontent.com/EmuELEC/EmuELEC/v4.8/" "packages/sx05re/emuelec/bin/batocera/batocera-systems" ) - self.assertEqual(launcher_revision(url), "v4.8") + self.assertEqual(revision_of(url), "v4.8") def test_a_url_without_a_revision_raises(self): with self.assertRaises(ValueError): - launcher_revision("https://example.org/batocera-systems") + revision_of("https://example.org/batocera-systems") class PlatformRecords(unittest.TestCase): diff --git a/tests/test_launchers_retrobat.py b/tests/test_launchers_retrobat.py index 78f6a8e77..11367fea7 100644 --- a/tests/test_launchers_retrobat.py +++ b/tests/test_launchers_retrobat.py @@ -17,7 +17,7 @@ from pathlib import Path from scraper import retrobat_launchers as rl from scraper.csharp_source import LauncherPatternMissing, Source, render_concat -from scraper.retrobat_scraper import launcher_revision +from model.sourcerevision import required_revision REPO_ROOT = Path(__file__).resolve().parent.parent @@ -354,6 +354,11 @@ def _psx_sources() -> dict[str, Source]: ) +def revision_of(url: str) -> str: + return required_revision(url, repo="RetroBat-Official/emulatorlauncher", commit=True) + + + class NamesInLauncherOrder(unittest.TestCase): def test_ares_fallback_chain_keeps_its_order(self): [record] = rl.ares(_sources(**{f"{G}/Ares.Generator.cs": ARES})) @@ -1598,9 +1603,9 @@ class Helpers(unittest.TestCase): "https://raw.githubusercontent.com/RetroBat-Official/emulatorlauncher/" "48cdc61623c5943bb17647b80a60d32d395c3725/batocera-systems/Resources/batocera-systems.json" ) - self.assertEqual(launcher_revision(url), "48cdc61623c5943bb17647b80a60d32d395c3725") + self.assertEqual(revision_of(url), "48cdc61623c5943bb17647b80a60d32d395c3725") with self.assertRaises(ValueError): - launcher_revision("https://example.test/master/batocera-systems.json") + revision_of("https://example.test/master/batocera-systems.json") if __name__ == "__main__": diff --git a/tests/test_launchers_rocknix.py b/tests/test_launchers_rocknix.py index a27647f08..54a3ecc72 100644 --- a/tests/test_launchers_rocknix.py +++ b/tests/test_launchers_rocknix.py @@ -18,7 +18,7 @@ from pathlib import Path import yaml from scraper import rocknix_launchers as rl -from scraper.rocknix_scraper import launcher_revision +from model.sourcerevision import required_revision from scraper.shell_launchers import LauncherPatternMissing, RepoTree REPO_ROOT = Path(__file__).resolve().parent.parent @@ -311,6 +311,11 @@ def by(records: list[dict], emulator: str) -> list[dict]: return [r for r in records if r["emulator"] == emulator] +def revision_of(url: str) -> str: + return required_revision(url, repo="ROCKNIX/distribution") + + + class ConfigsPerDevice(unittest.TestCase): def test_a_device_appears_only_where_configs_differ(self): records = [r.entry() for r in rl.melonds(melonds_tree())] @@ -654,11 +659,11 @@ class Revision(unittest.TestCase): "https://raw.githubusercontent.com/ROCKNIX/distribution/20261001/" "projects/ROCKNIX/packages/rocknix/sources/scripts/rocknix-systems" ) - self.assertEqual(launcher_revision(url), "20261001") + self.assertEqual(revision_of(url), "20261001") def test_a_url_without_a_revision_raises(self): with self.assertRaises(ValueError): - launcher_revision("https://rocknix.org/") + revision_of("https://rocknix.org/") class PlatformRecords(unittest.TestCase): diff --git a/tests/test_retrodeck_scraper_errors.py b/tests/test_retrodeck_scraper_errors.py index 6239482e3..03db9f83b 100644 --- a/tests/test_retrodeck_scraper_errors.py +++ b/tests/test_retrodeck_scraper_errors.py @@ -43,7 +43,9 @@ def _opener(failure): class ManifestErrors(unittest.TestCase): def fetch(self, failure): - with mock.patch("urllib.request.urlopen", _opener(failure)): + # A 503 is retried after a wait: the waits are skipped, not the retries. + with mock.patch("urllib.request.urlopen", _opener(failure)), \ + mock.patch("time.sleep"): return Scraper()._fetch_remote_manifests() def test_a_server_error_stops_the_scrape(self): @@ -76,7 +78,7 @@ class ManifestErrors(unittest.TestCase): def test_a_truncated_tree_stops_the_scrape(self): TREE["truncated"] = True self.addCleanup(TREE.pop, "truncated") - with self.assertRaises(ConnectionError): + with self.assertRaises(RuntimeError): self.fetch(None) diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index 47485161c..2bb10b1ab 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -861,15 +861,15 @@ class FbneoFetchReadsOneRevision(unittest.TestCase): "download_url": "https://raw.githubusercontent.com/libretro/FBNeo/c0ffee/dats/Demo.dat", }] - def _download(self, url: str, destination: Path) -> Path: + def _download(self, url: str, destination: Path, **_options: object) -> str: destination.write_bytes(self.served) - return destination + return "" def _patched(self): from unittest import mock return mock.patch.multiple( - self.importer, _api_json=self._api, _download=self._download + self.importer, _api_json=self._api, download=self._download ) def test_bytes_that_are_not_the_listed_blob_are_refused(self): diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index 84d692930..a14fb36e6 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -23,6 +23,7 @@ import urllib.error from pathlib import Path from unittest import mock +from model.sourcerevision import source_revision from scraper import emudeck_scraper, libretro_scraper from scraper.base_scraper import ( BaseScraper, @@ -685,7 +686,7 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase): "urllib.request.urlopen", self._refuse ): self.assertEqual( - module.launcher_revision(module.Scraper().url), module.pinned_revision() + source_revision(module.Scraper().url), module.pinned_revision() ) def test_a_branch_read_records_its_commit(self): @@ -766,7 +767,7 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase): scraper = coreinfo_scraper.Scraper() with mock.patch.object( - scraper, "_fetch_info_list", return_value=["mednafen_psx_libretro.info"] + coreinfo_scraper, "core_info_files", return_value=["mednafen_psx_libretro.info"] ), mock.patch("urllib.request.urlopen", self._refuse), self.assertRaises( ConnectionError ): @@ -1032,7 +1033,7 @@ class HashScraperRefusesAnEmptyRead(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: cache = Path(tmp) / "mame-hashes.json" with mock.patch.object(m, "_CACHE_PATH", cache), \ - mock.patch.object(m, "_get_release_tag", return_value="mame0289"), \ + mock.patch.object(m, "fetch_github_latest_version", return_value="mame0289"), \ mock.patch.object(m, "_sparse_clone"), \ mock.patch.object(m, "_cleanup"), \ mock.patch.object(m, "_get_commit", return_value="abc"), \ diff --git a/tests/test_scraper_network.py b/tests/test_scraper_network.py new file mode 100644 index 000000000..11b941bfd --- /dev/null +++ b/tests/test_scraper_network.py @@ -0,0 +1,264 @@ +"""The scrapers' shared network helpers and the source revision reader (no network).""" + +from __future__ import annotations + +import tests + +import io +import json +import os +import tempfile +import unittest +import urllib.error +from pathlib import Path +from unittest import mock + +import yaml + +from model.sourcerevision import platform_revision, required_revision, source_revision +from scraper import base_scraper +from scraper.base_scraper import ( + FetchError, + download, + fetch_bytes, + fetch_github_latest_version, + fetch_present, + forge_headers, + github_tree, + submodule_commit, +) + +REPO_ROOT = Path(__file__).resolve().parent.parent +TMP_ROOT = REPO_ROOT / "tmp" +SHA = "0123456789abcdef0123456789abcdef01234567" + + +class _Response(io.BytesIO): + def __init__(self, body: bytes, headers: dict[str, str] | None = None) -> None: + super().__init__(body) + self.headers = headers or {} + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def _answer(*replies: object): + """An urlopen that gives each reply in turn: bytes, a dict body or an + HTTP status to raise.""" + pending = list(replies) + seen: list[object] = [] + + def urlopen(request, timeout=None): + seen.append(request) + reply = pending.pop(0) + if isinstance(reply, int): + raise urllib.error.HTTPError(request.full_url, reply, "status", {}, None) + if isinstance(reply, (dict, list)): + reply = json.dumps(reply).encode() + return _Response(reply, {"Content-Disposition": 'attachment; filename="a.zip"'}) + + urlopen.seen = seen + return urlopen + + +class SourceRevisionReadsEveryShape(unittest.TestCase): + SHAPES = { + f"https://raw.githubusercontent.com/o/r/{SHA}/dir/file.json": SHA, + f"https://raw.githubusercontent.com/o/r/{SHA}": SHA, + "https://github.com/o/r/blob/v2/src/f.cs": "v2", + f"https://github.com/o/r/tree/{SHA}": SHA, + f"https://github.com/o/r/tree/{SHA}/": SHA, + "https://gitlab.com/g/sub/r/-/raw/10.1.1/a/b.xml": "10.1.1", + "https://gitlab.com/g/r/-/blob/main/a.txt": "main", + "https://gitlab.com/g/r/-/tree/v1": "v1", + "https://gitlab.com/g/r/-/archive/v1/r-v1.tar.gz": "v1", + f"https://codeload.github.com/o/r/tar.gz/{SHA}": SHA, + "https://codeload.github.com/o/r/zip/v3": "v3", + } + + def test_each_url_shape(self): + for url, revision in self.SHAPES.items(): + with self.subTest(url=url): + self.assertEqual(source_revision(url), revision) + + def test_a_url_without_a_revision(self): + for url in ("https://github.com/emulatorjs/emulatorjs", "https://example.org/x", + "https://github.com.example/o/r/blob/v2/f"): + with self.subTest(url=url): + self.assertEqual(source_revision(url), "") + + def test_every_registered_platform_names_its_revision(self): + """The target scrapers raised for RetroDECK and NextUI, whose tree + URLs carry no path after the commit, while the exporter answered.""" + registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) + checked = 0 + for name in registry["platforms"]: + path = REPO_ROOT / "platforms" / f"{name}.yml" + source = (yaml.safe_load(path.read_text()) or {}).get("source") if path.is_file() else None + if not source: + continue + with self.subTest(platform=name): + self.assertTrue(source_revision(source), source) + self.assertEqual(platform_revision(path), source_revision(source)) + checked += 1 + self.assertGreater(checked, 15) + + def test_a_repository_and_a_commit_can_be_required(self): + url = f"https://raw.githubusercontent.com/o/r/{SHA}/f" + self.assertEqual(required_revision(url, "o/r", commit=True), SHA) + for bad in ( + lambda: required_revision(url, "o/other"), + lambda: required_revision("https://raw.githubusercontent.com/o/r/main/f", commit=True), + lambda: required_revision("https://example.org/f"), + ): + with self.assertRaises(ValueError): + bad() + + def test_a_platform_without_a_revision_raises(self): + with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: + path = Path(tmp, "p.yml") + path.write_text("source: https://github.com/emulatorjs/emulatorjs\n") + with self.assertRaises(RuntimeError): + platform_revision(path) + + +class TheTokenGoesToGitHubOnly(unittest.TestCase): + def setUp(self): + patcher = mock.patch.dict(os.environ, {"GITHUB_TOKEN": "t0k"}) + patcher.start() + self.addCleanup(patcher.stop) + + def test_api_and_raw_hosts(self): + for url in ("https://api.github.com/repos/o/r", "https://raw.githubusercontent.com/o/r/x/f"): + self.assertEqual(forge_headers(url)["Authorization"], "Bearer t0k") + + def test_other_hosts(self): + for url in ("https://github.com/o/r/releases/download/v1/a.zip", + "https://gitlab.com/api/v4/projects/1", + "https://evil.example/?u=api.github.com", + "https://api.github.com.evil.example/x"): + with self.subTest(url=url): + self.assertNotIn("Authorization", forge_headers(url)) + + def test_every_fetch_carries_it(self): + opener = _answer(b"x") + with mock.patch("urllib.request.urlopen", opener): + fetch_bytes("https://api.github.com/repos/o/r") + self.assertEqual(opener.seen[0].get_header("Authorization"), "Bearer t0k") + + +class FetchFailures(unittest.TestCase): + def test_the_status_is_kept(self): + with mock.patch("urllib.request.urlopen", _answer(403)), \ + self.assertRaises(FetchError) as caught: + fetch_bytes("https://x.example/f") + self.assertEqual(caught.exception.status, 403) + self.assertIsInstance(caught.exception, ConnectionError) + + def test_only_a_404_is_absent(self): + with mock.patch("urllib.request.urlopen", _answer(404)): + self.assertIsNone(fetch_present("https://x.example/f")) + with mock.patch("urllib.request.urlopen", _answer(503, 503, 503, 503, 503)), \ + mock.patch("time.sleep"), self.assertRaises(FetchError): + fetch_present("https://x.example/f") + + def test_a_body_over_the_cap_raises(self): + with mock.patch("urllib.request.urlopen", _answer(b"x" * 10)), \ + self.assertRaises(ValueError): + fetch_bytes("https://x.example/f", max_bytes=5) + + +class GitHubAnswers(unittest.TestCase): + def test_a_truncated_tree_raises(self): + with mock.patch("urllib.request.urlopen", _answer({"tree": [], "truncated": True})), \ + self.assertRaises(RuntimeError): + github_tree("o/r", "v1") + + def test_a_body_that_is_no_tree_raises(self): + with mock.patch("urllib.request.urlopen", _answer([])), self.assertRaises(RuntimeError): + github_tree("o/r", "v1") + + def test_the_tree_entries(self): + tree = {"tree": [{"path": "a", "type": "blob"}, {"type": "blob"}], "truncated": False} + opener = _answer(tree) + with mock.patch("urllib.request.urlopen", opener): + self.assertEqual(github_tree("o/r", "v1", recursive=False), [tree["tree"][0]]) + self.assertTrue(opener.seen[0].full_url.endswith("/git/trees/v1")) + + def test_a_directory_is_not_a_submodule(self): + """A directory's contents answer has a sha too, the sha of a tree.""" + with mock.patch("urllib.request.urlopen", _answer({"type": "dir", "sha": SHA})), \ + self.assertRaises(RuntimeError): + submodule_commit("o/r", "sub", "v1") + with mock.patch("urllib.request.urlopen", _answer({"type": "submodule", "sha": SHA})): + self.assertEqual(submodule_commit("o/r", "sub", "v1"), SHA) + + def test_a_release_without_a_tag_raises(self): + for body in ({}, {"tag_name": 5}, [], {"tag_name": ""}): + with self.subTest(body=body), mock.patch("urllib.request.urlopen", _answer(body)), \ + self.assertRaises(RuntimeError): + fetch_github_latest_version("o/r") + with mock.patch("urllib.request.urlopen", _answer({"tag_name": "v9"})): + self.assertEqual(fetch_github_latest_version("o/r"), "v9") + + +class Downloads(unittest.TestCase): + def test_written_whole_with_its_disposition(self): + with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: + target = Path(tmp, "sub", "a.zip") + with mock.patch("urllib.request.urlopen", _answer(503, b"payload")), \ + mock.patch("time.sleep"): + disposition = download("https://x.example/a.zip", target) + self.assertEqual(target.read_bytes(), b"payload") + self.assertIn("a.zip", disposition) + self.assertEqual(sorted(p.name for p in target.parent.iterdir()), ["a.zip"]) + + def test_a_failure_leaves_nothing(self): + with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: + target = Path(tmp, "a.zip") + with mock.patch("urllib.request.urlopen", _answer(403)), \ + self.assertRaises(FetchError): + download("https://x.example/a.zip", target) + self.assertEqual(list(Path(tmp).iterdir()), []) + + def test_an_existing_file_is_kept_when_asked(self): + with tempfile.TemporaryDirectory(dir=TMP_ROOT) as tmp: + target = Path(tmp, "a.zip") + target.write_bytes(b"cached") + with mock.patch("urllib.request.urlopen", _answer(403)): + self.assertEqual(download("https://x.example/a.zip", target, skip_existing=True), "") + self.assertEqual(target.read_bytes(), b"cached") + + +class OneImplementationPerJob(unittest.TestCase): + """Each job had its own copy: a revision reader in six modules, a + release lookup in four, a tree listing in seven.""" + + def test_no_scraper_keeps_its_own_copy(self): + scraper_dir = REPO_ROOT / "scripts" / "scraper" + needles = ("def launcher_revision", "releases/latest", "urlopen(", "?recursive=1", + "def _download") + found = [ + f"{path.relative_to(scraper_dir)}: {needle}" + for path in sorted(scraper_dir.rglob("*.py")) + if path.name != "base_scraper.py" + for needle in needles + if needle in path.read_text(encoding="utf-8") + ] + # buildbot_system asks for ETags with HEAD requests, which no shared + # helper sends. MinUI reads through a fetch its tests replace, and + # hands the answer to tree_entries. + self.assertEqual(found, ["buildbot_system.py: urlopen(", "minui_scraper.py: ?recursive=1"]) + + def test_the_target_package_reads_through_the_platform_helpers(self): + from scraper import targets + + self.assertIs(targets.fetch_text, base_scraper.fetch_text) + self.assertIs(targets.forge_headers, base_scraper.forge_headers) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 2e8c45dd7..ad19623f6 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -10,6 +10,7 @@ from __future__ import annotations import tests +import io import json import os import unittest @@ -31,9 +32,9 @@ def _refuse(*_args, **_kwargs): raise urllib.error.HTTPError("https://api.github.com/x", 403, "rate limited", {}, None) -class _Body: +class _Body(io.BytesIO): def __init__(self, body: str | bytes): - self.body = body.encode() if isinstance(body, str) else body + super().__init__(body.encode() if isinstance(body, str) else body) def __enter__(self): return self @@ -41,9 +42,6 @@ class _Body: def __exit__(self, *exc): return False - def read(self): - return self.body - def _serve_batocera(boards: list[str], refuse_board: bool): def urlopen(request, *_a, **_k): @@ -53,7 +51,7 @@ def _serve_batocera(boards: list[str], refuse_board: bool): if "/contents/configs" in url: return _Body(json.dumps([{"name": b} for b in boards]).encode()) if "/contents/buildroot" in url: - return _Body(b'{"sha": "0123abc"}') + return _Body(b'{"type": "submodule", "sha": "0123abc"}') if url.endswith("x86_wow64.board"): # Builds the 32-bit Wine package, not an image. return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86=y\n") @@ -92,23 +90,13 @@ class FailedRequestsStopTheScrape(unittest.TestCase): ): with self.subTest(scraper=module.__name__), mock.patch( "urllib.request.urlopen", _refuse - ), self.assertRaises(RuntimeError): + ), self.assertRaises((RuntimeError, ConnectionError)): module.Scraper().fetch_targets() def test_an_empty_listing_is_not_a_target(self): - class _Empty: - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def read(self): - return b"[]" - for module in (emudeck_targets_scraper, retropie_targets_scraper): with self.subTest(scraper=module.__name__), mock.patch( - "urllib.request.urlopen", lambda *_a, **_k: _Empty() + "urllib.request.urlopen", lambda *_a, **_k: _Body(b"[]") ), self.assertRaises(RuntimeError): module.Scraper().fetch_targets() @@ -116,16 +104,13 @@ class FailedRequestsStopTheScrape(unittest.TestCase): """No board listed, or one board unreadable, used to print a warning and write the targets file without those boards.""" for boards, refuse_board in (([], False), (["batocera-x86_64.board"], True)): - with self.subTest(boards=boards), mock.patch.object( - batocera_targets_scraper.urllib.request, - "urlopen", - _serve_batocera(boards, refuse_board), - ), self.assertRaises(RuntimeError): + with self.subTest(boards=boards), mock.patch( + "urllib.request.urlopen", _serve_batocera(boards, refuse_board), + ), self.assertRaises((RuntimeError, ConnectionError)): batocera_targets_scraper.Scraper().fetch_targets() - with mock.patch.object( - batocera_targets_scraper.urllib.request, - "urlopen", + with mock.patch( + "urllib.request.urlopen", _serve_batocera(["batocera-x86_64.board", "batocera-x86_wow64.board"], False), ): targets = batocera_targets_scraper.Scraper().fetch_targets()["targets"] @@ -440,8 +425,8 @@ class KnulliPerBoard(unittest.TestCase): names = [p.removeprefix("configs/") for p in self.FILES if p.startswith("configs/")] exact = { f"{api}configs?ref={pin}": json.dumps([{"name": n} for n in names]), - f"{api}buildroot?ref={pin}": '{"sha": "c2d7985b"}', - f"{api}batocera?ref={pin}": '{"sha": "487014d9"}', + f"{api}buildroot?ref={pin}": '{"type": "submodule", "sha": "c2d7985b"}', + f"{api}batocera?ref={pin}": '{"type": "submodule", "sha": "487014d9"}', f"{raw}board/r16/retroarch.cfg": 'menu_show_core_updater = "false"\n', f"{raw}package/retroarch/retroarch/retroarch.mk": "RETROARCH_CONF_OPTS = --enable-networking\n", @@ -470,7 +455,7 @@ class KnulliPerBoard(unittest.TestCase): return _Body(self.FILES[path]) return _refuse() - with mock.patch.object(batocera_targets_scraper.urllib.request, "urlopen", urlopen): + with mock.patch("urllib.request.urlopen", urlopen): data = knulli_targets_scraper.Scraper().fetch_targets() self.assertEqual(data["platform"], "knulli") @@ -729,20 +714,11 @@ class TargetsReadThePlatformRevision(unittest.TestCase): pin = "d" * 40 seen: list[str] = [] - class _Body: - def __init__(self, url): - seen.append(url) + def answer(req, **_kw): + seen.append(req.full_url) + return _Body(json.dumps([{"name": "emuDeckRMG.sh"}])) - def __enter__(self): - return self - - def __exit__(self, *_exc): - return False - - def read(self): - return json.dumps([{"name": "emuDeckRMG.sh"}]).encode() - - with mock.patch("urllib.request.urlopen", lambda req, **_kw: _Body(req.full_url)): + with mock.patch("urllib.request.urlopen", answer): cores = emudeck_scraper.Scraper(checkbios_url="pinned")._fetch_installed_emulators(pin) self.assertEqual(cores, ["mupen64plus_next"]) self.assertEqual(len(seen), 1) @@ -812,7 +788,7 @@ class HashScrapersRefuseAnUnknownVersion(unittest.TestCase): def test_mame_raises(self): from scripts.scraper import mame_hash_scraper - with mock.patch.object(mame_hash_scraper.urllib.request, "urlopen", _refuse), \ + with mock.patch("urllib.request.urlopen", _refuse), \ self.assertRaises(RuntimeError): mame_hash_scraper._get_version() diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index b40f69f00..8da13a6e0 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -880,7 +880,7 @@ class TheGitHubTokenComesFromGh(unittest.TestCase): with self._gh(): self.assertEqual( upstream._headers("https://api.github.com/repos/o/n")["Authorization"], - "token gho_fromgh", + "Bearer gho_fromgh", ) os.environ.pop("GITHUB_TOKEN") with self._gh(): diff --git a/tests/test_upstream.py b/tests/test_upstream.py index 820204eab..06f0ab9f7 100644 --- a/tests/test_upstream.py +++ b/tests/test_upstream.py @@ -169,7 +169,7 @@ class TestTokenScope(unittest.TestCase): def test_sent_to_github_api(self): h = upstream._headers("https://api.github.com/repos/o/n/commits") - self.assertEqual(h["Authorization"], "token gho_secret") + self.assertEqual(h["Authorization"], "Bearer gho_secret") def test_sent_to_github_raw(self): h = upstream._headers("https://raw.githubusercontent.com/o/n/sha/a.c") @@ -192,6 +192,16 @@ class TestTokenScope(unittest.TestCase): h = upstream._headers("https://github.com.evil.example/repos/o/n") self.assertNotIn("Authorization", h) + def test_withheld_from_a_url_that_only_names_the_api(self): + h = upstream._headers("https://evil.example/x?next=https://api.github.com/") + self.assertNotIn("Authorization", h) + + def test_withheld_from_the_web_host(self): + # A release download on github.com redirects to asset storage, and + # urllib carries the header across the redirect. + h = upstream._headers("https://github.com/o/n/releases/download/v1/a.zip") + self.assertNotIn("Authorization", h) + def test_absent_token_adds_no_header(self): os.environ.pop("GITHUB_TOKEN", None) h = upstream._headers("https://api.github.com/repos/o/n")