refactor: walk gitlab trees in one place

core.upstream.gitlab_tree_entries serves _gitlab_tree, list_gitlinks
and the romfolders listing. The Recalbox systems listing becomes
Scraper.system_folders, so the targets scraper gets the page cap and
refuses an empty listing instead of writing boards without cores.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:00:53 +01:00
1 parent 8bc497cf15
commit 39e6d57fcb
5 files changed
+92 -80

No files matched your search

+35 -36
View File
@@ -1028,33 +1028,44 @@ TREE_PAGE_SIZE = 100
MAX_TREE_PAGES = 50
def _gitlab_tree(
repo: Repo, sha: str, cache_dir: str, offline: bool
) -> tuple[list[str], bool]:
"""GitLab serves its tree in pages, each page cached on its own URL.
def gitlab_tree_entries(
repo: Repo, sha: str, cache_dir: str, offline: bool, *,
path: str | None = None, recursive: bool = True,
) -> tuple[list[dict], bool]:
"""The entries of a GitLab tree at a revision, and whether the listing
is truncated. GitLab serves its tree in pages, each page cached on its
own URL.
A page that cannot be read mid-walk reports the listing as truncated:
the paths already collected are real, but their absence proves nothing.
A page that cannot be read mid-walk, or the page cap, reports the
listing as truncated: the entries already collected are real, but an
absence proves nothing.
"""
paths: list[str] = []
entries: list[dict] = []
scope = "" if path is None else f"&path={path}"
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{project_path(repo)}/repository/tree"
f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}"
f"?ref={sha}{scope}&recursive={'true' if recursive else 'false'}"
f"&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
return paths, True
paths.extend(
entry["path"]
for entry in payload
if isinstance(entry, dict)
and entry.get("type") == "blob"
and entry.get("path")
)
return entries, True
entries.extend(entry for entry in payload if isinstance(entry, dict))
if len(payload) < TREE_PAGE_SIZE:
return paths, False
return paths, True
return entries, False
return entries, True
def _gitlab_tree(
repo: Repo, sha: str, cache_dir: str, offline: bool
) -> tuple[list[str], bool]:
entries, truncated = gitlab_tree_entries(repo, sha, cache_dir, offline)
paths = [
entry["path"] for entry in entries
if entry.get("type") == "blob" and entry.get("path")
]
return paths, truncated
def cache_gitlab_directory(
@@ -1183,24 +1194,12 @@ def list_gitlinks(
once the tree is cached.
"""
if repo.family == "gitlab":
links: dict[str, str] = {}
for page in range(1, MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{project_path(repo)}/repository/tree"
f"?ref={sha}&recursive=true&per_page={TREE_PAGE_SIZE}&page={page}"
)
payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, list):
break
links.update(
(entry["path"], entry["id"])
for entry in payload
if isinstance(entry, dict) and entry.get("type") == "commit"
and entry.get("path") and entry.get("id")
)
if len(payload) < TREE_PAGE_SIZE:
break
return links
entries, _truncated = gitlab_tree_entries(repo, sha, cache_dir, offline)
return {
entry["path"]: entry["id"]
for entry in entries
if entry.get("type") == "commit" and entry.get("path") and entry.get("id")
}
tree_url = _tree_url(repo, sha)
payload = cached_api(tree_url, cache_dir, offline) if tree_url else None
if not isinstance(payload, dict):
+25 -15
View File
@@ -15,6 +15,7 @@ Recalbox verification logic:
from __future__ import annotations
from core import upstream
from model.safeparse import parse_untrusted_xml
from .base_scraper import BaseScraper, BiosRequirement, fetch_bytes, systems_from_requirements
@@ -250,6 +251,29 @@ class Scraper(BaseScraper):
self.tag = tag or _fetch_gitlab_stable_tag()
super().__init__(url=SOURCE_URL.format(tag=self.tag))
def system_folders(self) -> list[str]:
"""The system folders of recalbox-romfs2 at the scraped tag.
An empty listing raises: written as is, it gave every board of the
targets scraper an empty core list.
"""
import json
systems: list[str] = []
for page in range(1, upstream.MAX_TREE_PAGES + 1):
listing = json.loads(fetch_bytes(SYSTEMS_TREE_URL.format(tag=self.tag, page=page)))
systems += [
item["name"] for item in listing
if item.get("type") == "tree" and not item["name"].startswith(".")
]
if len(listing) < upstream.TREE_PAGE_SIZE:
break
else:
raise RuntimeError(f"{SYSTEMS_DIR} at {self.tag} outruns the page cap")
if not systems:
raise RuntimeError(f"no Recalbox system found at {self.tag}")
return systems
def _system_inis(self, systems: list[str]) -> list[str]:
"""Every system's system.ini at the tag, read in batches."""
paths = [f"{SYSTEMS_DIR}/{system}/system.ini" for system in systems]
@@ -296,21 +320,7 @@ class Scraper(BaseScraper):
Read from each system.ini of recalbox-romfs2 at the scraped tag: the
systems ES lists and the cores a user can pick for each.
"""
import json
systems: list[str] = []
page = 1
while True:
listing = json.loads(fetch_bytes(SYSTEMS_TREE_URL.format(tag=self.tag, page=page)))
systems += [
item["name"] for item in listing
if item.get("type") == "tree" and not item["name"].startswith(".")
]
if len(listing) < 100:
break
page += 1
if not systems:
raise RuntimeError(f"no Recalbox system found at {self.tag}")
systems = self.system_folders()
cores: set[str] = set()
standalone: set[str] = set()
libretro: set[str] = set()
+9 -18
View File
@@ -117,24 +117,15 @@ class Fetcher:
self, repo: upstream.Repo, sha: str, directory: str, *, recursive: bool, blobs: bool
) -> list[str]:
directory = directory.strip("/")
paths: list[str] = []
for page in range(1, upstream.MAX_TREE_PAGES + 1):
url = (
f"{repo.api_base}/projects/{upstream.project_path(repo)}/repository/tree"
f"?ref={sha}&path={directory}&recursive={'true' if recursive else 'false'}"
f"&per_page={upstream.TREE_PAGE_SIZE}&page={page}"
)
payload = upstream.cached_api(url, self.cache_dir, self.offline)
if not isinstance(payload, list):
raise SourceError(f"{repo.slug}@{sha[:8]}: {directory} could not be listed")
paths.extend(
entry["path"] for entry in payload
if isinstance(entry, dict) and entry.get("path")
and (entry.get("type") == "blob" or not blobs)
)
if len(payload) < upstream.TREE_PAGE_SIZE:
return sorted(paths)
raise SourceError(f"{repo.slug}@{sha[:8]}: {directory} outruns the page cap")
entries, truncated = upstream.gitlab_tree_entries(
repo, sha, self.cache_dir, self.offline, path=directory, recursive=recursive
)
if truncated:
raise SourceError(f"{repo.slug}@{sha[:8]}: {directory} could not be listed whole")
return sorted(
entry["path"] for entry in entries
if entry.get("path") and (entry.get("type") == "blob" or not blobs)
)
Parser = Callable[[dict, Fetcher], list[dict]]
@@ -21,7 +21,7 @@ from datetime import datetime, timezone
from . import BaseTargetScraper, target_cli
from ..base_scraper import fetch_bytes, fetch_text
from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores
from ..recalbox_scraper import Scraper as PlatformScraper, board_cores
PLATFORM_NAME = "recalbox"
@@ -66,16 +66,7 @@ class Scraper(BaseTargetScraper):
if not boards:
raise RuntimeError(f"no recalbox-*_defconfig in configs/ at {tag}")
systems: list[str] = []
page = 1
while True:
entries = json.loads(fetch_bytes(SYSTEMS_TREE_URL.format(tag=tag, page=page)))
systems += [e["name"] for e in entries
if e.get("type") == "tree" and not e["name"].startswith(".")]
if len(entries) < 100:
break
page += 1
inis = platform._system_inis(systems)
inis = platform._system_inis(platform.system_folders())
targets: dict[str, dict] = {}
for board, name in sorted(boards.items()):
+21
View File
@@ -242,6 +242,27 @@ class RecalboxReadsItsSystemsInBatches(unittest.TestCase):
self.assertEqual(len(cores), 120)
class AnEmptyRecalboxListingStopsTheTargets(unittest.TestCase):
"""The targets scraper kept its own copy of the systems listing, without
the empty check: an empty answer wrote every board with no core."""
def test_the_targets_scraper_refuses_an_empty_listing(self):
from scraper import recalbox_scraper
from scraper.targets import recalbox_targets_scraper as targets
def fetch(url, data=None, headers=None):
if "path=configs" in url:
return b'[{"name": "recalbox-rpi4_64_defconfig"}]'
return b"[]"
scraper = targets.Scraper()
with mock.patch.object(scraper, "pinned_revision", lambda _name: "10.1.1"), \
mock.patch.object(targets, "fetch_bytes", fetch), \
mock.patch.object(recalbox_scraper, "fetch_bytes", fetch), \
self.assertRaisesRegex(RuntimeError, "no Recalbox system"):
scraper.fetch_targets()
class EveryNamedScraperExists(unittest.TestCase):
"""The registry named lakka_targets, a scraper no file defines: a refresh
of stale targets would have failed on its import."""