refactor: read retropie module fields in one place

rp_registerModule sources the script: the id, section, flags and repo
are top-level assignments, the last one wins. The platform, target,
launcher, rom folder and export readers each kept their own pattern;
they now share module_fields. Same ids and flags over the 287
scriptmodules at 427e7621.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 16:43:46 +01:00
1 parent 24463647f6
commit 12b00e024b
6 files changed
+40 -39

No files matched your search

+5 -6
View File
@@ -19,6 +19,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from scraper.retropie_modules import module_fields
from scraper.retropie_scraper import script_members
from .base_exporter import BaseExporter
@@ -33,7 +34,6 @@ ARCHIVE = "RetroPie-Setup.tar.gz"
# sentence stops being something a reader uses, so the names are reported
# instead of appended.
_MODULE_ID = re.compile(r'rp_module_id="([^"]+)"')
_MODULE_HELP = re.compile(r'rp_module_help="((?:[^"\\]|\\.)*)"')
_FILENAME = re.compile(r"[A-Za-z0-9][\w.+-]*\.[A-Za-z0-9]{1,5}\b")
# fs-uae's help reads "(e.g, kick13.rom)": e.g and i.e have a file name's shape.
@@ -286,11 +286,11 @@ class Exporter(BaseExporter[str]):
for relative, text in originals.items():
if not relative.startswith("scriptmodules/"):
continue
module = _MODULE_ID.search(text)
module_id = module_fields(text).get("id")
help_text = _MODULE_HELP.search(text)
if not module or not help_text or "bios" not in help_text.group(1).lower():
if not module_id or not help_text or "bios" not in help_text.group(1).lower():
continue
found[relative] = (module.group(1), help_text.group(1))
found[relative] = (module_id, help_text.group(1))
return found
def render(
@@ -481,9 +481,8 @@ class Exporter(BaseExporter[str]):
) -> list[str]:
issues: list[str] = []
for relative, text in produced.items():
module = _MODULE_ID.search(text)
help_text = _MODULE_HELP.search(text)
if not module:
if not module_fields(text).get("id"):
issues.append(f"{relative}: the module lost its id")
if not help_text:
issues.append(f"{relative}: the help string is not closed")
+2 -5
View File
@@ -29,6 +29,7 @@ from pathlib import PurePosixPath
from typing import Any, ClassVar
from .configgen_launchers import Launcher as ConfiggenLauncher
from .retropie_modules import module_field_lines
SCRIPTMODULES = "scriptmodules"
SECTIONS = ("emulators", "libretrocores", "ports")
@@ -68,7 +69,6 @@ _HEREDOC = re.compile(r"(?<!<)<<-?(?!<)\s*['\"]?(\w+)['\"]?")
_VAR = re.compile(r"\$\{([A-Za-z_]\w*)(\[@\])?\}|\$([A-Za-z_]\w*|\d)")
_SUBST = re.compile(r"\$\(([\w.+-]+(?:\$\{md_id\}|\$md_id)?)\)")
_MD_ID_TEST = re.compile(r'^!?\s*\[\[\s*"\$md_id"\s*(==|!=)\s*"?([\w.+-]+)"?\s*\]\]$')
_MODULE_FIELD = re.compile(r'^rp_module_(id|repo)="([^"]*)"', re.MULTILINE)
_EXTENSION = re.compile(r"\.[A-Za-z0-9]{1,5}$")
@@ -207,10 +207,7 @@ class Scripts:
@staticmethod
def _parse(path: str, section: str, text: str) -> Module | None:
lines = text.splitlines()
fields: dict[str, tuple[str, int]] = {}
for found in _MODULE_FIELD.finditer(text):
field_line = text.count("\n", 0, found.start()) + 1
fields.setdefault(found.group(1), (found.group(2), field_line))
fields = module_field_lines(text)
if "id" not in fields:
return None
repo = fields.get("repo")
+21 -1
View File
@@ -1,9 +1,15 @@
"""Which RetroPie scriptmodules a platform enables, as RetroPie-Setup decides."""
"""How RetroPie-Setup reads a scriptmodule: the fields it declares, the platforms that enable it."""
from __future__ import annotations
import re
from collections.abc import Iterable
# scriptmodules/packages.sh rp_registerModule sources the script, so a
# top-level assignment sets the field and the last one wins. RetroPie writes
# each at the start of a line, in double quotes.
_MODULE_FIELD = re.compile(r'^rp_module_(id|section|flags|repo)="([^"]*)"', re.MULTILINE)
# scriptmodules/system.sh: set_platform_defaults starts each platform's flags
# with its own name and getconf LONG_BIT (`x86_64`, `64bit`), then the cpu_*
# and platform_* functions add theirs. A PC takes platform_native, which adds
@@ -25,6 +31,20 @@ PLATFORM_FLAGS: dict[str, set[str]] = {
}
def module_field_lines(text: str) -> dict[str, tuple[str, int]]:
"""(value, line) of the id, section, flags and repo a scriptmodule
declares, by field name."""
return {
found.group(1): (found.group(2), text.count("\n", 0, found.start()) + 1)
for found in _MODULE_FIELD.finditer(text)
}
def module_fields(text: str) -> dict[str, str]:
"""The id, section, flags and repo a scriptmodule declares, by field name."""
return dict(_MODULE_FIELD.findall(text))
def module_enabled(flags: Iterable[str], platform_flags: set[str]) -> bool:
"""Whether RetroPie enables a module whose rp_module_flags are `flags`.
+6 -7
View File
@@ -32,6 +32,7 @@ from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head, fetch
from .retropie_launchers import SCRIPTMODULES
from .retropie_launchers import SECTIONS as _SCRIPT_SECTIONS
from .retropie_launchers import extract_launchers
from .retropie_modules import module_fields
PLATFORM_NAME = "retropie"
@@ -39,7 +40,6 @@ SOURCE_URL = "https://codeload.github.com/RetroPie/RetroPie-Setup/tar.gz/{rev}"
GITHUB_REPO = "RetroPie/RetroPie-Setup"
MAX_ARCHIVE = 64 * 1024 * 1024
_MODULE_ID = re.compile(r'^rp_module_id="([^"]+)"', re.MULTILINE)
# RetroPie updates in place from master, so its release tags stop at the last
# SD image. The version a user runs is the one this script declares.
_VERSION_FILE = "retropie_packages.sh"
@@ -119,13 +119,12 @@ class Scraper(BaseScraper):
self._scripts[relative] = text
if not (is_version_file or is_package):
continue
match = (_VERSION if is_version_file else _MODULE_ID).search(text)
if not match:
continue
if is_version_file:
self._version = match.group(1)
else:
found.add(match.group(1))
version = _VERSION.search(text)
if version:
self._version = version.group(1)
elif module_id := module_fields(text).get("id"):
found.add(module_id)
if not found:
raise ValueError(f"{self.url}: no rp_module_id under {SCRIPTMODULES}/")
+2 -3
View File
@@ -33,7 +33,7 @@ from collections.abc import Iterator
from model.safeparse import parse_untrusted_xml, yaml_load_upstream
from ..retropie_modules import PLATFORM_FLAGS, module_enabled
from ..retropie_modules import PLATFORM_FLAGS, module_enabled, module_fields
from . import Fetcher, SourceError, register
@@ -917,7 +917,6 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]:
# RetroPie
_MODULE_FIELD = re.compile(r'^rp_module_(id|section|flags)="([^"]*)"', re.MULTILINE)
_ADD_EMULATOR = re.compile(r'^\s*addEmulator\s+(\S+)\s+("[^"]*"|\S+)\s+("[^"]*"|\S+)')
_LIST = re.compile(r'(?:local\s+)?(\w+)=\(([^)]*)\)')
_LOOP = re.compile(r'for (\w+) in (.+?); do')
@@ -979,7 +978,7 @@ def retropie(spec: dict, fetcher: Fetcher) -> list[dict]:
if not path.endswith(".sh") or path.count("/") != 2:
continue
text = fetcher.text(key, path)
fields = dict(_MODULE_FIELD.findall(text))
fields = module_fields(text)
if not module_enabled(fields.get("flags", "").split(), platform):
continue
modules.append({"path": path, "id": fields.get("id", ""),
@@ -9,12 +9,11 @@ to determine which platforms each package supports.
from __future__ import annotations
import re
import sys
import tarfile
from datetime import datetime, timezone
from ..retropie_modules import PLATFORM_FLAGS, module_enabled
from ..retropie_modules import PLATFORM_FLAGS, module_enabled, module_fields
from ..retropie_scraper import SOURCE_URL, core_name, fetch_archive, script_members
from . import BaseTargetScraper, target_cli
@@ -38,10 +37,6 @@ ARCH_MAP: dict[str, str] = {
"x86_64": "x86_64",
}
_MODULE_ID_RE = re.compile(r'rp_module_id\s*=\s*["\']([^"\']+)["\']')
_MODULE_FLAGS_RE = re.compile(r'rp_module_flags\s*=\s*["\']([^"\']*)["\']')
def _fetch_archive(url: str) -> bytes:
try:
return fetch_archive(url)
@@ -49,15 +44,6 @@ def _fetch_archive(url: str) -> bytes:
raise RuntimeError(str(exc)) from exc
def _parse_module(content: str) -> tuple[str | None, str]:
"""Return (module_id, flags_string) from a scriptmodule file."""
id_match = _MODULE_ID_RE.search(content)
flags_match = _MODULE_FLAGS_RE.search(content)
module_id = id_match.group(1) if id_match else None
flags = flags_match.group(1) if flags_match else ""
return module_id, flags
class Scraper(BaseTargetScraper):
"""Fetches RetroPie package availability by parsing scriptmodules."""
@@ -99,13 +85,14 @@ class Scraper(BaseTargetScraper):
platform_cores: dict[str, set[str]] = {p: set() for p in PLATFORM_FLAGS}
for filename, content in modules.items():
module_id, flags = _parse_module(content)
fields = module_fields(content)
module_id = fields.get("id")
if not module_id:
print(f" warning: no rp_module_id in {filename}", file=sys.stderr)
continue
# The platform scraper names the package the same way.
for platform in PLATFORM_FLAGS:
if module_enabled(flags.split(), PLATFORM_FLAGS[platform]):
if module_enabled(fields.get("flags", "").split(), PLATFORM_FLAGS[platform]):
platform_cores[platform].add(core_name(module_id))
print(f" parsed {len(modules)} scriptmodules", file=sys.stderr)