diff --git a/scripts/scraper/recalbox_romfs.py b/scripts/scraper/recalbox_romfs.py new file mode 100644 index 000000000..c0a50dea1 --- /dev/null +++ b/scripts/scraper/recalbox_romfs.py @@ -0,0 +1,86 @@ +"""How Recalbox's romfs2 reads a system.ini and a board defconfig to build a board's systems.""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Iterator +from dataclasses import dataclass + +# romfs2 systemholder.py reads core.0 to core.19. +CORE_SLOTS = 20 +# romfs2 configin.py: the board is the lowercased rest of the first key +# carrying this prefix, the suffix a system.ini key or section takes. +TARGET_PREFIX = "BR2_PACKAGE_RECALBOX_TARGET_" +# romfs2 inisettings.py loadFile: a key line is tried first, then a section. +_INI_KEY = re.compile(r'^([^#;].*?)\s?=\s?"?(.*?)"?$') +_INI_SECTION = re.compile(r"^\[(.*)\]") +# romfs2 keyvaluesettings.py loadFile, the reader configin.py uses. +_CONFIG_KEY = re.compile(r"^([^#;].*?)\s?=\s?(.+)$") + + +@dataclass(frozen=True) +class SystemIni: + """The sections of one system.ini, and the line of each `
/`.""" + + sections: dict[str, dict[str, str]] + lines: dict[str, int] + + def slots(self, board: str) -> Iterator[str]: + """The `core.N` sections a board builds: `[core.N]` or `[core.N.]` alone.""" + for slot in range(CORE_SLOTS): + section = f"core.{slot}" + if section in self.sections or f"{section}.{board}" in self.sections: + yield section + + def get(self, section: str, key: str, board: str) -> tuple[str | None, int | None]: + """systemholder.py __get: the board's section, then the board's key, + then the plain key.""" + for where, name in ((f"{section}.{board}", key), (section, f"{key}.{board}"), (section, key)): + if name in self.sections.get(where, {}): + return self.sections[where][name], self.lines.get(f"{where}/{name}") + return None, None + + +def read_system_ini(text: str) -> SystemIni: + """One system.ini as romfs2 reads it, the last value of a key kept.""" + sections: dict[str, dict[str, str]] = {} + lines: dict[str, int] = {} + section = "default" + for number, line in enumerate(text.splitlines(), 1): + if key := _INI_KEY.match(line): + name = key.group(1).strip() + sections.setdefault(section, {})[name] = key.group(2).strip() + lines[f"{section}/{name}"] = number + elif header := _INI_SECTION.match(line): + section = header.group(1).strip() + sections.setdefault(section, {}) + return SystemIni(sections, lines) + + +@dataclass(frozen=True) +class Defconfig: + """The board a defconfig builds, and the line of each symbol it sets to y.""" + + board: str | None + enabled: dict[str, int] + + +def read_defconfig(text: str) -> Defconfig: + """One Buildroot defconfig as romfs2 configin.py reads it.""" + values: dict[str, tuple[str, int]] = {} + for number, line in enumerate(text.splitlines(), 1): + if key := _CONFIG_KEY.match(line): + values[key.group(1).strip()] = (key.group(2).strip(), number) + board = next((name[len(TARGET_PREFIX):].lower() for name in values if name.startswith(TARGET_PREFIX)), None) + return Defconfig(board, {name: number for name, (value, number) in values.items() if value == "y"}) + + +def defconfig_boards(defconfigs: Iterable[tuple[str, str]]) -> dict[str, tuple[str, Defconfig]]: + """Each board and the (path, defconfig) that builds it, from (path, text) + pairs. A defconfig that names no Recalbox target builds no board.""" + found: dict[str, tuple[str, Defconfig]] = {} + for path, text in defconfigs: + config = read_defconfig(text) + if config.board: + found[config.board] = (path, config) + return found diff --git a/scripts/scraper/recalbox_scraper.py b/scripts/scraper/recalbox_scraper.py index 7cecc3134..501b8d350 100644 --- a/scripts/scraper/recalbox_scraper.py +++ b/scripts/scraper/recalbox_scraper.py @@ -15,12 +15,15 @@ Recalbox verification logic: from __future__ import annotations +from collections.abc import Container + from core import upstream from model.safeparse import parse_untrusted_xml from .base_scraper import BaseScraper, BiosRequirement, fetch_bytes, systems_from_requirements from .recalbox_launchers import SOURCE_FILES as LAUNCHER_FILES from .recalbox_launchers import LauncherShapeError, extract_launchers +from .recalbox_romfs import read_system_ini PLATFORM_NAME = "recalbox" @@ -138,30 +141,6 @@ BLOBS_QUERY = ( BLOBS_PER_QUERY = 50 -def _ini_sections(text: str) -> dict[str, dict[str, str]]: - """Sections and their key = value lines of one Recalbox system.ini. - - Recalbox's .ini files are not strict INI (a value can run on a bare - line), so only sections and key = value lines are read. - """ - import re - - sections: dict[str, dict[str, str]] = {} - current: dict[str, str] | None = None - for raw in text.splitlines(): - line = raw.strip() - if not line or line.startswith((";", "#")): - continue - header = re.fullmatch(r"\[([^\]]+)\]", line) - if header: - current = sections.setdefault(header.group(1).strip(), {}) - continue - if current is not None and "=" in line: - key, value = line.split("=", 1) - current[key.strip()] = value.strip().strip('"') - return sections - - def _core_names(values: dict[str, str]) -> tuple[set[str], set[str]]: """(cores, standalone) one [core.N] section names.""" emulator = values.get("emulator", "") @@ -180,7 +159,7 @@ def system_ini_libretro(text: str) -> set[str]: return { values.get("core", "") - for section, values in _ini_sections(text).items() + for section, values in read_system_ini(text).sections.items() if re.fullmatch(r"core\.\d+(\.[\w-]+)?", section) and values.get("emulator") == "libretro" and values.get("core") } @@ -193,7 +172,7 @@ def system_ini_name(text: str, folder: str) -> str: (projects/configgen/configgen/generators/libretro/libretroRetroarch.py savesFolder). The folder name stands in where the file names none. """ - return _ini_sections(text).get("system", {}).get("name") or folder + return read_system_ini(text).sections.get("system", {}).get("name") or folder def libretro_systems(inis: dict[str, str]) -> dict[str, list[str]]: @@ -221,7 +200,7 @@ def system_ini_cores(text: str) -> tuple[set[str], set[str]]: cores: set[str] = set() standalone: set[str] = set() - for section, values in _ini_sections(text).items(): + for section, values in read_system_ini(text).sections.items(): if not re.fullmatch(r"core\.\d+(\.[\w-]+)?", section): continue found, alone = _core_names(values) @@ -230,11 +209,7 @@ def system_ini_cores(text: str) -> tuple[set[str], set[str]]: return cores, standalone -# romfs2 systemholder.py reads core.0 to core.19. -CORE_SLOTS = 20 - - -def board_cores(text: str, board: str, enabled: set[str]) -> set[str]: +def board_cores(text: str, board: str, enabled: Container[str]) -> set[str]: """The cores of one system.ini a board's image builds. romfs2 builds each board's list as systemholder.py does: a slot exists @@ -243,21 +218,12 @@ def board_cores(text: str, board: str, enabled: set[str]) -> set[str]: then plain, and a core is kept when the Buildroot package it names is enabled in the board's defconfig. """ - sections = _ini_sections(text) + ini = read_system_ini(text) cores: set[str] = set() - for slot in range(CORE_SLOTS): - plain, own = f"core.{slot}", f"core.{slot}.{board}" - if plain not in sections and own not in sections: - continue - - def read(key: str, plain: str = plain, own: str = own) -> str: - for where, name in ((own, key), (plain, f"{key}.{board}"), (plain, key)): - if name in sections.get(where, {}): - return sections[where][name] - return "" - - if read("package") in enabled: - cores |= _core_names({"emulator": read("emulator"), "core": read("core")})[0] + for slot in ini.slots(board): + if ini.get(slot, "package", board)[0] in enabled: + values = {key: ini.get(slot, key, board)[0] or "" for key in ("emulator", "core")} + cores |= _core_names(values)[0] return cores diff --git a/scripts/scraper/romfolders/es.py b/scripts/scraper/romfolders/es.py index 71ee58ef1..259700fe2 100644 --- a/scripts/scraper/romfolders/es.py +++ b/scripts/scraper/romfolders/es.py @@ -34,6 +34,7 @@ from collections.abc import Iterator from model.safeparse import parse_untrusted_xml, yaml_load_upstream from ..retropie_modules import PLATFORM_FLAGS, module_enabled, module_fields +from ..recalbox_romfs import Defconfig, defconfig_boards, read_system_ini from . import Fetcher, SourceError, register @@ -762,30 +763,6 @@ def esde(spec: dict, fetcher: Fetcher) -> list[dict]: # Recalbox -def _ini_sections(text: str) -> tuple[dict[str, dict[str, str]], dict[str, int]]: - sections: dict[str, dict[str, str]] = {} - lines: dict[str, int] = {} - current: dict[str, str] | None = None - name = "" - for number, raw in enumerate(text.splitlines(), 1): - line = raw.strip() - if not line or line.startswith((";", "#")): - continue - if line.startswith("[") and line.endswith("]"): - name = line[1:-1] - current = sections.setdefault(name, {}) - lines.setdefault(name, number) - elif current is not None and "=" in line: - k, v = line.split("=", 1) - current[k.strip()] = v.strip().strip('"') - lines.setdefault(f"{name}/{k.strip()}", number) - return sections, lines - - -# romfs2 systemholder.py reads core.0 to core.19. -_RECALBOX_CORE_SLOTS = 20 -_RECALBOX_TARGET = "BR2_PACKAGE_RECALBOX_TARGET_" -_ENABLED = re.compile(r"^(BR2_\w+)=y\s*$") # FolderData.cpp IsMatching: a list opening with files: holds whole file # names, each bounded by a space or an end of the list. _FILES_PREFIX = "files:" @@ -801,37 +778,17 @@ def _recalbox_names(listed: str) -> list[str]: return [listed.strip()] if listed.strip() else [] -def _recalbox_boards(fetcher: Fetcher, key: str, configs_dir: str) -> dict[str, tuple[str, dict[str, int]]]: - """Each board's tag and the packages its defconfig enables, with their - lines. The tag is the lowercased BR2_PACKAGE_RECALBOX_TARGET_ - (romfs2 configin.py), the suffix a system.ini key or section takes.""" +def _recalbox_boards(fetcher: Fetcher, key: str, configs_dir: str) -> dict[str, tuple[str, Defconfig]]: + """Each board and the defconfig that builds it, with the lines of the + packages it enables.""" fetcher.cache_directory(key, configs_dir) - boards: dict[str, tuple[str, dict[str, int]]] = {} - for path in fetcher.entries(key, configs_dir): - if not path.endswith("_defconfig"): - continue - enabled: dict[str, int] = {} - for number, line in enumerate(fetcher.text(key, path).splitlines(), 1): - found = _ENABLED.match(line.strip()) - if found: - enabled.setdefault(found.group(1), number) - tags = [name[len(_RECALBOX_TARGET):].lower() for name in enabled if name.startswith(_RECALBOX_TARGET)] - if tags: - boards[tags[0]] = (path, enabled) - if not boards: + found = defconfig_boards( + (path, fetcher.text(key, path)) + for path in fetcher.entries(key, configs_dir) if path.endswith("_defconfig") + ) + if not found: raise SourceError(f"{configs_dir}: no defconfig names a Recalbox target") - return boards - - -def _recalbox_get( - sections: dict[str, dict[str, str]], lines: dict[str, int], section: str, key: str, board: str -) -> tuple[str | None, int | None]: - """systemholder.py __get: the board's section, then the board's key, - then the plain key.""" - for where, name in ((f"{section}.{board}", key), (section, f"{key}.{board}"), (section, key)): - if name in sections.get(where, {}): - return sections[where][name], lines.get(f"{where}/{name}") - return None, None + return found @register("recalbox") @@ -853,7 +810,8 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]: text = fetcher.optional_text(key, path) if text is None: continue - sections, lines = _ini_sections(text) + ini = read_system_ini(text) + sections, lines = ini.sections, ini.lines system = sections.get("system", {}) folder = _strip_prefix(system.get("roms.folder", ""), ["%ROOT%/"]) if not folder: @@ -861,19 +819,17 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]: picks: dict[str, dict] = {} extensions: set[str] = set() names: set[str] = set() - for board, (config_path, enabled) in sorted(boards.items()): + for board, (config_path, config) in sorted(boards.items()): + enabled = config.enabled cores = [] - for slot in range(_RECALBOX_CORE_SLOTS): - section = f"core.{slot}" - if section not in sections and f"{section}.{board}" not in sections: - continue - package, _ = _recalbox_get(sections, lines, section, "package", board) + for section in ini.slots(board): + package, _ = ini.get(section, "package", board) if package not in enabled: continue - priority, priority_line = _recalbox_get(sections, lines, section, "priority", board) - core, core_line = _recalbox_get(sections, lines, section, "core", board) - emulator, _ = _recalbox_get(sections, lines, section, "emulator", board) - exts, _ = _recalbox_get(sections, lines, section, "extensions", board) + priority, priority_line = ini.get(section, "priority", board) + core, core_line = ini.get(section, "core", board) + emulator, _ = ini.get(section, "emulator", board) + exts, _ = ini.get(section, "extensions", board) listed = exts or "" if listed.startswith(_FILES_PREFIX): names.update(_recalbox_names(listed[len(_FILES_PREFIX):])) diff --git a/scripts/scraper/targets/recalbox_targets_scraper.py b/scripts/scraper/targets/recalbox_targets_scraper.py index b8ec8d82b..c723be467 100644 --- a/scripts/scraper/targets/recalbox_targets_scraper.py +++ b/scripts/scraper/targets/recalbox_targets_scraper.py @@ -1,8 +1,9 @@ """Scraper for Recalbox per-board emulator availability. Sources (recalbox/recalbox on GitLab, at the tag platforms/recalbox.yml names): - - configs/recalbox-_defconfig -- the Buildroot packages each image - enables, one `BR2_PACKAGE_=y` line per emulator package + - configs/*_defconfig -- the board each image builds, its + `BR2_PACKAGE_RECALBOX_TARGET_=y` line, and the Buildroot packages + it enables, one `BR2_PACKAGE_=y` line per emulator package - package/recalbox-romfs2/systems//system.ini -- the cores of each system, each `[core.N]` naming the package that builds it, with board overrides (`package.`, `[core.N.]`) @@ -20,18 +21,12 @@ from datetime import datetime, timezone from . import BaseTargetScraper, target_cli from ..base_scraper import fetch_text +from ..recalbox_romfs import defconfig_boards from ..recalbox_scraper import Scraper as PlatformScraper, board_cores, tree_listing PLATFORM_NAME = "recalbox" DEFCONFIG_URL = "https://gitlab.com/recalbox/recalbox/-/raw/{tag}/configs/{name}" -_DEFCONFIG_RE = re.compile(r"^recalbox-(\w+)_defconfig$") -_ENABLED_RE = re.compile(r"^(BR2_PACKAGE_\w+)=y\s*$", re.MULTILINE) - - -def enabled_packages(defconfig: str) -> set[str]: - """The Buildroot packages a defconfig turns on.""" - return set(_ENABLED_RE.findall(defconfig)) def defconfig_arch(defconfig: str) -> str: @@ -52,24 +47,23 @@ class Scraper(BaseTargetScraper): def fetch_targets(self) -> dict: tag = self.pinned_revision(PLATFORM_NAME) platform = PlatformScraper(tag) - boards = { - match.group(1): item["name"] + defconfigs = { + item["name"]: fetch_text(DEFCONFIG_URL.format(tag=tag, name=item["name"])) for item in tree_listing("configs", tag) - if (match := _DEFCONFIG_RE.match(item.get("name", ""))) + if item.get("name", "").endswith("_defconfig") } - if not boards: - raise RuntimeError(f"no recalbox-*_defconfig in configs/ at {tag}") + built = defconfig_boards(defconfigs.items()) + if not built: + raise RuntimeError(f"no defconfig in configs/ at {tag} names a Recalbox target") inis = platform._system_inis(platform.system_folders()) targets: dict[str, dict] = {} - for board, name in sorted(boards.items()): - defconfig = fetch_text(DEFCONFIG_URL.format(tag=tag, name=name)) - enabled = enabled_packages(defconfig) + for board, (name, config) in sorted(built.items()): cores: set[str] = set() for text in inis: - cores |= board_cores(text, board, enabled) - arch = defconfig_arch(defconfig) + cores |= board_cores(text, board, config.enabled) + arch = defconfig_arch(defconfigs[name]) targets[board] = {"architecture": arch, "cores": sorted(cores)} print(f" {board} ({arch}): {len(cores)} cores", file=sys.stderr) diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 26802d0e1..2d4d73b23 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -627,19 +627,18 @@ class RecalboxPerBoard(unittest.TestCase): ) def test_a_board_gets_the_cores_its_defconfig_builds(self): + from scraper.recalbox_romfs import read_defconfig from scraper.recalbox_scraper import board_cores - from scraper.targets.recalbox_targets_scraper import ( - defconfig_arch, - enabled_packages, - ) + from scraper.targets.recalbox_targets_scraper import defconfig_arch - x86 = enabled_packages("BR2_x86_64=y\nBR2_PACKAGE_PCSX2=y\n" - "BR2_PACKAGE_LIBRETRO_PCSX_REARMED=y\n" - "BR2_PACKAGE_LIBRETRO_SWANSTATION=y\n# BR2_PACKAGE_X is not set\n") + x86 = read_defconfig("BR2_x86_64=y\nBR2_PACKAGE_PCSX2=y\n" + "BR2_PACKAGE_LIBRETRO_PCSX_REARMED=y\n" + "BR2_PACKAGE_LIBRETRO_SWANSTATION=y\n# BR2_PACKAGE_X is not set\n").enabled + self.assertNotIn("BR2_PACKAGE_X", x86) self.assertEqual(board_cores(self.SYSTEM_INI, "x86_64", x86), {"pcsx2", "pcsx_rearmed", "swanstation"}) - rpi3 = enabled_packages("BR2_arm=y\nBR2_PACKAGE_LIBRETRO_PCSX_REARMED_NEON=y\n" - "BR2_PACKAGE_LIBRETRO_DUCKSTATION=y\n") + rpi3 = read_defconfig("BR2_arm=y\nBR2_PACKAGE_LIBRETRO_PCSX_REARMED_NEON=y\n" + "BR2_PACKAGE_LIBRETRO_DUCKSTATION=y\n").enabled self.assertEqual(board_cores(self.SYSTEM_INI, "rpi3", rpi3), {"pcsx_rearmed", "duckstation"}) self.assertEqual(defconfig_arch("BR2_arm=y\n"), "armhf") @@ -659,6 +658,20 @@ class RecalboxPerBoard(unittest.TestCase): self.assertEqual(board_cores(ini, "x86_64", enabled), {"gambatte", "bsnes"}) self.assertEqual(board_cores(ini, "rpi3", enabled), {"gambatte"}) + def test_a_board_is_the_target_its_defconfig_names(self): + """romfs2 configin.py takes the board from the first + BR2_PACKAGE_RECALBOX_TARGET_ key, not from the file name, and the + target list and the rom folders read the same rule.""" + from scraper.recalbox_romfs import defconfig_boards + + found = defconfig_boards([ + ("configs/recalbox-pi3_defconfig", "BR2_PACKAGE_RECALBOX_TARGET_RPI3=y\nBR2_arm=y\n"), + ("configs/other_defconfig", "BR2_x86_64=y\n"), + ]) + self.assertEqual(list(found), ["rpi3"]) + path, config = found["rpi3"] + self.assertEqual((path, config.enabled["BR2_arm"]), ("configs/recalbox-pi3_defconfig", 2)) + class RetroPieModuleFlags(unittest.TestCase): """The RetroPie target list read flags as requirements and libretro alone.